2
0
mirror of https://github.com/orbitdb/orbitdb.git synced 2025-03-30 15:08:28 +00:00
haad 8f990e0ccc Immutable ipfs-log
Use immutable ipfs-log.
Simplify internals.
Remove obsolete dependencies.
Update dependencies.
Use @dignifiedquire's mapSeries for Promises.
Split tests to individual stores.
Improve tests.
Fix build process.
Build size down to 121kb.
Fix benchmarks and examples.
Move Cache to Stores (and to its own module).
2017-03-21 18:13:58 +01:00

14498 lines
459 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var OrbitDB =
/******/ (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;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // 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 = 191);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _defineProperty = __webpack_require__(56);
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = 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;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
/***/ }),
/* 2 */
/***/ (function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(46)('wks')
, uid = __webpack_require__(33)
, Symbol = __webpack_require__(4).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(18);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(17)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, core = __webpack_require__(2)
, ctx = __webpack_require__(22)
, hide = __webpack_require__(11)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(5)
, IE8_DOM_DEFINE = __webpack_require__(61)
, toPrimitive = __webpack_require__(48)
, dP = Object.defineProperty;
exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(106), __esModule: true };
/***/ }),
/* 10 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(8)
, createDesc = __webpack_require__(30);
module.exports = __webpack_require__(6) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(62)
, defined = __webpack_require__(39);
module.exports = function(it){
return IObject(defined(it));
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(111), __esModule: true };
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(110), __esModule: true };
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _setPrototypeOf = __webpack_require__(101);
var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
var _create = __webpack_require__(99);
var _create2 = _interopRequireDefault(_create);
var _typeof2 = __webpack_require__(58);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _typeof2 = __webpack_require__(58);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
/***/ }),
/* 17 */
/***/ (function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ }),
/* 18 */
/***/ (function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(68)
, enumBugKeys = __webpack_require__(41);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(104)
var ieee754 = __webpack_require__(154)
var isArray = __webpack_require__(157)
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(exports, __webpack_require__(35)))
/***/ }),
/* 21 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(38);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ }),
/* 23 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function drain (op, done) {
var read, abort
function sink (_read) {
read = _read
if(abort) return sink.abort()
//this function is much simpler to write if you
//just use recursion, but by using a while loop
//we do not blow the stack if the stream happens to be sync.
;(function next() {
var loop = true, cbed = false
while(loop) {
cbed = false
read(null, function (end, data) {
cbed = true
if(end = end || abort) {
loop = false
if(done) done(end === true ? null : end)
else if(end && end !== true)
throw end
}
else if(op && false === op(data) || abort) {
loop = false
read(abort || true, done || function () {})
}
else if(!loop){
next()
}
})
if(!cbed) {
loop = false
return
}
}
})()
}
sink.abort = function (err, cb) {
if('function' == typeof err)
cb = err, err = true
abort = err || true
if(read) return read(abort, cb || function () {})
}
return sink
}
/***/ }),
/* 25 */
/***/ (function(module, exports) {
module.exports = function prop (key) {
return key && (
'string' == typeof key
? function (data) { return data[key] }
: 'object' === typeof key && 'function' === typeof key.exec //regexp
? function (data) { var v = key.exec(data); return v && v[0] }
: key
)
}
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _promise = __webpack_require__(27);
var _promise2 = _interopRequireDefault(_promise);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventEmitter = __webpack_require__(36).EventEmitter;
var Log = __webpack_require__(90);
var Index = __webpack_require__(98);
var DefaultOptions = {
Index: Index,
maxHistory: 256
};
var Store = function () {
function Store(ipfs, id, dbname) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
(0, _classCallCheck3.default)(this, Store);
this.id = id;
this.dbname = dbname;
this.events = new EventEmitter();
var opts = (0, _assign2.default)({}, DefaultOptions);
(0, _assign2.default)(opts, options);
this.options = opts;
this._ipfs = ipfs;
this._index = new this.options.Index(this.id);
this._oplog = Log.create(this._ipfs);
this._lastWrite = [];
}
(0, _createClass3.default)(Store, [{
key: 'loadHistory',
value: function loadHistory(hash) {
var _this = this;
if (this._lastWrite.includes(hash)) return _promise2.default.resolve([]);
if (hash) this._lastWrite.push(hash);
if (hash && this.options.maxHistory > 0) {
this.events.emit('load', this.dbname, hash);
return Log.fromMultihash(this._ipfs, hash, this.options.maxHistory, this._onLoadProgress.bind(this)).then(function (log) {
return Log.join(_this._ipfs, _this._oplog, log);
}).then(function (merged) {
_this._index.updateIndex(_this._oplog);
_this.events.emit('load.end', _this.dbname);
_this.events.emit('ready', _this.dbname);
return _this;
});
} else {
this.events.emit('ready', this.dbname);
return _promise2.default.resolve(this);
}
}
}, {
key: 'sync',
value: function sync(hash) {
var _this2 = this;
if (!hash || this._lastWrite.includes(hash)) return _promise2.default.resolve(hash);
var newItems = [];
if (hash) this._lastWrite.push(hash);
this.events.emit('sync', this.dbname);
var startTime = new Date().getTime();
return Log.fromMultihash(this._ipfs, hash, this.options.maxHistory, this._onLoadProgress.bind(this)).then(function (log) {
_this2._oplog = Log.join(_this2._ipfs, _this2._oplog, log);
_this2._index.updateIndex(_this2._oplog);
_this2.events.emit('load.end', _this2.dbname);
_this2.events.emit('synced', _this2.dbname);
}).then(function () {
return Log.toMultihash(_this2._ipfs, _this2._oplog);
});
}
}, {
key: '_addOperation',
value: function _addOperation(data) {
var _this3 = this;
var result = void 0,
logHash = void 0;
if (this._oplog) {
return Log.append(this._ipfs, this._oplog, data).then(function (res) {
return _this3._oplog = res;
}).then(function () {
return Log.toMultihash(_this3._ipfs, _this3._oplog);
}).then(function (hash) {
return logHash = hash;
}).then(function () {
return _this3._lastWrite.push(logHash);
}).then(function () {
return _this3._index.updateIndex(_this3._oplog, [result]);
}).then(function () {
return _this3.events.emit('write', _this3.dbname, logHash);
}).then(function () {
return _this3.events.emit('data', _this3.dbname, _this3._oplog.items[_this3._oplog.items.length - 1].hash);
}).then(function () {
return _this3._oplog.items[_this3._oplog.items.length - 1].hash;
});
}
}
}, {
key: '_onLoadProgress',
value: function _onLoadProgress(hash, entry, parent, depth) {
this.events.emit('load.progress', this.dbname, depth);
}
}]);
return Store;
}();
module.exports = Store;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(113), __esModule: true };
/***/ }),
/* 28 */
/***/ (function(module, exports) {
module.exports = true;
/***/ }),
/* 29 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 30 */
/***/ (function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(8).f
, has = __webpack_require__(10)
, TAG = __webpack_require__(3)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(39);
module.exports = function(it){
return Object(defined(it));
};
/***/ }),
/* 33 */
/***/ (function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
exports.nextTick = function nextTick(fn) {
setTimeout(fn, 0);
};
exports.platform = exports.arch =
exports.execPath = exports.title = 'browser';
exports.pid = 1;
exports.browser = true;
exports.env = {};
exports.argv = [];
exports.binding = function (name) {
throw new Error('No such module. (Possibly not yet loaded)')
};
(function () {
var cwd = '/';
var path;
exports.cwd = function () { return cwd };
exports.chdir = function (dir) {
if (!path) path = __webpack_require__(160);
cwd = path.resolve(dir, cwd);
};
})();
exports.exit = exports.kill =
exports.umask = exports.dlopen =
exports.uptime = exports.memoryUsage =
exports.uvCounters = function() {};
exports.features = {};
/***/ }),
/* 35 */
/***/ (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 || Function("return this")() || (1,eval)("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;
/***/ }),
/* 36 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
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.
EventEmitter.defaultMaxListeners = 10;
// 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(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(105), __esModule: true };
/***/ }),
/* 38 */
/***/ (function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 39 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(18)
, document = __webpack_require__(4).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ }),
/* 41 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(5)
, dPs = __webpack_require__(132)
, enumBugKeys = __webpack_require__(41)
, IE_PROTO = __webpack_require__(45)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(40)('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(60).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 43 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(7)
, core = __webpack_require__(2)
, fails = __webpack_require__(17);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(46)('keys')
, uid = __webpack_require__(33);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ }),
/* 47 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(18);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, core = __webpack_require__(2)
, LIBRARY = __webpack_require__(28)
, wksExt = __webpack_require__(50)
, defineProperty = __webpack_require__(8).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(3);
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var drain = __webpack_require__(24)
module.exports = function reduce (reducer, acc, cb ) {
if(!cb) cb = acc, acc = null
var sink = drain(function (data) {
acc = reducer(acc, data)
}, function (err) {
cb(err, acc)
})
if (arguments.length === 2)
return function (source) {
source(null, function (end, data) {
//if ended immediately, and no initial...
if(end) return cb(end === true ? null : end)
acc = data; sink(source)
})
}
else
return sink
}
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var abortCb = __webpack_require__(78)
module.exports = function values (array, onAbort) {
if(!array)
return function (abort, cb) {
if(abort) return abortCb(cb, abort, onAbort)
return cb(true)
}
if(!Array.isArray(array))
array = Object.keys(array).map(function (k) {
return array[k]
})
var i = 0
return function (abort, cb) {
if(abort)
return abortCb(cb, abort, onAbort)
if(i >= array.length)
cb(true)
else
cb(null, array[i++])
}
}
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var tester = __webpack_require__(79)
module.exports = function filter (test) {
//regexp
test = tester(test)
return function (read) {
return function next (end, cb) {
var sync, loop = true
while(loop) {
loop = false
sync = true
read(end, function (end, data) {
if(!end && !test(data))
return sync ? loop = true : next(end, cb)
cb(end, data)
})
sync = false
}
}
}
}
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _defineProperty2 = __webpack_require__(103);
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _iterator2 = __webpack_require__(57);
var _iterator3 = _interopRequireDefault(_iterator2);
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = __webpack_require__(26);
var EventIndex = __webpack_require__(55);
var EventStore = function (_Store) {
(0, _inherits3.default)(EventStore, _Store);
function EventStore(ipfs, id, dbname) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
(0, _classCallCheck3.default)(this, EventStore);
if (options.Index === undefined) (0, _assign2.default)(options, { Index: EventIndex });
return (0, _possibleConstructorReturn3.default)(this, (EventStore.__proto__ || (0, _getPrototypeOf2.default)(EventStore)).call(this, ipfs, id, dbname, options));
}
(0, _createClass3.default)(EventStore, [{
key: 'add',
value: function add(data) {
return this._addOperation({
op: 'ADD',
key: null,
value: data,
meta: {
ts: new Date().getTime()
}
});
}
}, {
key: 'get',
value: function get(hash) {
return this.iterator({ gte: hash, limit: 1 }).collect()[0];
}
}, {
key: 'iterator',
value: function iterator(options) {
var _iterator;
var messages = this._query(options);
var currentIndex = 0;
var iterator = (_iterator = {}, (0, _defineProperty3.default)(_iterator, _iterator3.default, function () {
return this;
}), (0, _defineProperty3.default)(_iterator, 'next', function next() {
var item = { value: null, done: true };
if (currentIndex < messages.length) {
item = { value: messages[currentIndex], done: false };
currentIndex++;
}
return item;
}), (0, _defineProperty3.default)(_iterator, 'collect', function collect() {
return messages;
}), _iterator);
return iterator;
}
}, {
key: '_query',
value: function _query(opts) {
if (!opts) opts = {};
var amount = opts.limit ? opts.limit > -1 ? opts.limit : this._index.get().length : 1; // Return 1 if no limit is provided
var events = this._index.get().slice();
var result = [];
if (opts.gt || opts.gte) {
// Greater than case
result = this._read(events, opts.gt ? opts.gt : opts.gte, amount, opts.gte ? true : false);
} else {
// Lower than and lastN case, search latest first by reversing the sequence
result = this._read(events.reverse(), opts.lt ? opts.lt : opts.lte, amount, opts.lte || !opts.lt).reverse();
}
return result;
}
}, {
key: '_read',
value: function _read(ops, hash, amount, inclusive) {
// Find the index of the gt/lt hash, or start from the beginning of the array if not found
var index = ops.map(function (e) {
return e.hash;
}).indexOf(hash);
var startIndex = Math.max(index, 0);
// If gte/lte is set, we include the given hash, if not, start from the next element
startIndex += inclusive ? 0 : 1;
// Slice the array to its requested size
var res = ops.slice(startIndex).slice(0, amount);
return res;
}
}]);
return EventStore;
}(Store);
module.exports = EventStore;
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventIndex = function () {
function EventIndex() {
(0, _classCallCheck3.default)(this, EventIndex);
this._index = {};
}
(0, _createClass3.default)(EventIndex, [{
key: 'get',
value: function get() {
var _this = this;
return (0, _keys2.default)(this._index).map(function (f) {
return _this._index[f];
});
}
}, {
key: 'updateIndex',
value: function updateIndex(oplog) {
var _this2 = this;
oplog.items.reduce(function (handled, item) {
if (!handled.includes(item.hash) && !_this2._index[item.hash]) {
handled.push(item.hash);
if (item.payload.op === 'ADD') _this2._index[item.hash] = item;
}
return handled;
}, []);
}
}]);
return EventIndex;
}();
module.exports = EventIndex;
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(108), __esModule: true };
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(115), __esModule: true };
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _iterator = __webpack_require__(57);
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = __webpack_require__(102);
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(21)
, TAG = __webpack_require__(3)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(4).document && document.documentElement;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(6) && !__webpack_require__(17)(function(){
return Object.defineProperty(__webpack_require__(40)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(21);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(28)
, $export = __webpack_require__(7)
, redefine = __webpack_require__(69)
, hide = __webpack_require__(11)
, has = __webpack_require__(10)
, Iterators = __webpack_require__(23)
, $iterCreate = __webpack_require__(125)
, setToStringTag = __webpack_require__(31)
, getPrototypeOf = __webpack_require__(67)
, ITERATOR = __webpack_require__(3)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(29)
, createDesc = __webpack_require__(30)
, toIObject = __webpack_require__(12)
, toPrimitive = __webpack_require__(48)
, has = __webpack_require__(10)
, IE8_DOM_DEFINE = __webpack_require__(61)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(12)
, gOPN = __webpack_require__(66).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(68)
, hiddenKeys = __webpack_require__(41).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(10)
, toObject = __webpack_require__(32)
, IE_PROTO = __webpack_require__(45)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(10)
, toIObject = __webpack_require__(12)
, arrayIndexOf = __webpack_require__(118)(false)
, IE_PROTO = __webpack_require__(45)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(11);
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(22)
, invoke = __webpack_require__(121)
, html = __webpack_require__(60)
, cel = __webpack_require__(40)
, global = __webpack_require__(4)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(21)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(47)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 72 */
/***/ (function(module, exports) {
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__(137)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(63)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(140);
var global = __webpack_require__(4)
, hide = __webpack_require__(11)
, Iterators = __webpack_require__(23)
, TO_STRING_TAG = __webpack_require__(3)('toStringTag');
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var sources = __webpack_require__(173)
var sinks = __webpack_require__(167)
var throughs = __webpack_require__(179)
exports = module.exports = __webpack_require__(163)
for(var k in sources)
exports[k] = sources[k]
for(var k in throughs)
exports[k] = throughs[k]
for(var k in sinks)
exports[k] = sinks[k]
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var abortCb = __webpack_require__(78)
module.exports = function once (value, onAbort) {
return function (abort, cb) {
if(abort)
return abortCb(cb, abort, onAbort)
if(value != null) {
var _value = value; value = null
cb(null, _value)
} else
cb(true)
}
}
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function id (e) { return e }
var prop = __webpack_require__(25)
var filter = __webpack_require__(53)
//drop items you have already seen.
module.exports = function unique (field, invert) {
field = prop(field) || id
var seen = {}
return filter(function (data) {
var key = field(data)
if(seen[key]) return !!invert //false, by default
else seen[key] = true
return !invert //true by default
})
}
/***/ }),
/* 78 */
/***/ (function(module, exports) {
module.exports = function abortCb(cb, abort, onAbort) {
cb(abort)
onAbort && onAbort(abort === true ? null: abort)
return
}
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var prop = __webpack_require__(25)
function id (e) { return e }
module.exports = function tester (test) {
return (
'object' === typeof test && 'function' === typeof test.test //regexp
? function (data) { return test.test(data) }
: prop (test) || id
)
}
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, 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(window, 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__(186);
exports.setImmediate = setImmediate;
exports.clearImmediate = clearImmediate;
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var _stringify = __webpack_require__(37);
var _stringify2 = _interopRequireDefault(_stringify);
var _promise = __webpack_require__(27);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pull = __webpack_require__(75);
var BlobStore = __webpack_require__(153);
var Lock = __webpack_require__(158);
var filePath = void 0;
var store = void 0;
var cache = {};
var lock = new Lock();
var Cache = function () {
function Cache() {
(0, _classCallCheck3.default)(this, Cache);
}
(0, _createClass3.default)(Cache, null, [{
key: 'set',
value: function set(key, value) {
return new _promise2.default(function (resolve, reject) {
if (cache[key] === value) return resolve();
cache[key] = value;
if (filePath && store) {
lock(filePath, function (release) {
// console.log("write cache:", filePath, JSON.stringify(cache, null, 2))
pull(pull.values([cache]), pull.map(function (v) {
return (0, _stringify2.default)(v, null, 2);
}), store.write(filePath, release(function (err) {
if (err) {
return reject(err);
}
resolve();
})));
});
} else {
resolve();
}
});
}
}, {
key: 'get',
value: function get(key) {
return cache[key];
}
}, {
key: 'loadCache',
value: function loadCache(cachePath) {
var cacheFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'orbit-db.cache';
cache = {};
if (!cachePath) return _promise2.default.resolve();
// console.log("cache data:", cachePath)
store = new BlobStore(cachePath);
filePath = cacheFile;
return new _promise2.default(function (resolve, reject) {
// console.log("load cache:", cacheFile)
store.exists(cacheFile, function (err, exists) {
if (err || !exists) {
return resolve();
}
lock(cacheFile, function (release) {
pull(store.read(cacheFile), pull.collect(release(function (err, res) {
if (err) {
return reject(err);
}
cache = JSON.parse(Buffer.concat(res).toString() || '{}');
resolve();
})));
});
});
});
}
}, {
key: 'reset',
value: function reset() {
cache = {};
store = null;
}
}]);
return Cache;
}();
module.exports = Cache;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = __webpack_require__(26);
var CounterIndex = __webpack_require__(93);
var CounterStore = function (_Store) {
(0, _inherits3.default)(CounterStore, _Store);
function CounterStore(ipfs, id, dbname) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
(0, _classCallCheck3.default)(this, CounterStore);
if (!options.Index) (0, _assign2.default)(options, { Index: CounterIndex });
return (0, _possibleConstructorReturn3.default)(this, (CounterStore.__proto__ || (0, _getPrototypeOf2.default)(CounterStore)).call(this, ipfs, id, dbname, options));
}
(0, _createClass3.default)(CounterStore, [{
key: 'inc',
value: function inc(amount) {
var counter = this._index.get();
if (counter) {
counter.increment(amount);
return this._addOperation({
op: 'COUNTER',
key: null,
value: counter.payload,
meta: {
ts: new Date().getTime()
}
});
}
}
}, {
key: 'value',
get: function get() {
return this._index.get().value;
}
}]);
return CounterStore;
}(Store);
module.exports = CounterStore;
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = __webpack_require__(26);
var DocumentIndex = __webpack_require__(94);
var DocumentStore = function (_Store) {
(0, _inherits3.default)(DocumentStore, _Store);
function DocumentStore(ipfs, id, dbname, options) {
(0, _classCallCheck3.default)(this, DocumentStore);
if (!options) options = {};
if (!options.indexBy) (0, _assign2.default)(options, { indexBy: '_id' });
if (!options.Index) (0, _assign2.default)(options, { Index: DocumentIndex });
return (0, _possibleConstructorReturn3.default)(this, (DocumentStore.__proto__ || (0, _getPrototypeOf2.default)(DocumentStore)).call(this, ipfs, id, dbname, options));
}
(0, _createClass3.default)(DocumentStore, [{
key: 'get',
value: function get(key) {
var _this2 = this;
return (0, _keys2.default)(this._index._index).filter(function (e) {
return e.indexOf(key) !== -1;
}).map(function (e) {
return _this2._index.get(e);
});
}
}, {
key: 'query',
value: function query(mapper) {
var _this3 = this;
return (0, _keys2.default)(this._index._index).map(function (e) {
return _this3._index.get(e);
}).filter(function (e) {
return mapper(e);
});
}
}, {
key: 'put',
value: function put(doc) {
return this._addOperation({
op: 'PUT',
key: doc[this.options.indexBy],
value: doc,
meta: {
ts: new Date().getTime()
}
});
}
}, {
key: 'del',
value: function del(key) {
return this._addOperation({
op: 'DEL',
key: key,
value: null,
meta: {
ts: new Date().getTime()
}
});
}
}]);
return DocumentStore;
}(Store);
module.exports = DocumentStore;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventStore = __webpack_require__(54);
var FeedIndex = __webpack_require__(95);
var FeedStore = function (_EventStore) {
(0, _inherits3.default)(FeedStore, _EventStore);
function FeedStore(ipfs, id, dbname, options) {
(0, _classCallCheck3.default)(this, FeedStore);
if (!options) options = {};
if (!options.Index) (0, _assign2.default)(options, { Index: FeedIndex });
return (0, _possibleConstructorReturn3.default)(this, (FeedStore.__proto__ || (0, _getPrototypeOf2.default)(FeedStore)).call(this, ipfs, id, dbname, options));
}
(0, _createClass3.default)(FeedStore, [{
key: 'remove',
value: function remove(hash) {
var operation = {
op: 'DEL',
key: null,
value: hash,
meta: {
ts: new Date().getTime()
}
};
return this._addOperation(operation);
}
}]);
return FeedStore;
}(EventStore);
module.exports = FeedStore;
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = __webpack_require__(26);
var KeyValueIndex = __webpack_require__(96);
var KeyValueStore = function (_Store) {
(0, _inherits3.default)(KeyValueStore, _Store);
function KeyValueStore(ipfs, id, dbname, options) {
(0, _classCallCheck3.default)(this, KeyValueStore);
var opts = (0, _assign2.default)({}, { Index: KeyValueIndex });
(0, _assign2.default)(opts, options);
return (0, _possibleConstructorReturn3.default)(this, (KeyValueStore.__proto__ || (0, _getPrototypeOf2.default)(KeyValueStore)).call(this, ipfs, id, dbname, opts));
}
(0, _createClass3.default)(KeyValueStore, [{
key: 'get',
value: function get(key) {
return this._index.get(key);
}
}, {
key: 'set',
value: function set(key, data) {
return this.put(key, data);
}
}, {
key: 'put',
value: function put(key, data) {
return this._addOperation({
op: 'PUT',
key: key,
value: data,
meta: {
ts: new Date().getTime()
}
});
}
}, {
key: 'del',
value: function del(key) {
return this._addOperation({
op: 'DEL',
key: key,
value: null,
meta: {
ts: new Date().getTime()
}
});
}
}]);
return KeyValueStore;
}(Store);
module.exports = KeyValueStore;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(97);
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isEqual = __webpack_require__(88).isEqual;
var GCounter = function () {
function GCounter(id, payload) {
(0, _classCallCheck3.default)(this, GCounter);
this.id = id;
this._counters = payload ? payload : {};
this._counters[this.id] = this._counters[this.id] ? this._counters[this.id] : 0;
}
(0, _createClass3.default)(GCounter, [{
key: 'increment',
value: function increment(amount) {
if (!amount) amount = 1;
this._counters[this.id] = this._counters[this.id] + amount;
}
}, {
key: 'compare',
value: function compare(other) {
if (other.id !== this.id) return false;
return isEqual(other._counters, this._counters);
}
}, {
key: 'merge',
value: function merge(other) {
var _this = this;
(0, _keys2.default)(other._counters).forEach(function (f) {
_this._counters[f] = Math.max(_this._counters[f] ? _this._counters[f] : 0, other._counters[f]);
});
}
}, {
key: 'value',
get: function get() {
var _this2 = this;
return (0, _keys2.default)(this._counters).map(function (f) {
return _this2._counters[f];
}).reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
}
}, {
key: 'payload',
get: function get() {
return { id: this.id, counters: this._counters };
}
}], [{
key: 'from',
value: function from(payload) {
return new GCounter(payload.id, payload.counters);
}
}]);
return GCounter;
}();
module.exports = GCounter;
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getOwnPropertyNames = __webpack_require__(100);
var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.isEqual = function (a, b) {
var propsA = (0, _getOwnPropertyNames2.default)(a);
var propsB = (0, _getOwnPropertyNames2.default)(b);
if (propsA.length !== propsB.length) return false;
for (var i = 0; i < propsA.length; i++) {
var prop = propsA[i];
if (a[prop] !== b[prop]) return false;
}
return true;
};
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var _stringify = __webpack_require__(37);
var _stringify2 = _interopRequireDefault(_stringify);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Entry = function () {
function Entry() {
(0, _classCallCheck3.default)(this, Entry);
}
(0, _createClass3.default)(Entry, null, [{
key: "create",
/**
* Create an Entry
* @param {IPFS} ipfs - An IPFS instance
* @param {string|Buffer|Object|Array} data - Data of the entry to be added
* @param {Array<Entry>} [next=[]] Parents of the entry
* @example
* const entry = await Entry.create(ipfs, 'hello')
* console.log(entry)
* // { hash: "Qm...Foo", payload: "hello", next: [] }
* @returns {Promise<Entry>}
*/
value: function create(ipfs) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var next = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!ipfs) throw new Error("Entry requires ipfs instance");
// convert single objects to an array and entry objects to single hashes
var nexts = next !== null && Array.isArray(next) ? next.filter(function (e) {
return e !== undefined;
}).map(function (e) {
return e.hash ? e.hash : e;
}) : [next !== null && next.hash ? next.hash : next];
var entry = {
hash: null, // "Qm...Foo", we'll set the hash after ipfsfying the data structure,
payload: data, // Can be any JSON.stringifyable data
next: nexts // Array of IPFS hashes
};
return Entry.toMultihash(ipfs, entry).then(function (hash) {
entry.hash = hash;
return entry;
});
}
/**
* Get the multihash of an Entry
* @param {IPFS} [ipfs] An IPFS instance
* @param {string|Buffer|Object|Array} [data] Data of the entry to be added
* @param {Array<Entry>} [next=[]] Parents of the entry
* @example
* const hash = await Entry.toMultihash(ipfs, entry)
* console.log(hash)
* // "Qm...Foo"
* @returns {Promise<string>}
*/
}, {
key: "toMultihash",
value: function toMultihash(ipfs, entry) {
if (!ipfs) throw new Error("Entry requires ipfs instance");
var data = new Buffer((0, _stringify2.default)(entry));
return ipfs.object.put(data).then(function (res) {
return res.toJSON().multihash;
});
}
/**
* Create an Entry from a multihash
* @param {IPFS} [ipfs] An IPFS instance
* @param {string} [hash] Multihash to create an Entry from
* @example
* const hash = await Entry.fromMultihash(ipfs, "Qm...Foo")
* console.log(hash)
* // { hash: "Qm...Foo", payload: "hello", next: [] }
* @returns {Promise<Entry>}
*/
}, {
key: "fromMultihash",
value: function fromMultihash(ipfs, hash) {
if (!ipfs) throw new Error("Entry requires ipfs instance");
if (!hash) throw new Error("Invalid hash: " + hash);
return ipfs.object.get(hash, { enc: 'base58' }).then(function (obj) {
return JSON.parse(obj.toJSON().data);
}).then(function (data) {
var entry = {
hash: hash,
payload: data.payload,
next: data.next
};
return entry;
});
}
/**
* Check if an entry has another entry as its child
* @param {Entry} [entry1] Entry to check from
* @param {Entry} [entry2] Child
* @returns {boolean}
*/
}, {
key: "hasChild",
value: function hasChild(entry1, entry2) {
return entry1.next.includes(entry2.hash);
}
/**
* Check if an entry equals another entry
* @param {Entry} a
* @param {Entry} b
* @returns {boolean}
*/
}, {
key: "compare",
value: function compare(a, b) {
return a.hash === b.hash;
}
/**
* @alias compare
*/
}, {
key: "isEqual",
value: function isEqual(a, b) {
return a.hash === b.hash;
}
}]);
return Entry;
}();
module.exports = Entry;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var _promise = __webpack_require__(27);
var _promise2 = _interopRequireDefault(_promise);
var _stringify = __webpack_require__(37);
var _stringify2 = _interopRequireDefault(_stringify);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Entry = __webpack_require__(89);
var mapSeries = __webpack_require__(91);
/**
* ipfs-log
*
* @example
* // https://github.com/haadcode/ipfs-log/blob/master/examples/log.js
* const IPFS = require('ipfs-daemon')
* const Log = require('ipfs-log')
* const ipfs = new IPFS()
*
* ipfs.on('ready', () => {
* const log1 = Log.create(ipfs, ['one'])
* const log2 = Log.create(ipfs, [{ two: 'hello' }, { ok: true }])
* const out = Log.join(ipfs, log2, log2)
* .collect()
* .map((e) => e.payload)
* .join('\n')
* console.log(out)
* // ['one', '{ two: 'hello' }', '{ ok: true }']
* })
*/
var Log = function () {
function Log(ipfs, entries, heads) {
(0, _classCallCheck3.default)(this, Log);
this._entries = entries || [];
this._heads = heads || LogUtils._findHeads(this) || [];
}
/**
* Returns the items in the log
* @returns {Array<Entry>}
*/
(0, _createClass3.default)(Log, [{
key: 'get',
/**
* Find a log entry
* @param {string} [hash] [The multihash of the entry]
* @returns {Entry|undefined}
*/
value: function get(hash) {
return this.items.find(function (e) {
return e.hash === hash;
});
}
/**
* Returns the log entries as a formatted string
* @example
* two
* └─one
* └─three
* @param {boolean} [withHash=false] - If set to 'true', the hash of the entry is included
* @returns {string}
*/
}, {
key: 'toString',
value: function toString(withHash) {
var _this = this;
return this.items.slice().reverse().map(function (e, idx) {
var parents = LogUtils._findParents(_this, e);
var len = parents.length;
var padding = new Array(Math.max(len - 1, 0));
padding = len > 1 ? padding.fill(' ') : padding;
padding = len > 0 ? padding.concat(['└─']) : padding;
return padding.join('') + (withHash ? e.hash + ' ' : '') + e.payload;
}).join('\n');
}
/**
* Get the log in JSON format
* @returns {Object<{heads}>}
*/
}, {
key: 'toJSON',
value: function toJSON() {
return { heads: this.heads };
}
/**
* Get the log as a Buffer
* @returns {Buffer}
*/
}, {
key: 'toBuffer',
value: function toBuffer() {
return new Buffer((0, _stringify2.default)(this.toJSON()));
}
}, {
key: 'items',
get: function get() {
return this._entries;
}
/**
* Returns a list of heads as multihashes
* @returns {Array<string>}
*/
}, {
key: 'heads',
get: function get() {
return this._heads;
}
}]);
return Log;
}();
var LogUtils = function () {
function LogUtils() {
(0, _classCallCheck3.default)(this, LogUtils);
}
(0, _createClass3.default)(LogUtils, null, [{
key: 'create',
/**
* Create a new log
* @param {IPFS} ipfs An IPFS instance
* @param {string} id - ID for the log
* @param {Array} [entries] - Entries for this log
* @param {Array} [heads] - Heads for this log
* @returns {Log}
*/
value: function create(ipfs, entries, heads) {
if (!ipfs) throw new Error('Ipfs instance not defined');
// TODO: if (Array.isArray(entries))
// TODO: entries.map((e) => Entry.isEntry(e) ? e : await Entry.create(ipfs, e))
return new Log(ipfs, entries, heads);
}
/**
* Create a new log starting from an entry
* @param {IPFS} [ipfs] An IPFS instance
* @param {string} id
* @param {string} [hash] [Multihash of the entry to start from]
* @param {Number} length
* @param {function(hash, entry, parent, depth)} onProgressCallback
* @returns {Promise<Log>}
*/
}, {
key: 'fromEntry',
value: function fromEntry(ipfs, hash) {
var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
var onProgressCallback = arguments[3];
return LogUtils._fetchRecursive(ipfs, hash, {}, length, 0, null, onProgressCallback).then(function (items) {
var log = LogUtils.create(ipfs);
items.reverse().forEach(function (e) {
return LogUtils._insert(ipfs, log, e);
});
log._heads = LogUtils._findHeads(log);
return log;
});
}
/**
* Create a log from multihash
* @param {IPFS} [ipfs] An IPFS instance
* @param {string} [hash] Multihash to create the log from
* @param {Number} [length=-1] How many items to include in the log
* @returns {Promise<Log>}
*/
}, {
key: 'fromMultihash',
value: function fromMultihash(ipfs, hash) {
var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
var onProgressCallback = arguments[3];
if (!ipfs) throw new Error('Ipfs instance not defined');
if (!hash) throw new Error('Invalid hash: ' + hash);
var logData = void 0;
return ipfs.object.get(hash, { enc: 'base58' }).then(function (res) {
return logData = JSON.parse(res.toJSON().data);
}).then(function (res) {
if (!logData.heads) throw new Error('Not a Log instance');
// Fetch logs starting from each head entry
var allLogs = logData.heads.sort(LogUtils._compare).map(function (f) {
return LogUtils.fromEntry(ipfs, f, length, onProgressCallback);
});
// Join all logs together to one log
var joinAll = function joinAll(logs) {
return LogUtils.joinAll(ipfs, logs);
};
return _promise2.default.all(allLogs).then(joinAll);
});
}
/**
* Get the log's multihash
* @param {IPFS} [ipfs] An IPFS instance
* @param {Log} log
* @returns {Promise<string>}
*/
}, {
key: 'toMultihash',
value: function toMultihash(ipfs, log) {
if (!ipfs) throw new Error('Ipfs instance not defined');
if (!log) throw new Error('Log instance not defined');
if (log.items.length < 1) throw new Error('Can\'t serialize an empty log');
return ipfs.object.put(log.toBuffer()).then(function (res) {
return res.toJSON().multihash;
});
}
/**
* Add an entry to a log
* @description Adds an entry to the Log and returns a new Log. Doesn't modify the original Log.
* @memberof Log
* @static
* @param {IPFS} ipfs An IPFS instance
* @param {Log} log - The Log to add the entry to
* @param {string|Buffer|Object|Array} data - Data of the entry to be added
* @returns {Log}
*/
}, {
key: 'append',
value: function append(ipfs, log, data) {
if (!ipfs) throw new Error('Ipfs instance not defined');
if (!log) throw new Error('Log instance not defined');
// Create the entry
return Entry.create(ipfs, data, log.heads).then(function (entry) {
// Add the entry to the previous log entries
var items = log.items.slice().concat([entry]);
// Set the heads of this log to the latest entry
var heads = [entry.hash];
// Create a new log instance
return new Log(ipfs, items, heads);
});
}
/**
* Join two logs
*
* @description Joins two logs returning a new log. Doesn't mutate the original logs.
*
* @param {IPFS} [ipfs] An IPFS instance
* @param {Log} a
* @param {Log} b
*
* @example
* const log = Log.join(ipfs, log1, log2)
*
* @returns {Log}
*/
}, {
key: 'join',
value: function join(ipfs, a, b, size) {
if (!ipfs) throw new Error('Ipfs instance not defined');
if (!a || !b) throw new Error('Log instance not defined');
if (!a.items || !b.items) throw new Error('Log to join must be an instance of Log');
// If size is not specified, join all entries by default
size = size ? size : a.items.length + b.items.length;
// Get the heads from both logs and sort them by their IDs
var getHeadEntries = function getHeadEntries(log) {
return log.heads.map(function (e) {
return log.get(e);
}).filter(function (e) {
return e !== undefined;
}).slice();
};
var headsA = getHeadEntries(a);
var headsB = getHeadEntries(b);
var heads = headsA.concat(headsB).map(function (e) {
return e.hash;
}).sort();
// Sort which log should come first based on heads' IDs
var aa = headsA[0] ? headsA[0].hash : null;
var bb = headsB[0] ? headsB[0].hash : null;
var isFirst = aa < bb;
var log1 = isFirst ? a : b;
var log2 = isFirst ? b : a;
// Cap the size of the entries
var newEntries = log2.items.slice(0, size);
var oldEntries = log1.items.slice(0, size);
// Create a new log instance
var result = LogUtils.create(ipfs, oldEntries, heads);
// Insert each entry to the log
newEntries.forEach(function (e) {
return LogUtils._insert(ipfs, result, e);
});
return result;
}
/**
* Join multiple logs
* @param {IPFS} [ipfs] An IPFS instance
* @param {Array<Log>} logs
* @returns {Log}
*/
}, {
key: 'joinAll',
value: function joinAll(ipfs, logs) {
return logs.reduce(function (log, val, i) {
if (!log) return val;
return LogUtils.join(ipfs, log, val);
}, null);
}
/**
* Expand the size of the log
* @param {IPFS} [ipfs] An IPFS instance
* @param {Log} log
* @param {Number} length
* @param {function(hash, entry, parent, depth)} onProgressCallback
* @returns {Promise<Log>}
*/
}, {
key: 'expand',
value: function expand(ipfs, log) {
var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
var onProgressCallback = arguments[3];
// TODO: Find tails (entries that point to an entry that is not in the log)
var tails = log.items.slice()[0].next.sort(LogUtils._compare);
// Fetch a log starting from each tail entry
var getLog = tails.map(function (f) {
return LogUtils.fromEntry(ipfs, f, length, onProgressCallback);
});
// Join all logs together to one log
var joinAll = function joinAll(logs) {
return LogUtils.joinAll(ipfs, logs.concat([log]));
};
// Create all logs and join them
return _promise2.default.all(getLog).then(joinAll);
}
/**
* Insert an entry to the log
* @private
* @param {Entry} entry Entry to be inserted
* @returns {Entry}
*/
}, {
key: '_insert',
value: function _insert(ipfs, log, entry) {
var hashes = log.items.map(function (f) {
return f.hash;
});
// If entry is already in the log, don't insert
if (hashes.includes(entry.hash)) return entry;
// Find the item's parents' indices
var indices = entry.next.map(function (next) {
return hashes.indexOf(next);
});
// Find the largest index (latest parent)
var index = indices.length > 0 ? Math.max(Math.max.apply(null, indices) + 1, 0) : 0;
// Insert
log.items.splice(index, 0, entry);
return entry;
}
/**
* Fetch log entries recursively
* @private
* @param {IPFS} [ipfs] An IPFS instance
* @param {string} [hash] Multihash of the entry to fetch
* @param {string} [parent] Parent of the node to be fetched
* @param {Object} [all] Entries to skip
* @param {Number} [amount=-1] How many entries to fetch.
* @param {Number} [depth=0] Current depth of the recursion
* @param {function(hash, entry, parent, depth)} onProgressCallback
* @returns {Promise<Array<Entry>>}
*/
}, {
key: '_fetchRecursive',
value: function _fetchRecursive(ipfs, hash) {
var all = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var amount = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : -1;
var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
var parent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
var onProgressCallback = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : function () {};
// If the given hash is already fetched
// or if we're at maximum depth, return
if (all[hash] || depth >= amount && amount > 0) {
return _promise2.default.resolve([]);
}
// Create the entry and add it to the result
return Entry.fromMultihash(ipfs, hash).then(function (entry) {
all[hash] = entry;
onProgressCallback(hash, entry, parent, depth);
var fetch = function fetch(hash) {
return LogUtils._fetchRecursive(ipfs, hash, all, amount, depth + 1, entry, onProgressCallback);
};
return mapSeries(entry.next, fetch, { concurrency: 1 }).then(function (res) {
return res.concat([entry]);
}).then(function (res) {
return res.reduce(function (a, b) {
return a.concat(b);
}, []);
}); // flatten the array
});
}
/**
* Find heads of a log
* @private
* @param {Log} log
* @returns {Array<Entry>}
*/
}, {
key: '_findHeads',
value: function _findHeads(log) {
return log.items.slice().reverse().filter(function (f) {
return !LogUtils._isReferencedInChain(log, f);
}).map(function (f) {
return f.hash;
}).sort(LogUtils._compare);
}
/**
* Check if an entry is referenced by another entry in the log
* @private
* @param {log} [log] Log to search an entry from
* @param {Entry} [entry] Entry to search for
* @returns {boolean}
*/
}, {
key: '_isReferencedInChain',
value: function _isReferencedInChain(log, entry) {
return log.items.slice().reverse().find(function (e) {
return Entry.hasChild(e, entry);
}) !== undefined;
}
/**
* Find entry's parents
* @private
* @description Returns entry's parents as an Array up to the root entry
* @param {Log} [log] Log to search parents from
* @param {Entry} [entry] Entry for which to find the parents
* @returns {Array<Entry>}
*/
}, {
key: '_findParents',
value: function _findParents(log, entry) {
var stack = [];
var parent = log.items.find(function (e) {
return Entry.hasChild(e, entry);
});
var prev = entry;
while (parent) {
stack.push(parent);
prev = parent;
parent = log.items.find(function (e) {
return Entry.hasChild(e, prev);
});
}
return stack;
}
/**
* Internal compare function
* @private
* @returns {boolean}
*/
}, {
key: '_compare',
value: function _compare(a, b) {
return a < b;
}
}]);
return LogUtils;
}();
module.exports = LogUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://gist.github.com/dignifiedquire/dd08d2f3806a7b87f45b00c41fe109b7
var _promise = __webpack_require__(27);
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = function mapSeries(list, func) {
var res = [];
return list.reduce(function (acc, next) {
return acc.then(function (val) {
res.push(val);
return func(next);
});
}, _promise2.default.resolve(null)).then(function (val) {
res.push(val);
return res.slice(1);
});
};
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _assign = __webpack_require__(9);
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fs = __webpack_require__(190);
var format = __webpack_require__(189).format;
var EventEmitter = __webpack_require__(36).EventEmitter;
var isNodejs = process.version ? true : false;
var LogLevels = {
'DEBUG': 'DEBUG',
'INFO': 'INFO',
'WARN': 'WARN',
'ERROR': 'ERROR',
'NONE': 'NONE'
};
// Global log level
var GlobalLogLevel = LogLevels.DEBUG;
// Global log file name
var GlobalLogfile = null;
var GlobalEvents = new EventEmitter();
// ANSI colors
var Colors = {
'Black': 0,
'Red': 1,
'Green': 2,
'Yellow': 3,
'Blue': 4,
'Magenta': 5,
'Cyan': 6,
'Grey': 7,
'White': 9,
'Default': 9
};
// CSS colors
if (!isNodejs) {
Colors = {
'Black': 'Black',
'Red': 'IndianRed',
'Green': 'LimeGreen',
'Yellow': 'Orange',
'Blue': 'RoyalBlue',
'Magenta': 'Orchid',
'Cyan': 'SkyBlue',
'Grey': 'DimGrey',
'White': 'White',
'Default': 'Black'
};
}
var loglevelColors = [Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Red, Colors.Default];
var defaultOptions = {
useColors: true,
color: Colors.Default,
showTimestamp: true,
showLevel: true,
filename: GlobalLogfile,
appendFile: true
};
var Logger = function () {
function Logger(category, options) {
(0, _classCallCheck3.default)(this, Logger);
this.category = category;
var opts = {};
(0, _assign2.default)(opts, defaultOptions);
(0, _assign2.default)(opts, options);
this.options = opts;
}
(0, _createClass3.default)(Logger, [{
key: 'debug',
value: function debug() {
this._write(LogLevels.DEBUG, format.apply(null, arguments));
}
}, {
key: 'log',
value: function log() {
this.debug.apply(this, arguments);
}
}, {
key: 'info',
value: function info() {
this._write(LogLevels.INFO, format.apply(null, arguments));
}
}, {
key: 'warn',
value: function warn() {
this._write(LogLevels.WARN, format.apply(null, arguments));
}
}, {
key: 'error',
value: function error() {
this._write(LogLevels.ERROR, format.apply(null, arguments));
}
}, {
key: '_write',
value: function _write(level, text) {
if (!this._shouldLog(level)) return;
if ((this.options.filename || GlobalLogfile) && !this.fileWriter && isNodejs) this.fileWriter = fs.openSync(this.options.filename || GlobalLogfile, this.options.appendFile ? 'a+' : 'w+');
var format = this._format(level, text);
var unformattedText = this._createLogMessage(level, text);
var formattedText = this._createLogMessage(level, text, format.timestamp, format.level, format.category, format.text);
if (this.fileWriter && isNodejs) fs.writeSync(this.fileWriter, unformattedText + '\n', null, 'utf-8');
if (isNodejs || !this.options.useColors) {
console.log(formattedText);
GlobalEvents.emit('data', this.category, level, text);
} else {
// TODO: clean this up
if (level === LogLevels.ERROR) {
if (this.options.showTimestamp && this.options.showLevel) {
console.error(formattedText, format.timestamp, format.level, format.category, format.text);
} else if (this.options.showTimestamp && !this.options.showLevel) {
console.error(formattedText, format.timestamp, format.category, format.text);
} else if (!this.options.showTimestamp && this.options.showLevel) {
console.error(formattedText, format.level, format.category, format.text);
} else {
console.error(formattedText, format.category, format.text);
}
} else {
if (this.options.showTimestamp && this.options.showLevel) {
console.log(formattedText, format.timestamp, format.level, format.category, format.text);
} else if (this.options.showTimestamp && !this.options.showLevel) {
console.log(formattedText, format.timestamp, format.category, format.text);
} else if (!this.options.showTimestamp && this.options.showLevel) {
console.log(formattedText, format.level, format.category, format.text);
} else {
console.log(formattedText, format.category, format.text);
}
}
}
}
}, {
key: '_format',
value: function _format(level, text) {
var timestampFormat = '';
var levelFormat = '';
var categoryFormat = '';
var textFormat = ': ';
if (this.options.useColors) {
var levelColor = (0, _keys2.default)(LogLevels).map(function (f) {
return LogLevels[f];
}).indexOf(level);
var categoryColor = this.options.color;
if (isNodejs) {
if (this.options.showTimestamp) timestampFormat = '\x1B[3' + Colors.Grey + 'm';
if (this.options.showLevel) levelFormat = '\x1B[3' + loglevelColors[levelColor] + ';22m';
categoryFormat = '\x1B[3' + categoryColor + ';1m';
textFormat = '\x1B[0m: ';
} else {
if (this.options.showTimestamp) timestampFormat = 'color:' + Colors.Grey;
if (this.options.showLevel) levelFormat = 'color:' + loglevelColors[levelColor];
categoryFormat = 'color:' + categoryColor + '; font-weight: bold';
}
}
return {
timestamp: timestampFormat,
level: levelFormat,
category: categoryFormat,
text: textFormat
};
}
}, {
key: '_createLogMessage',
value: function _createLogMessage(level, text, timestampFormat, levelFormat, categoryFormat, textFormat) {
timestampFormat = timestampFormat || '';
levelFormat = levelFormat || '';
categoryFormat = categoryFormat || '';
textFormat = textFormat || ': ';
if (!isNodejs && this.options.useColors) {
if (this.options.showTimestamp) timestampFormat = '%c';
if (this.options.showLevel) levelFormat = '%c';
categoryFormat = '%c';
textFormat = ': %c';
}
var result = '';
if (this.options.showTimestamp) result += '' + new Date().toISOString() + ' ';
result = timestampFormat + result;
if (this.options.showLevel) result += levelFormat + '[' + level + ']' + (level === LogLevels.INFO || level === LogLevels.WARN ? ' ' : '') + ' ';
result += categoryFormat + this.category;
result += textFormat + text;
return result;
}
}, {
key: '_shouldLog',
value: function _shouldLog(level) {
var envLogLevel = typeof process !== "undefined" && process.env !== undefined && process.env.LOG !== undefined ? process.env.LOG.toUpperCase() : null;
envLogLevel = typeof window !== "undefined" && window.LOG ? window.LOG.toUpperCase() : envLogLevel;
var logLevel = envLogLevel || GlobalLogLevel;
var levels = (0, _keys2.default)(LogLevels).map(function (f) {
return LogLevels[f];
});
var index = levels.indexOf(level);
var levelIdx = levels.indexOf(logLevel);
return index >= levelIdx;
}
}]);
return Logger;
}();
;
/* Public API */
module.exports = {
Colors: Colors,
LogLevels: LogLevels,
setLogLevel: function setLogLevel(level) {
GlobalLogLevel = level;
},
setLogfile: function setLogfile(filename) {
GlobalLogfile = filename;
},
create: function create(category, options) {
var logger = new Logger(category, options);
return logger;
},
forceBrowserMode: function forceBrowserMode(force) {
return isNodejs = !force;
}, // for testing,
events: GlobalEvents
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(34)))
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Counter = __webpack_require__(87);
var CounterIndex = function () {
function CounterIndex(id) {
(0, _classCallCheck3.default)(this, CounterIndex);
this._counter = new Counter(id);
}
(0, _createClass3.default)(CounterIndex, [{
key: 'get',
value: function get() {
return this._counter;
}
}, {
key: 'updateIndex',
value: function updateIndex(oplog) {
var _this = this;
console.log(oplog.items);
if (this._counter) {
oplog.items.filter(function (f) {
return f && f.payload.op === 'COUNTER';
}).map(function (f) {
return Counter.from(f.payload.value);
}).forEach(function (f) {
return _this._counter.merge(f);
});
}
}
}]);
return CounterIndex;
}();
module.exports = CounterIndex;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DocumentIndex = function () {
function DocumentIndex() {
(0, _classCallCheck3.default)(this, DocumentIndex);
this._index = {};
}
(0, _createClass3.default)(DocumentIndex, [{
key: 'get',
value: function get(key) {
return this._index[key];
}
}, {
key: 'updateIndex',
value: function updateIndex(oplog) {
var _this = this;
oplog.items.slice().reverse().reduce(function (handled, item) {
if (handled.indexOf(item.payload.key) === -1) {
handled.push(item.payload.key);
if (item.payload.op === 'PUT') {
_this._index[item.payload.key] = item.payload.value;
} else if (item.payload.op === 'DEL') {
delete _this._index[item.payload.key];
}
}
return handled;
}, []);
}
}]);
return DocumentIndex;
}();
module.exports = DocumentIndex;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getPrototypeOf = __webpack_require__(14);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(16);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(15);
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventIndex = __webpack_require__(55);
var FeedIndex = function (_EventIndex) {
(0, _inherits3.default)(FeedIndex, _EventIndex);
function FeedIndex() {
(0, _classCallCheck3.default)(this, FeedIndex);
return (0, _possibleConstructorReturn3.default)(this, (FeedIndex.__proto__ || (0, _getPrototypeOf2.default)(FeedIndex)).apply(this, arguments));
}
(0, _createClass3.default)(FeedIndex, [{
key: 'updateIndex',
value: function updateIndex(oplog) {
var _this2 = this;
oplog.items.reduce(function (handled, item) {
if (!handled.includes(item.hash)) {
handled.push(item.hash);
if (item.payload.op === 'ADD') {
_this2._index[item.hash] = item;
} else if (item.payload.op === 'DEL') {
delete _this2._index[item.payload.value];
}
}
return handled;
}, []);
}
}]);
return FeedIndex;
}(EventIndex);
module.exports = FeedIndex;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var KeyValueIndex = function () {
function KeyValueIndex() {
(0, _classCallCheck3.default)(this, KeyValueIndex);
this._index = {};
}
(0, _createClass3.default)(KeyValueIndex, [{
key: 'get',
value: function get(key) {
return this._index[key];
}
}, {
key: 'updateIndex',
value: function updateIndex(oplog) {
var _this = this;
oplog.items.slice().reverse().reduce(function (handled, item) {
if (!handled.includes(item.payload.key)) {
handled.push(item.payload.key);
if (item.payload.op === 'PUT') {
_this._index[item.payload.key] = item.payload.value;
} else if (item.payload.op === 'DEL') {
delete _this._index[item.payload.key];
}
}
return handled;
}, []);
}
}]);
return KeyValueIndex;
}();
module.exports = KeyValueIndex;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Logger = __webpack_require__(92);
var logger = Logger.create("orbit-db.ipfs-pubsub");
Logger.setLogLevel('ERROR');
var IPFSPubsub = function () {
function IPFSPubsub(ipfs) {
(0, _classCallCheck3.default)(this, IPFSPubsub);
this._ipfs = ipfs;
this._subscriptions = {};
if (this._ipfs.pubsub === null) logger.error("The provided version of ipfs doesn't have pubsub support. Messages will not be exchanged.");
}
(0, _createClass3.default)(IPFSPubsub, [{
key: 'subscribe',
value: function subscribe(hash, onMessageCallback) {
if (!this._subscriptions[hash]) {
this._subscriptions[hash] = { onMessage: onMessageCallback };
if (this._ipfs.pubsub) this._ipfs.pubsub.subscribe(hash, { discover: true }, this._handleMessage.bind(this));
}
}
}, {
key: 'unsubscribe',
value: function unsubscribe(hash) {
if (this._subscriptions[hash]) {
this._ipfs.pubsub.unsubscribe(hash, this._handleMessage);
delete this._subscriptions[hash];
logger.debug('Unsubscribed from \'' + hash + '\'');
}
}
}, {
key: 'publish',
value: function publish(hash, message) {
if (this._subscriptions[hash] && this._ipfs.pubsub) this._ipfs.pubsub.publish(hash, new Buffer(message));
}
}, {
key: 'disconnect',
value: function disconnect() {
var _this = this;
(0, _keys2.default)(this._subscriptions).forEach(function (e) {
return _this.unsubscribe(e);
});
}
}, {
key: '_handleMessage',
value: function _handleMessage(message) {
var hash = message.topicCIDs[0];
var data = message.data.toString();
var subscription = this._subscriptions[hash];
if (subscription && subscription.onMessage && data) subscription.onMessage(hash, data);
}
}]);
return IPFSPubsub;
}();
module.exports = IPFSPubsub;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
Index
Index contains the state of a datastore, ie. what data we currently have.
Index receives a call from a Store when the operations log for the Store
was updated, ie. new operations were added. In updateIndex, the Index
implements its CRDT logic: add, remove or update items in the data
structure. Each new operation received from the operations log is applied
in order onto the current state, ie. each new operation changes the data
and the state changes.
Implementing each CRDT as an Index, we can implement both operation-based
and state-based CRDTs with the same higher level abstractions.
To read the current state of the database, Index provides a single public
function: `get()`. It is up to the Store to decide what kind of query
capabilities it provides to the consumer.
Usage:
```javascript
const Index = new Index(userId)
```
*/
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Index = function () {
/*
@param id - unique identifier of this index, eg. a user id or a hash
*/
function Index(id) {
(0, _classCallCheck3.default)(this, Index);
this.id = id;
this._index = [];
}
/*
Returns the state of the datastore, ie. most up-to-date data
@return - current state
*/
(0, _createClass3.default)(Index, [{
key: 'get',
value: function get() {
return this._index;
}
/*
Applies operations to the Index and updates the state
@param oplog - the source operations log that called updateIndex
@param entries - operations that were added to the log
*/
}, {
key: 'updateIndex',
value: function updateIndex(oplog, entries) {
this._index = oplog.ops;
}
}]);
return Index;
}();
module.exports = Index;
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(107), __esModule: true };
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(109), __esModule: true };
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(112), __esModule: true };
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(114), __esModule: true };
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _defineProperty = __webpack_require__(56);
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (obj, key, value) {
if (key in obj) {
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}( false ? (this.base64js = {}) : exports))
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(2)
, $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify});
module.exports = function stringify(it){ // eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
};
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(141);
module.exports = __webpack_require__(2).Object.assign;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(142);
var $Object = __webpack_require__(2).Object;
module.exports = function create(P, D){
return $Object.create(P, D);
};
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(143);
var $Object = __webpack_require__(2).Object;
module.exports = function defineProperty(it, key, desc){
return $Object.defineProperty(it, key, desc);
};
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(144);
var $Object = __webpack_require__(2).Object;
module.exports = function getOwnPropertyNames(it){
return $Object.getOwnPropertyNames(it);
};
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(145);
module.exports = __webpack_require__(2).Object.getPrototypeOf;
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(146);
module.exports = __webpack_require__(2).Object.keys;
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(147);
module.exports = __webpack_require__(2).Object.setPrototypeOf;
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(72);
__webpack_require__(73);
__webpack_require__(74);
__webpack_require__(148);
module.exports = __webpack_require__(2).Promise;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(149);
__webpack_require__(72);
__webpack_require__(150);
__webpack_require__(151);
module.exports = __webpack_require__(2).Symbol;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(73);
__webpack_require__(74);
module.exports = __webpack_require__(50).f('iterator');
/***/ }),
/* 116 */
/***/ (function(module, exports) {
module.exports = function(){ /* empty */ };
/***/ }),
/* 117 */
/***/ (function(module, exports) {
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(12)
, toLength = __webpack_require__(71)
, toIndex = __webpack_require__(138);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(19)
, gOPS = __webpack_require__(43)
, pIE = __webpack_require__(29);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(22)
, call = __webpack_require__(124)
, isArrayIter = __webpack_require__(122)
, anObject = __webpack_require__(5)
, toLength = __webpack_require__(71)
, getIterFn = __webpack_require__(139)
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/* 121 */
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(23)
, ITERATOR = __webpack_require__(3)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(21);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(5);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__(42)
, descriptor = __webpack_require__(30)
, setToStringTag = __webpack_require__(31)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(11)(IteratorPrototype, __webpack_require__(3)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(3)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ }),
/* 127 */
/***/ (function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(19)
, toIObject = __webpack_require__(12);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__(33)('meta')
, isObject = __webpack_require__(18)
, has = __webpack_require__(10)
, setDesc = __webpack_require__(8).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(17)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, macrotask = __webpack_require__(70).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(21)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(19)
, gOPS = __webpack_require__(43)
, pIE = __webpack_require__(29)
, toObject = __webpack_require__(32)
, IObject = __webpack_require__(62)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(17)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(8)
, anObject = __webpack_require__(5)
, getKeys = __webpack_require__(19);
module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var hide = __webpack_require__(11);
module.exports = function(target, src, safe){
for(var key in src){
if(safe && target[key])target[key] = src[key];
else hide(target, key, src[key]);
} return target;
};
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(18)
, anObject = __webpack_require__(5);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(22)(Function.call, __webpack_require__(64).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(4)
, core = __webpack_require__(2)
, dP = __webpack_require__(8)
, DESCRIPTORS = __webpack_require__(6)
, SPECIES = __webpack_require__(3)('species');
module.exports = function(KEY){
var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(5)
, aFunction = __webpack_require__(38)
, SPECIES = __webpack_require__(3)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(47)
, defined = __webpack_require__(39);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(47)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(59)
, ITERATOR = __webpack_require__(3)('iterator')
, Iterators = __webpack_require__(23);
module.exports = __webpack_require__(2).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__(116)
, step = __webpack_require__(127)
, Iterators = __webpack_require__(23)
, toIObject = __webpack_require__(12);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(63)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(7);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(131)});
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(7)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: __webpack_require__(42)});
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(7);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperty: __webpack_require__(8).f});
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(44)('getOwnPropertyNames', function(){
return __webpack_require__(65).f;
});
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(32)
, $getPrototypeOf = __webpack_require__(67);
__webpack_require__(44)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(32)
, $keys = __webpack_require__(19);
__webpack_require__(44)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(7);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(134).set});
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(28)
, global = __webpack_require__(4)
, ctx = __webpack_require__(22)
, classof = __webpack_require__(59)
, $export = __webpack_require__(7)
, isObject = __webpack_require__(18)
, aFunction = __webpack_require__(38)
, anInstance = __webpack_require__(117)
, forOf = __webpack_require__(120)
, speciesConstructor = __webpack_require__(136)
, task = __webpack_require__(70).set
, microtask = __webpack_require__(130)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[__webpack_require__(3)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(133)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
__webpack_require__(31)($Promise, PROMISE);
__webpack_require__(135)(PROMISE);
Wrapper = __webpack_require__(2)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(126)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__(4)
, has = __webpack_require__(10)
, DESCRIPTORS = __webpack_require__(6)
, $export = __webpack_require__(7)
, redefine = __webpack_require__(69)
, META = __webpack_require__(129).KEY
, $fails = __webpack_require__(17)
, shared = __webpack_require__(46)
, setToStringTag = __webpack_require__(31)
, uid = __webpack_require__(33)
, wks = __webpack_require__(3)
, wksExt = __webpack_require__(50)
, wksDefine = __webpack_require__(49)
, keyOf = __webpack_require__(128)
, enumKeys = __webpack_require__(119)
, isArray = __webpack_require__(123)
, anObject = __webpack_require__(5)
, toIObject = __webpack_require__(12)
, toPrimitive = __webpack_require__(48)
, createDesc = __webpack_require__(30)
, _create = __webpack_require__(42)
, gOPNExt = __webpack_require__(65)
, $GOPD = __webpack_require__(64)
, $DP = __webpack_require__(8)
, $keys = __webpack_require__(19)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(66).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(29).f = $propertyIsEnumerable;
__webpack_require__(43).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(28)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(11)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(49)('asyncIterator');
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(49)('observable');
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, setImmediate) {(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Dexie = factory());
}(this, (function () { 'use strict';
/*
* Dexie.js - a minimalistic wrapper for IndexedDB
* ===============================================
*
* By David Fahlander, david.fahlander@gmail.com
*
* Version 1.5.1, Tue Nov 01 2016
* www.dexie.com
* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
*/
var keys = Object.keys;
var isArray = Array.isArray;
var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
function extend(obj, extension) {
if (typeof extension !== 'object') return obj;
keys(extension).forEach(function (key) {
obj[key] = extension[key];
});
return obj;
}
var getProto = Object.getPrototypeOf;
var _hasOwn = {}.hasOwnProperty;
function hasOwn(obj, prop) {
return _hasOwn.call(obj, prop);
}
function props(proto, extension) {
if (typeof extension === 'function') extension = extension(getProto(proto));
keys(extension).forEach(function (key) {
setProp(proto, key, extension[key]);
});
}
function setProp(obj, prop, functionOrGetSet, options) {
Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options));
}
function derive(Child) {
return {
from: function (Parent) {
Child.prototype = Object.create(Parent.prototype);
setProp(Child.prototype, "constructor", Child);
return {
extend: props.bind(null, Child.prototype)
};
}
};
}
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
function getPropertyDescriptor(obj, prop) {
var pd = getOwnPropertyDescriptor(obj, prop),
proto;
return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);
}
var _slice = [].slice;
function slice(args, start, end) {
return _slice.call(args, start, end);
}
function override(origFunc, overridedFactory) {
return overridedFactory(origFunc);
}
function doFakeAutoComplete(fn) {
var to = setTimeout(fn, 1000);
clearTimeout(to);
}
function assert(b) {
if (!b) throw new Error("Assertion Failed");
}
function asap(fn) {
if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0);
}
/** Generate an object (hash map) based on given array.
* @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to
* instert on the resulting object for each item in the array. If this function returns a falsy value, the
* current item wont affect the resulting object.
*/
function arrayToObject(array, extractor) {
return array.reduce(function (result, item, i) {
var nameAndValue = extractor(item, i);
if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];
return result;
}, {});
}
function trycatcher(fn, reject) {
return function () {
try {
fn.apply(this, arguments);
} catch (e) {
reject(e);
}
};
}
function tryCatch(fn, onerror, args) {
try {
fn.apply(null, args);
} catch (ex) {
onerror && onerror(ex);
}
}
function getByKeyPath(obj, keyPath) {
// http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path
if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.
if (!keyPath) return obj;
if (typeof keyPath !== 'string') {
var rv = [];
for (var i = 0, l = keyPath.length; i < l; ++i) {
var val = getByKeyPath(obj, keyPath[i]);
rv.push(val);
}
return rv;
}
var period = keyPath.indexOf('.');
if (period !== -1) {
var innerObj = obj[keyPath.substr(0, period)];
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));
}
return undefined;
}
function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "") {
if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value;
} else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = obj[currentKeyPath] = {};
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) delete obj[keyPath];else obj[keyPath] = value;
}
}
}
function delByKeyPath(obj, keyPath) {
if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) {
setByKeyPath(obj, kp, undefined);
});
}
function shallowClone(obj) {
var rv = {};
for (var m in obj) {
if (hasOwn(obj, m)) rv[m] = obj[m];
}
return rv;
}
function deepClone(any) {
if (!any || typeof any !== 'object') return any;
var rv;
if (isArray(any)) {
rv = [];
for (var i = 0, l = any.length; i < l; ++i) {
rv.push(deepClone(any[i]));
}
} else if (any instanceof Date) {
rv = new Date();
rv.setTime(any.getTime());
} else {
rv = any.constructor ? Object.create(any.constructor.prototype) : {};
for (var prop in any) {
if (hasOwn(any, prop)) {
rv[prop] = deepClone(any[prop]);
}
}
}
return rv;
}
function getObjectDiff(a, b, rv, prfx) {
// Compares objects a and b and produces a diff object.
rv = rv || {};
prfx = prfx || '';
keys(a).forEach(function (prop) {
if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed
else {
var ap = a[prop],
bp = b[prop];
if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor)
// Same type of object but its properties may have changed
getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed
}
});
keys(b).forEach(function (prop) {
if (!hasOwn(a, prop)) {
rv[prfx + prop] = b[prop]; // Property added
}
});
return rv;
}
// If first argument is iterable or array-like, return it as an array
var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;
var getIteratorOf = iteratorSymbol ? function (x) {
var i;
return x != null && (i = x[iteratorSymbol]) && i.apply(x);
} : function () {
return null;
};
var NO_CHAR_ARRAY = {};
// Takes one or several arguments and returns an array based on the following criteras:
// * If several arguments provided, return arguments converted to an array in a way that
// still allows javascript engine to optimize the code.
// * If single argument is an array, return a clone of it.
// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special
// case to the two bullets below.
// * If single argument is an iterable, convert it to an array and return the resulting array.
// * If single argument is array-like (has length of type number), convert it to an array.
function getArrayOf(arrayLike) {
var i, a, x, it;
if (arguments.length === 1) {
if (isArray(arrayLike)) return arrayLike.slice();
if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];
if (it = getIteratorOf(arrayLike)) {
a = [];
while (x = it.next(), !x.done) {
a.push(x.value);
}return a;
}
if (arrayLike == null) return [arrayLike];
i = arrayLike.length;
if (typeof i === 'number') {
a = new Array(i);
while (i--) {
a[i] = arrayLike[i];
}return a;
}
return [arrayLike];
}
i = arguments.length;
a = new Array(i);
while (i--) {
a[i] = arguments[i];
}return a;
}
var concat = [].concat;
function flatten(a) {
return concat.apply([], a);
}
function nop() {}
function mirror(val) {
return val;
}
function pureFunctionChain(f1, f2) {
// Enables chained events that takes ONE argument and returns it to the next function in chain.
// This pattern is used in the hook("reading") event.
if (f1 == null || f1 === mirror) return f2;
return function (val) {
return f2(f1(val));
};
}
function callBoth(on1, on2) {
return function () {
on1.apply(this, arguments);
on2.apply(this, arguments);
};
}
function hookCreatingChain(f1, f2) {
// Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.
// This pattern is used in the hook("creating") event.
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res !== undefined) arguments[0] = res;
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res2 !== undefined ? res2 : res;
};
}
function hookDeletingChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
f1.apply(this, arguments);
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = this.onerror = null;
f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
};
}
function hookUpdatingChain(f1, f2) {
if (f1 === nop) return f2;
return function (modifications) {
var res = f1.apply(this, arguments);
extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2);
};
}
function reverseStoppableEventChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
if (f2.apply(this, arguments) === false) return false;
return f1.apply(this, arguments);
};
}
function promisableChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res && typeof res.then === 'function') {
var thiz = this,
i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
}return res.then(function () {
return f2.apply(thiz, args);
});
}
return f2.apply(this, arguments);
};
}
// By default, debug will be true only if platform is a web platform and its page is served from localhost.
// When debug = true, error's stacks will contain asyncronic long stacks.
var debug = typeof location !== 'undefined' &&
// By default, use debug mode if served from localhost.
/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);
function setDebug(value, filter) {
debug = value;
libraryFilter = filter;
}
var libraryFilter = function () {
return true;
};
var NEEDS_THROW_FOR_STACK = !new Error("").stack;
function getErrorWithStack() {
"use strict";
if (NEEDS_THROW_FOR_STACK) try {
// Doing something naughty in strict mode here to trigger a specific error
// that can be explicitely ignored in debugger's exception settings.
// If we'd just throw new Error() here, IE's debugger's exception settings
// will just consider it as "exception thrown by javascript code" which is
// something you wouldn't want it to ignore.
getErrorWithStack.arguments;
throw new Error(); // Fallback if above line don't throw.
} catch (e) {
return e;
}
return new Error();
}
function prettyStack(exception, numIgnoredFrames) {
var stack = exception.stack;
if (!stack) return "";
numIgnoredFrames = numIgnoredFrames || 0;
if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length;
return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) {
return "\n" + frame;
}).join('');
}
function deprecated(what, fn) {
return function () {
console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1));
return fn.apply(this, arguments);
};
}
var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise'];
var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone'];
var errorList = dexieErrorNames.concat(idbDomErrorNames);
var defaultTexts = {
VersionChanged: "Database version changed by other database connection",
DatabaseClosed: "Database has been closed",
Abort: "Transaction aborted",
TransactionInactive: "Transaction has already completed or failed"
};
//
// DexieError - base class of all out exceptions.
//
function DexieError(name, msg) {
// Reason we don't use ES6 classes is because:
// 1. It bloats transpiled code and increases size of minified code.
// 2. It doesn't give us much in this case.
// 3. It would require sub classes to call super(), which
// is not needed when deriving from Error.
this._e = getErrorWithStack();
this.name = name;
this.message = msg;
}
derive(DexieError).from(Error).extend({
stack: {
get: function () {
return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2));
}
},
toString: function () {
return this.name + ": " + this.message;
}
});
function getMultiErrorMessage(msg, failures) {
return msg + ". Errors: " + failures.map(function (f) {
return f.toString();
}).filter(function (v, i, s) {
return s.indexOf(v) === i;
}) // Only unique error strings
.join('\n');
}
//
// ModifyError - thrown in WriteableCollection.modify()
// Specific constructor because it contains members failures and failedKeys.
//
function ModifyError(msg, failures, successCount, failedKeys) {
this._e = getErrorWithStack();
this.failures = failures;
this.failedKeys = failedKeys;
this.successCount = successCount;
}
derive(ModifyError).from(DexieError);
function BulkError(msg, failures) {
this._e = getErrorWithStack();
this.name = "BulkError";
this.failures = failures;
this.message = getMultiErrorMessage(msg, failures);
}
derive(BulkError).from(DexieError);
//
//
// Dynamically generate error names and exception classes based
// on the names in errorList.
//
//
// Map of {ErrorName -> ErrorName + "Error"}
var errnames = errorList.reduce(function (obj, name) {
return obj[name] = name + "Error", obj;
}, {});
// Need an alias for DexieError because we're gonna create subclasses with the same name.
var BaseException = DexieError;
// Map of {ErrorName -> exception constructor}
var exceptions = errorList.reduce(function (obj, name) {
// Let the name be "DexieError" because this name may
// be shown in call stack and when debugging. DexieError is
// the most true name because it derives from DexieError,
// and we cannot change Function.name programatically without
// dynamically create a Function object, which would be considered
// 'eval-evil'.
var fullName = name + "Error";
function DexieError(msgOrInner, inner) {
this._e = getErrorWithStack();
this.name = fullName;
if (!msgOrInner) {
this.message = defaultTexts[name] || fullName;
this.inner = null;
} else if (typeof msgOrInner === 'string') {
this.message = msgOrInner;
this.inner = inner || null;
} else if (typeof msgOrInner === 'object') {
this.message = msgOrInner.name + ' ' + msgOrInner.message;
this.inner = msgOrInner;
}
}
derive(DexieError).from(BaseException);
obj[name] = DexieError;
return obj;
}, {});
// Use ECMASCRIPT standard exceptions where applicable:
exceptions.Syntax = SyntaxError;
exceptions.Type = TypeError;
exceptions.Range = RangeError;
var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {
obj[name + "Error"] = exceptions[name];
return obj;
}, {});
function mapError(domError, message) {
if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError;
var rv = new exceptionMap[domError.name](message || domError.message, domError);
if ("stack" in domError) {
// Derive stack from inner exception if it has a stack
setProp(rv, "stack", { get: function () {
return this.inner.stack;
} });
}
return rv;
}
var fullNameExceptions = errorList.reduce(function (obj, name) {
if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name];
return obj;
}, {});
fullNameExceptions.ModifyError = ModifyError;
fullNameExceptions.DexieError = DexieError;
fullNameExceptions.BulkError = BulkError;
function Events(ctx) {
var evs = {};
var rv = function (eventName, subscriber) {
if (subscriber) {
// Subscribe. If additional arguments than just the subscriber was provided, forward them as well.
var i = arguments.length,
args = new Array(i - 1);
while (--i) {
args[i - 1] = arguments[i];
}evs[eventName].subscribe.apply(null, args);
return ctx;
} else if (typeof eventName === 'string') {
// Return interface allowing to fire or unsubscribe from event
return evs[eventName];
}
};
rv.addEventType = add;
for (var i = 1, l = arguments.length; i < l; ++i) {
add(arguments[i]);
}
return rv;
function add(eventName, chainFunction, defaultFunction) {
if (typeof eventName === 'object') return addConfiguredEvents(eventName);
if (!chainFunction) chainFunction = reverseStoppableEventChain;
if (!defaultFunction) defaultFunction = nop;
var context = {
subscribers: [],
fire: defaultFunction,
subscribe: function (cb) {
if (context.subscribers.indexOf(cb) === -1) {
context.subscribers.push(cb);
context.fire = chainFunction(context.fire, cb);
}
},
unsubscribe: function (cb) {
context.subscribers = context.subscribers.filter(function (fn) {
return fn !== cb;
});
context.fire = context.subscribers.reduce(chainFunction, defaultFunction);
}
};
evs[eventName] = rv[eventName] = context;
return context;
}
function addConfiguredEvents(cfg) {
// events(this, {reading: [functionChain, nop]});
keys(cfg).forEach(function (eventName) {
var args = cfg[eventName];
if (isArray(args)) {
add(eventName, cfg[eventName][0], cfg[eventName][1]);
} else if (args === 'asap') {
// Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack
// enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.
var context = add(eventName, mirror, function fire() {
// Optimazation-safe cloning of arguments into args.
var i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
} // All each subscriber:
context.subscribers.forEach(function (fn) {
asap(function fireEvent() {
fn.apply(null, args);
});
});
});
} else throw new exceptions.InvalidArgument("Invalid event config");
});
}
}
//
// Promise Class for Dexie library
//
// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by
// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.
//
// Modifications needed to be done to support indexedDB because it wont accept setTimeout()
// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .
// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45
//
// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since
// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.
//
// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another
// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use
// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick
// engine that is used instead of setImmediate() or setTimeout().
// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.
// Also with inspiration from bluebird, asyncronic stacks in debug mode.
//
// Specific non-standard features of this Promise class:
// * Async static context support (Promise.PSD)
// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame
// and below + all promises that those promises creates or awaits.
// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled).
//
// David Fahlander, https://github.com/dfahlander
//
// Just a pointer that only this module knows about.
// Used in Promise constructor to emulate a private constructor.
var INTERNAL = {};
// Async stacks (long stacks) must not grow infinitely.
var LONG_STACKS_CLIP_LIMIT = 100;
var MAX_LONG_STACKS = 20;
var stack_being_generated = false;
/* The default "nextTick" function used only for the very first promise in a promise chain.
As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks
emulated in this module. For indexedDB compatibility, this means that every method needs to
execute at least one promise before doing an indexedDB operation. Dexie will always call
db.ready().then() for every operation to make sure the indexedDB event is started in an
emulated micro tick.
*/
var schedulePhysicalTick = _global.setImmediate ?
// setImmediate supported. Those modern platforms also supports Function.bind().
setImmediate.bind(null, physicalTick) : _global.MutationObserver ?
// MutationObserver supported
function () {
var hiddenDiv = document.createElement("div");
new MutationObserver(function () {
physicalTick();
hiddenDiv = null;
}).observe(hiddenDiv, { attributes: true });
hiddenDiv.setAttribute('i', '1');
} :
// No support for setImmediate or MutationObserver. No worry, setTimeout is only called
// once time. Every tick that follows will be our emulated micro tick.
// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug
function () {
setTimeout(physicalTick, 0);
};
// Confifurable through Promise.scheduler.
// Don't export because it would be unsafe to let unknown
// code call it unless they do try..catch within their callback.
// This function can be retrieved through getter of Promise.scheduler though,
// but users must not do Promise.scheduler (myFuncThatThrows exception)!
var asap$1 = function (callback, args) {
microtickQueue.push([callback, args]);
if (needsNewPhysicalTick) {
schedulePhysicalTick();
needsNewPhysicalTick = false;
}
};
var isOutsideMicroTick = true;
var needsNewPhysicalTick = true;
var unhandledErrors = [];
var rejectingErrors = [];
var currentFulfiller = null;
var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions
var globalPSD = {
global: true,
ref: 0,
unhandleds: [],
onunhandled: globalError,
//env: null, // Will be set whenever leaving a scope using wrappers.snapshot()
finalize: function () {
this.unhandleds.forEach(function (uh) {
try {
globalError(uh[0], uh[1]);
} catch (e) {}
});
}
};
var PSD = globalPSD;
var microtickQueue = []; // Callbacks to call in this or next physical tick.
var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.
var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.
// Wrappers are not being used yet. Their framework is functioning and can be used
// to replace environment during a PSD scope (a.k.a. 'zone').
/* **KEEP** export var wrappers = (() => {
var wrappers = [];
return {
snapshot: () => {
var i = wrappers.length,
result = new Array(i);
while (i--) result[i] = wrappers[i].snapshot();
return result;
},
restore: values => {
var i = wrappers.length;
while (i--) wrappers[i].restore(values[i]);
},
wrap: () => wrappers.map(w => w.wrap()),
add: wrapper => {
wrappers.push(wrapper);
}
};
})();
*/
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
this._listeners = [];
this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.
// A library may set `promise._lib = true;` after promise is created to make resolve() or reject()
// execute the microtask engine implicitely within the call to resolve() or reject().
// To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack
// only contains library code when calling resolve() or reject().
// RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from
// global scope (event handler, timer etc)!
this._lib = false;
// Current async scope
var psd = this._PSD = PSD;
if (debug) {
this._stackHolder = getErrorWithStack();
this._prev = null;
this._numPrev = 0; // Number of previous promises (for long stacks)
linkToPreviousPromise(this, currentFulfiller);
}
if (typeof fn !== 'function') {
if (fn !== INTERNAL) throw new TypeError('Not a function');
// Private constructor (INTERNAL, state, value).
// Used internally by Promise.resolve() and Promise.reject().
this._state = arguments[1];
this._value = arguments[2];
if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().
return;
}
this._state = null; // null (=pending), false (=rejected) or true (=resolved)
this._value = null; // error or result
++psd.ref; // Refcounting current scope
executePromiseTask(this, fn);
}
props(Promise.prototype, {
then: function (onFulfilled, onRejected) {
var _this = this;
var rv = new Promise(function (resolve, reject) {
propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject));
});
debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);
return rv;
},
_then: function (onFulfilled, onRejected) {
// A little tinier version of then() that don't have to create a resulting promise.
propagateToListener(this, new Listener(null, null, onFulfilled, onRejected));
},
catch: function (onRejected) {
if (arguments.length === 1) return this.then(null, onRejected);
// First argument is the Error type to catch
var type = arguments[0],
handler = arguments[1];
return typeof type === 'function' ? this.then(null, function (err) {
return (
// Catching errors by its constructor type (similar to java / c++ / c#)
// Sample: promise.catch(TypeError, function (e) { ... });
err instanceof type ? handler(err) : PromiseReject(err)
);
}) : this.then(null, function (err) {
return (
// Catching errors by the error.name property. Makes sense for indexedDB where error type
// is always DOMError but where e.name tells the actual error type.
// Sample: promise.catch('ConstraintError', function (e) { ... });
err && err.name === type ? handler(err) : PromiseReject(err)
);
});
},
finally: function (onFinally) {
return this.then(function (value) {
onFinally();
return value;
}, function (err) {
onFinally();
return PromiseReject(err);
});
},
// Deprecate in next major. Needed only for db.on.error.
uncaught: function (uncaughtHandler) {
var _this2 = this;
// Be backward compatible and use "onuncatched" as the event name on this.
// Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.
this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);
// In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not
// a previous promise. Reason: the prevous promise may lack onuncatched handler.
if (this._state === false && unhandledErrors.indexOf(this) === -1) {
// Replace unhandled error's destinaion promise with this one!
unhandledErrors.some(function (p, i, l) {
return p._value === _this2._value && (l[i] = _this2);
});
// Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could
// take away this piece of code as well as the onuncatched and uncaught() method.
}
return this;
},
stack: {
get: function () {
if (this._stack) return this._stack;
try {
stack_being_generated = true;
var stacks = getStack(this, [], MAX_LONG_STACKS);
var stack = stacks.join("\nFrom previous: ");
if (this._state !== null) this._stack = stack; // Stack may be updated on reject.
return stack;
} finally {
stack_being_generated = false;
}
}
}
});
function Listener(onFulfilled, onRejected, resolve, reject) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
this.psd = PSD;
}
// Promise Static Properties
props(Promise, {
all: function () {
var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.
return new Promise(function (resolve, reject) {
if (values.length === 0) resolve([]);
var remaining = values.length;
values.forEach(function (a, i) {
return Promise.resolve(a).then(function (x) {
values[i] = x;
if (! --remaining) resolve(values);
}, reject);
});
});
},
resolve: function (value) {
if (value instanceof Promise) return value;
if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) {
value.then(resolve, reject);
});
return new Promise(INTERNAL, true, value);
},
reject: PromiseReject,
race: function () {
var values = getArrayOf.apply(null, arguments);
return new Promise(function (resolve, reject) {
values.map(function (value) {
return Promise.resolve(value).then(resolve, reject);
});
});
},
PSD: {
get: function () {
return PSD;
},
set: function (value) {
return PSD = value;
}
},
newPSD: newScope,
usePSD: usePSD,
scheduler: {
get: function () {
return asap$1;
},
set: function (value) {
asap$1 = value;
}
},
rejectionMapper: {
get: function () {
return rejectionMapper;
},
set: function (value) {
rejectionMapper = value;
} // Map reject failures
},
follow: function (fn) {
return new Promise(function (resolve, reject) {
return newScope(function (resolve, reject) {
var psd = PSD;
psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()
psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.
psd.finalize = callBoth(function () {
var _this3 = this;
// Unhandled standard or 3rd part promises are put in PSD.unhandleds and
// examined upon scope completion while unhandled rejections in this Promise
// will trigger directly through psd.onunhandled
run_at_end_of_this_or_next_physical_tick(function () {
_this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]);
});
}, psd.finalize);
fn();
}, resolve, reject);
});
},
on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler
})
});
var PromiseOnError = Promise.on.error;
PromiseOnError.subscribe = deprecated("Promise.on('error')", PromiseOnError.subscribe);
PromiseOnError.unsubscribe = deprecated("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe);
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function executePromiseTask(promise, fn) {
// Promise Resolution Procedure:
// https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
try {
fn(function (value) {
if (promise._state !== null) return;
if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');
var shouldExecuteTick = promise._lib && beginMicroTickScope();
if (value && typeof value.then === 'function') {
executePromiseTask(promise, function (resolve, reject) {
value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject);
});
} else {
promise._state = true;
promise._value = value;
propagateAllListeners(promise);
}
if (shouldExecuteTick) endMicroTickScope();
}, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below
} catch (ex) {
handleRejection(promise, ex);
}
}
function handleRejection(promise, reason) {
rejectingErrors.push(reason);
if (promise._state !== null) return;
var shouldExecuteTick = promise._lib && beginMicroTickScope();
reason = rejectionMapper(reason);
promise._state = false;
promise._value = reason;
debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () {
var origProp = getPropertyDescriptor(reason, "stack");
reason._promise = promise;
setProp(reason, "stack", {
get: function () {
return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack;
}
});
});
// Add the failure to a list of possibly uncaught errors
addPossiblyUnhandledError(promise);
propagateAllListeners(promise);
if (shouldExecuteTick) endMicroTickScope();
}
function propagateAllListeners(promise) {
//debug && linkToPreviousPromise(promise);
var listeners = promise._listeners;
promise._listeners = [];
for (var i = 0, len = listeners.length; i < len; ++i) {
propagateToListener(promise, listeners[i]);
}
var psd = promise._PSD;
--psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();
if (numScheduledCalls === 0) {
// If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,
// and that no deferreds where listening to this rejection or success.
// Since there is a risk that our stack can contain application code that may
// do stuff after this code is finished that may generate new calls, we cannot
// call finalizers here.
++numScheduledCalls;
asap$1(function () {
if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors
}, []);
}
}
function propagateToListener(promise, listener) {
if (promise._state === null) {
promise._listeners.push(listener);
return;
}
var cb = promise._state ? listener.onFulfilled : listener.onRejected;
if (cb === null) {
// This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()
return (promise._state ? listener.resolve : listener.reject)(promise._value);
}
var psd = listener.psd;
++psd.ref;
++numScheduledCalls;
asap$1(callListener, [cb, promise, listener]);
}
function callListener(cb, promise, listener) {
var outerScope = PSD;
var psd = listener.psd;
try {
if (psd !== outerScope) {
// **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment.
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
// Set static variable currentFulfiller to the promise that is being fullfilled,
// so that we connect the chain of promises (for long stacks support)
currentFulfiller = promise;
// Call callback and resolve our listener with it's return value.
var value = promise._value,
ret;
if (promise._state) {
ret = cb(value);
} else {
if (rejectingErrors.length) rejectingErrors = [];
ret = cb(value);
if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.
}
listener.resolve(ret);
} catch (e) {
// Exception thrown in callback. Reject our listener.
listener.reject(e);
} finally {
// Restore PSD, env and currentFulfiller.
if (psd !== outerScope) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment
}
currentFulfiller = null;
if (--numScheduledCalls === 0) finalizePhysicalTick();
--psd.ref || psd.finalize();
}
}
function getStack(promise, stacks, limit) {
if (stacks.length === limit) return stacks;
var stack = "";
if (promise._state === false) {
var failure = promise._value,
errorName,
message;
if (failure != null) {
errorName = failure.name || "Error";
message = failure.message || failure;
stack = prettyStack(failure, 0);
} else {
errorName = failure; // If error is undefined or null, show that.
message = "";
}
stacks.push(errorName + (message ? ": " + message : "") + stack);
}
if (debug) {
stack = prettyStack(promise._stackHolder, 2);
if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);
if (promise._prev) getStack(promise._prev, stacks, limit);
}
return stacks;
}
function linkToPreviousPromise(promise, prev) {
// Support long stacks by linking to previous completed promise.
var numPrev = prev ? prev._numPrev + 1 : 0;
if (numPrev < LONG_STACKS_CLIP_LIMIT) {
// Prohibit infinite Promise loops to get an infinite long memory consuming "tail".
promise._prev = prev;
promise._numPrev = numPrev;
}
}
/* The callback to schedule with setImmediate() or setTimeout().
It runs a virtual microtick and executes any callback registered in microtickQueue.
*/
function physicalTick() {
beginMicroTickScope() && endMicroTickScope();
}
function beginMicroTickScope() {
var wasRootExec = isOutsideMicroTick;
isOutsideMicroTick = false;
needsNewPhysicalTick = false;
return wasRootExec;
}
/* Executes micro-ticks without doing try..catch.
This can be possible because we only use this internally and
the registered functions are exception-safe (they do try..catch
internally before calling any external method). If registering
functions in the microtickQueue that are not exception-safe, this
would destroy the framework and make it instable. So we don't export
our asap method.
*/
function endMicroTickScope() {
var callbacks, i, l;
do {
while (microtickQueue.length > 0) {
callbacks = microtickQueue;
microtickQueue = [];
l = callbacks.length;
for (i = 0; i < l; ++i) {
var item = callbacks[i];
item[0].apply(null, item[1]);
}
}
} while (microtickQueue.length > 0);
isOutsideMicroTick = true;
needsNewPhysicalTick = true;
}
function finalizePhysicalTick() {
var unhandledErrs = unhandledErrors;
unhandledErrors = [];
unhandledErrs.forEach(function (p) {
p._PSD.onunhandled.call(null, p._value, p);
});
var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.
var i = finalizers.length;
while (i) {
finalizers[--i]();
}
}
function run_at_end_of_this_or_next_physical_tick(fn) {
function finalizer() {
fn();
tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);
}
tickFinalizers.push(finalizer);
++numScheduledCalls;
asap$1(function () {
if (--numScheduledCalls === 0) finalizePhysicalTick();
}, []);
}
function addPossiblyUnhandledError(promise) {
// Only add to unhandledErrors if not already there. The first one to add to this list
// will be upon the first rejection so that the root cause (first promise in the
// rejection chain) is the one listed.
if (!unhandledErrors.some(function (p) {
return p._value === promise._value;
})) unhandledErrors.push(promise);
}
function markErrorAsHandled(promise) {
// Called when a reject handled is actually being called.
// Search in unhandledErrors for any promise whos _value is this promise_value (list
// contains only rejected promises, and only one item per error)
var i = unhandledErrors.length;
while (i) {
if (unhandledErrors[--i]._value === promise._value) {
// Found a promise that failed with this same error object pointer,
// Remove that since there is a listener that actually takes care of it.
unhandledErrors.splice(i, 1);
return;
}
}
}
// By default, log uncaught errors to the console
function defaultErrorHandler(e) {
console.warn('Unhandled rejection: ' + (e.stack || e));
}
function PromiseReject(reason) {
return new Promise(INTERNAL, false, reason);
}
function wrap(fn, errorCatcher) {
var psd = PSD;
return function () {
var wasRootExec = beginMicroTickScope(),
outerScope = PSD;
try {
if (outerScope !== psd) {
// **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
return fn.apply(this, arguments);
} catch (e) {
errorCatcher && errorCatcher(e);
} finally {
if (outerScope !== psd) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment
}
if (wasRootExec) endMicroTickScope();
}
};
}
function newScope(fn, a1, a2, a3) {
var parent = PSD,
psd = Object.create(parent);
psd.parent = parent;
psd.ref = 0;
psd.global = false;
// **KEEP** psd.env = wrappers.wrap(psd);
// unhandleds and onunhandled should not be specifically set here.
// Leave them on parent prototype.
// unhandleds.push(err) will push to parent's prototype
// onunhandled() will call parents onunhandled (with this scope's this-pointer though!)
++parent.ref;
psd.finalize = function () {
--this.parent.ref || this.parent.finalize();
};
var rv = usePSD(psd, fn, a1, a2, a3);
if (psd.ref === 0) psd.finalize();
return rv;
}
function usePSD(psd, fn, a1, a2, a3) {
var outerScope = PSD;
try {
if (psd !== outerScope) {
// **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment.
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
return fn(a1, a2, a3);
} finally {
if (psd !== outerScope) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment.
}
}
}
var UNHANDLEDREJECTION = "unhandledrejection";
function globalError(err, promise) {
var rv;
try {
rv = promise.onuncatched(err);
} catch (e) {}
if (rv !== false) try {
var event,
eventData = { promise: promise, reason: err };
if (_global.document && document.createEvent) {
event = document.createEvent('Event');
event.initEvent(UNHANDLEDREJECTION, true, true);
extend(event, eventData);
} else if (_global.CustomEvent) {
event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData });
extend(event, eventData);
}
if (event && _global.dispatchEvent) {
dispatchEvent(event);
if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)
// No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.
try {
_global.onunhandledrejection(event);
} catch (_) {}
}
if (!event.defaultPrevented) {
// Backward compatibility: fire to events registered at Promise.on.error
Promise.on.error.fire(err, promise);
}
} catch (e) {}
}
/* **KEEP**
export function wrapPromise(PromiseClass) {
var proto = PromiseClass.prototype;
var origThen = proto.then;
wrappers.add({
snapshot: () => proto.then,
restore: value => {proto.then = value;},
wrap: () => patchedThen
});
function patchedThen (onFulfilled, onRejected) {
var promise = this;
var onFulfilledProxy = wrap(function(value){
var rv = value;
if (onFulfilled) {
rv = onFulfilled(rv);
if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.
}
--PSD.ref || PSD.finalize();
return rv;
});
var onRejectedProxy = wrap(function(err){
promise._$err = err;
var unhandleds = PSD.unhandleds;
var idx = unhandleds.length,
rv;
while (idx--) if (unhandleds[idx]._$err === err) break;
if (onRejected) {
if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled.
rv = onRejected(err);
if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.
} else {
if (idx === -1) unhandleds.push(promise);
rv = PromiseClass.reject(err);
rv._$nointercept = true; // Prohibit eternal loop.
}
--PSD.ref || PSD.finalize();
return rv;
});
if (this._$nointercept) return origThen.apply(this, arguments);
++PSD.ref;
return origThen.call(this, onFulfilledProxy, onRejectedProxy);
}
}
// Global Promise wrapper
if (_global.Promise) wrapPromise(_global.Promise);
*/
doFakeAutoComplete(function () {
// Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.
asap$1 = function (fn, args) {
setTimeout(function () {
fn.apply(null, args);
}, 0);
};
});
function rejection(err, uncaughtHandler) {
// Get the call stack and return a rejected promise.
var rv = Promise.reject(err);
return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv;
}
/*
* Dexie.js - a minimalistic wrapper for IndexedDB
* ===============================================
*
* By David Fahlander, david.fahlander@gmail.com
*
* Version 1.5.1, Tue Nov 01 2016
*
* http://dexie.org
*
* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
*/
var DEXIE_VERSION = '1.5.1';
var maxString = String.fromCharCode(65535);
var maxKey = function () {
try {
IDBKeyRange.only([[]]);return [[]];
} catch (e) {
return maxString;
}
}();
var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.";
var STRING_EXPECTED = "String expected.";
var connections = [];
var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);
var hasIEDeleteObjectStoreBug = isIEOrEdge;
var hangsOnDeleteLargeKeyRange = isIEOrEdge;
var dexieStackFrameFilter = function (frame) {
return !/(dexie\.js|dexie\.min\.js)/.test(frame);
};
setDebug(debug, dexieStackFrameFilter);
function Dexie(dbName, options) {
/// <param name="options" type="Object" optional="true">Specify only if you wich to control which addons that should run on this instance</param>
var deps = Dexie.dependencies;
var opts = extend({
// Default Options
addons: Dexie.addons, // Pick statically registered addons by default
autoOpen: true, // Don't require db.open() explicitely.
indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env.
IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env.
}, options);
var addons = opts.addons,
autoOpen = opts.autoOpen,
indexedDB = opts.indexedDB,
IDBKeyRange = opts.IDBKeyRange;
var globalSchema = this._dbSchema = {};
var versions = [];
var dbStoreNames = [];
var allTables = {};
///<var type="IDBDatabase" />
var idbdb = null; // Instance of IDBDatabase
var dbOpenError = null;
var isBeingOpened = false;
var openComplete = false;
var READONLY = "readonly",
READWRITE = "readwrite";
var db = this;
var dbReadyResolve,
dbReadyPromise = new Promise(function (resolve) {
dbReadyResolve = resolve;
}),
cancelOpen,
openCanceller = new Promise(function (_, reject) {
cancelOpen = reject;
});
var autoSchema = true;
var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),
hasGetAll;
function init() {
// Default subscribers to "versionchange" and "blocked".
// Can be overridden by custom handlers. If custom handlers return false, these default
// behaviours will be prevented.
db.on("versionchange", function (ev) {
// Default behavior for versionchange event is to close database connection.
// Caller can override this behavior by doing db.on("versionchange", function(){ return false; });
// Let's not block the other window from making it's delete() or open() call.
// NOTE! This event is never fired in IE,Edge or Safari.
if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \'' + db.name + '\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \'' + db.name + '\'. Closing db now to resume the delete request.');
db.close();
// In many web applications, it would be recommended to force window.reload()
// when this event occurs. To do that, subscribe to the versionchange event
// and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)
// The reason for this is that your current web app obviously has old schema code that needs
// to be updated. Another window got a newer version of the app and needs to upgrade DB but
// your window is blocking it unless we close it here.
});
db.on("blocked", function (ev) {
if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\'' + db.name + '\') was blocked');else console.warn('Upgrade \'' + db.name + '\' blocked by other connection holding version ' + ev.oldVersion / 10);
});
}
//
//
//
// ------------------------- Versioning Framework---------------------------
//
//
//
this.version = function (versionNumber) {
/// <param name="versionNumber" type="Number"></param>
/// <returns type="Version"></returns>
if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open");
this.verno = Math.max(this.verno, versionNumber);
var versionInstance = versions.filter(function (v) {
return v._cfg.version === versionNumber;
})[0];
if (versionInstance) return versionInstance;
versionInstance = new Version(versionNumber);
versions.push(versionInstance);
versions.sort(lowerVersionFirst);
return versionInstance;
};
function Version(versionNumber) {
this._cfg = {
version: versionNumber,
storesSource: null,
dbschema: {},
tables: {},
contentUpgrade: null
};
this.stores({}); // Derive earlier schemas by default.
}
extend(Version.prototype, {
stores: function (stores) {
/// <summary>
/// Defines the schema for a particular version
/// </summary>
/// <param name="stores" type="Object">
/// Example: <br/>
/// {users: "id++,first,last,&amp;username,*email", <br/>
/// passwords: "id++,&amp;username"}<br/>
/// <br/>
/// Syntax: {Table: "[primaryKey][++],[&amp;][*]index1,[&amp;][*]index2,..."}<br/><br/>
/// Special characters:<br/>
/// "&amp;" means unique key, <br/>
/// "*" means value is multiEntry, <br/>
/// "++" means auto-increment and only applicable for primary key <br/>
/// </param>
this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;
// Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.
var storesSpec = {};
versions.forEach(function (version) {
// 'versions' is always sorted by lowest version first.
extend(storesSpec, version._cfg.storesSource);
});
var dbschema = this._cfg.dbschema = {};
this._parseStoresSpec(storesSpec, dbschema);
// Update the latest schema to this version
// Update API
globalSchema = db._dbSchema = dbschema;
removeTablesApi([allTables, db, Transaction.prototype]);
setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema);
dbStoreNames = keys(dbschema);
return this;
},
upgrade: function (upgradeFunction) {
/// <param name="upgradeFunction" optional="true">Function that performs upgrading actions.</param>
var self = this;
fakeAutoComplete(function () {
upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear.
});
this._cfg.contentUpgrade = upgradeFunction;
return this;
},
_parseStoresSpec: function (stores, outSchema) {
keys(stores).forEach(function (tableName) {
if (stores[tableName] !== null) {
var instanceTemplate = {};
var indexes = parseIndexSyntax(stores[tableName]);
var primKey = indexes.shift();
if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued");
if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);
indexes.forEach(function (idx) {
if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)");
if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string");
setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () {
return "";
}) : "");
});
outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);
}
});
}
});
function runUpgraders(oldVersion, idbtrans, reject) {
var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);
trans.create(idbtrans);
trans._completion.catch(reject);
var rejectTransaction = trans._reject.bind(trans);
newScope(function () {
PSD.trans = trans;
if (oldVersion === 0) {
// Create tables:
keys(globalSchema).forEach(function (tableName) {
createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);
});
Promise.follow(function () {
return db.on.populate.fire(trans);
}).catch(rejectTransaction);
} else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);
});
}
function updateTablesAndIndexes(oldVersion, trans, idbtrans) {
// Upgrade version to version, step-by-step from oldest to newest version.
// Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)
var queue = [];
var oldVersionStruct = versions.filter(function (version) {
return version._cfg.version === oldVersion;
})[0];
if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing");
globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;
var anyContentUpgraderHasRun = false;
var versToRun = versions.filter(function (v) {
return v._cfg.version > oldVersion;
});
versToRun.forEach(function (version) {
/// <param name="version" type="Version"></param>
queue.push(function () {
var oldSchema = globalSchema;
var newSchema = version._cfg.dbschema;
adjustToExistingIndexNames(oldSchema, idbtrans);
adjustToExistingIndexNames(newSchema, idbtrans);
globalSchema = db._dbSchema = newSchema;
var diff = getSchemaDiff(oldSchema, newSchema);
// Add tables
diff.add.forEach(function (tuple) {
createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);
});
// Change tables
diff.change.forEach(function (change) {
if (change.recreate) {
throw new exceptions.Upgrade("Not yet support for changing primary key");
} else {
var store = idbtrans.objectStore(change.name);
// Add indexes
change.add.forEach(function (idx) {
addIndex(store, idx);
});
// Update indexes
change.change.forEach(function (idx) {
store.deleteIndex(idx.name);
addIndex(store, idx);
});
// Delete indexes
change.del.forEach(function (idxName) {
store.deleteIndex(idxName);
});
}
});
if (version._cfg.contentUpgrade) {
anyContentUpgraderHasRun = true;
return Promise.follow(function () {
version._cfg.contentUpgrade(trans);
});
}
});
queue.push(function (idbtrans) {
if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) {
// Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.
var newSchema = version._cfg.dbschema;
// Delete old tables
deleteRemovedTables(newSchema, idbtrans);
}
});
});
// Now, create a queue execution engine
function runQueue() {
return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve();
}
return runQueue().then(function () {
createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)
});
}
function getSchemaDiff(oldSchema, newSchema) {
var diff = {
del: [], // Array of table names
add: [], // Array of [tableName, newDefinition]
change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}
};
for (var table in oldSchema) {
if (!newSchema[table]) diff.del.push(table);
}
for (table in newSchema) {
var oldDef = oldSchema[table],
newDef = newSchema[table];
if (!oldDef) {
diff.add.push([table, newDef]);
} else {
var change = {
name: table,
def: newDef,
recreate: false,
del: [],
add: [],
change: []
};
if (oldDef.primKey.src !== newDef.primKey.src) {
// Primary key has changed. Remove and re-add table.
change.recreate = true;
diff.change.push(change);
} else {
// Same primary key. Just find out what differs:
var oldIndexes = oldDef.idxByName;
var newIndexes = newDef.idxByName;
for (var idxName in oldIndexes) {
if (!newIndexes[idxName]) change.del.push(idxName);
}
for (idxName in newIndexes) {
var oldIdx = oldIndexes[idxName],
newIdx = newIndexes[idxName];
if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);
}
if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {
diff.change.push(change);
}
}
}
}
return diff;
}
function createTable(idbtrans, tableName, primKey, indexes) {
/// <param name="idbtrans" type="IDBTransaction"></param>
var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });
indexes.forEach(function (idx) {
addIndex(store, idx);
});
return store;
}
function createMissingTables(newSchema, idbtrans) {
keys(newSchema).forEach(function (tableName) {
if (!idbtrans.db.objectStoreNames.contains(tableName)) {
createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);
}
});
}
function deleteRemovedTables(newSchema, idbtrans) {
for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {
var storeName = idbtrans.db.objectStoreNames[i];
if (newSchema[storeName] == null) {
idbtrans.db.deleteObjectStore(storeName);
}
}
}
function addIndex(store, idx) {
store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });
}
function dbUncaught(err) {
return db.on.error.fire(err);
}
//
//
// Dexie Protected API
//
//
this._allTables = allTables;
this._tableFactory = function createTable(mode, tableSchema) {
/// <param name="tableSchema" type="TableSchema"></param>
if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema);
};
this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {
return new Transaction(mode, storeNames, dbschema, parentTransaction);
};
/* Generate a temporary transaction when db operations are done outside a transactino scope.
*/
function tempTransaction(mode, storeNames, fn) {
// Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it.
if (!openComplete && !PSD.letThrough) {
if (!isBeingOpened) {
if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught);
db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.
}
return dbReadyPromise.then(function () {
return tempTransaction(mode, storeNames, fn);
});
} else {
var trans = db._createTransaction(mode, storeNames, globalSchema);
return trans._promise(mode, function (resolve, reject) {
newScope(function () {
// OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.
PSD.trans = trans;
fn(resolve, reject, trans);
});
}).then(function (result) {
// Instead of resolving value directly, wait with resolving it until transaction has completed.
// Otherwise the data would not be in the DB if requesting it in the then() operation.
// Specifically, to ensure that the following expression will work:
//
// db.friends.put({name: "Arne"}).then(function () {
// db.friends.where("name").equals("Arne").count(function(count) {
// assert (count === 1);
// });
// });
//
return trans._completion.then(function () {
return result;
});
}); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.
trans._reject(err);
return rejection(err);
});*/
}
}
this._whenReady = function (fn) {
return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) {
if (!isBeingOpened) {
if (!autoOpen) {
reject(new exceptions.DatabaseClosed());
return;
}
db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.
}
dbReadyPromise.then(function () {
fn(resolve, reject);
});
}).uncaught(dbUncaught);
};
//
//
//
//
// Dexie API
//
//
//
this.verno = 0;
this.open = function () {
if (isBeingOpened || idbdb) return dbReadyPromise.then(function () {
return dbOpenError ? rejection(dbOpenError, dbUncaught) : db;
});
debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.
isBeingOpened = true;
dbOpenError = null;
openComplete = false;
// Function pointers to call when the core opening process completes.
var resolveDbReady = dbReadyResolve,
// upgradeTransaction to abort on failure.
upgradeTransaction = null;
return Promise.race([openCanceller, new Promise(function (resolve, reject) {
doFakeAutoComplete(function () {
return resolve();
});
// Make sure caller has specified at least one version
if (versions.length > 0) autoSchema = false;
// Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:
// IE fails when deleting objectStore after reading from it.
// A future version of Dexie.js will stopover an intermediate version to workaround this.
// At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.
// If no API, throw!
if (!indexedDB) throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill.");
var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));
if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134
req.onerror = wrap(eventRejectHandler(reject));
req.onblocked = wrap(fireOnBlocked);
req.onupgradeneeded = wrap(function (e) {
upgradeTransaction = req.transaction;
if (autoSchema && !db._allowEmptyDB) {
// Unless an addon has specified db._allowEmptyDB, lets make the call fail.
// Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.
// If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we
// do not create a new database by accident here.
req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!
upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)
// Close database and delete it.
req.result.close();
var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!
delreq.onsuccess = delreq.onerror = wrap(function () {
reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist'));
});
} else {
upgradeTransaction.onerror = wrap(eventRejectHandler(reject));
var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.
runUpgraders(oldVer / 10, upgradeTransaction, reject, req);
}
}, reject);
req.onsuccess = wrap(function () {
// Core opening procedure complete. Now let's just record some stuff.
upgradeTransaction = null;
idbdb = req.result;
connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.
if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) {
try {
adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));
} catch (e) {
// Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.
}
}
idbdb.onversionchange = wrap(function (ev) {
db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)
db.on("versionchange").fire(ev);
});
if (!hasNativeGetDatabaseNames) {
// Update localStorage with list of database names
globalDatabaseList(function (databaseNames) {
if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);
});
}
resolve();
}, reject);
})]).then(function () {
// Before finally resolving the dbReadyPromise and this promise,
// call and await all on('ready') subscribers:
// Dexie.vip() makes subscribers able to use the database while being opened.
// This is a must since these subscribers take part of the opening procedure.
return Dexie.vip(db.on.ready.fire);
}).then(function () {
// Resolve the db.open() with the db instance.
isBeingOpened = false;
return db;
}).catch(function (err) {
try {
// Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.
upgradeTransaction && upgradeTransaction.abort();
} catch (e) {}
isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).
db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.
// A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.
dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.
return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught().
}).finally(function () {
openComplete = true;
resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.
});
};
this.close = function () {
var idx = connections.indexOf(db);
if (idx >= 0) connections.splice(idx, 1);
if (idbdb) {
try {
idbdb.close();
} catch (e) {}
idbdb = null;
}
autoOpen = false;
dbOpenError = new exceptions.DatabaseClosed();
if (isBeingOpened) cancelOpen(dbOpenError);
// Reset dbReadyPromise promise:
dbReadyPromise = new Promise(function (resolve) {
dbReadyResolve = resolve;
});
openCanceller = new Promise(function (_, reject) {
cancelOpen = reject;
});
};
this.delete = function () {
var hasArguments = arguments.length > 0;
return new Promise(function (resolve, reject) {
if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()");
if (isBeingOpened) {
dbReadyPromise.then(doDelete);
} else {
doDelete();
}
function doDelete() {
db.close();
var req = indexedDB.deleteDatabase(dbName);
req.onsuccess = wrap(function () {
if (!hasNativeGetDatabaseNames) {
globalDatabaseList(function (databaseNames) {
var pos = databaseNames.indexOf(dbName);
if (pos >= 0) return databaseNames.splice(pos, 1);
});
}
resolve();
});
req.onerror = wrap(eventRejectHandler(reject));
req.onblocked = fireOnBlocked;
}
}).uncaught(dbUncaught);
};
this.backendDB = function () {
return idbdb;
};
this.isOpen = function () {
return idbdb !== null;
};
this.hasFailed = function () {
return dbOpenError !== null;
};
this.dynamicallyOpened = function () {
return autoSchema;
};
//
// Properties
//
this.name = dbName;
// db.tables - an array of all Table instances.
setProp(this, "tables", {
get: function () {
/// <returns type="Array" elementType="WriteableTable" />
return keys(allTables).map(function (name) {
return allTables[name];
});
}
});
//
// Events
//
this.on = Events(this, "error", "populate", "blocked", "versionchange", { ready: [promisableChain, nop] });
this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe);
this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe);
this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {
return function (subscriber, bSticky) {
Dexie.vip(function () {
if (openComplete) {
// Database already open. Call subscriber asap.
if (!dbOpenError) Promise.resolve().then(subscriber);
// bSticky: Also subscribe to future open sucesses (after close / reopen)
if (bSticky) subscribe(subscriber);
} else {
// Database not yet open. Subscribe to it.
subscribe(subscriber);
// If bSticky is falsy, make sure to unsubscribe subscriber when fired once.
if (!bSticky) subscribe(function unsubscribe() {
db.on.ready.unsubscribe(subscriber);
db.on.ready.unsubscribe(unsubscribe);
});
}
});
};
});
fakeAutoComplete(function () {
db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));
db.on("error").fire(new Error());
});
this.transaction = function (mode, tableInstances, scopeFunc) {
/// <summary>
///
/// </summary>
/// <param name="mode" type="String">"r" for readonly, or "rw" for readwrite</param>
/// <param name="tableInstances">Table instance, Array of Table instances, String or String Array of object stores to include in the transaction</param>
/// <param name="scopeFunc" type="Function">Function to execute with transaction</param>
// Let table arguments be all arguments between mode and last argument.
var i = arguments.length;
if (i < 2) throw new exceptions.InvalidArgument("Too few arguments");
// Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)
// and clone arguments except the first one into local var 'args'.
var args = new Array(i - 1);
while (--i) {
args[i - 1] = arguments[i];
} // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.
scopeFunc = args.pop();
var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.
var parentTransaction = PSD.trans;
// Check if parent transactions is bound to this db instance, and if caller wants to reuse it
if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;
var onlyIfCompatible = mode.indexOf('?') !== -1;
mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.
try {
//
// Get storeNames from arguments. Either through given table instances, or through given table names.
//
var storeNames = tables.map(function (table) {
var storeName = table instanceof Table ? table.name : table;
if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");
return storeName;
});
//
// Resolve mode. Allow shortcuts "r" and "rw".
//
if (mode == "r" || mode == READONLY) mode = READONLY;else if (mode == "rw" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode);
if (parentTransaction) {
// Basic checks
if (parentTransaction.mode === READONLY && mode === READWRITE) {
if (onlyIfCompatible) {
// Spawn new transaction instead.
parentTransaction = null;
} else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");
}
if (parentTransaction) {
storeNames.forEach(function (storeName) {
if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {
if (onlyIfCompatible) {
// Spawn new transaction instead.
parentTransaction = null;
} else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction.");
}
});
}
}
} catch (e) {
return parentTransaction ? parentTransaction._promise(null, function (_, reject) {
reject(e);
}) : rejection(e, dbUncaught);
}
// If this is a sub-transaction, lock the parent and then launch the sub-transaction.
return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady(enterTransactionScope);
function enterTransactionScope(resolve) {
var parentPSD = PSD;
resolve(Promise.resolve().then(function () {
return newScope(function () {
// Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().
PSD.transless = PSD.transless || parentPSD;
// Our transaction.
//return new Promise((resolve, reject) => {
var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);
// Let the transaction instance be part of a Promise-specific data (PSD) value.
PSD.trans = trans;
if (parentTransaction) {
// Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)
trans.idbtrans = parentTransaction.idbtrans;
} else {
trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.
}
// Provide arguments to the scope function (for backward compatibility)
var tableArgs = storeNames.map(function (name) {
return allTables[name];
});
tableArgs.push(trans);
var returnValue;
return Promise.follow(function () {
// Finally, call the scope function with our table and transaction arguments.
returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.
if (returnValue) {
if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {
// scopeFunc returned an iterator with throw-support. Handle yield as await.
returnValue = awaitIterator(returnValue);
} else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) {
throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString());
}
}
}).uncaught(dbUncaught).then(function () {
if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion.
return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well.
}).then(function () {
return returnValue;
}).catch(function (e) {
//reject(e);
trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!
return rejection(e);
});
//});
});
}));
}
};
this.table = function (tableName) {
/// <returns type="WriteableTable"></returns>
if (fake && autoSchema) return new WriteableTable(tableName);
if (!hasOwn(allTables, tableName)) {
throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist');
}
return allTables[tableName];
};
//
//
//
// Table Class
//
//
//
function Table(name, tableSchema, collClass) {
/// <param name="name" type="String"></param>
this.name = name;
this.schema = tableSchema;
this.hook = allTables[name] ? allTables[name].hook : Events(null, {
"creating": [hookCreatingChain, nop],
"reading": [pureFunctionChain, mirror],
"updating": [hookUpdatingChain, nop],
"deleting": [hookDeletingChain, nop]
});
this._collClass = collClass || Collection;
}
props(Table.prototype, {
//
// Table Protected Methods
//
_trans: function getTransaction(mode, fn, writeLocked) {
var trans = PSD.trans;
return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn);
},
_idbstore: function getIDBObjectStore(mode, fn, writeLocked) {
if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.
var trans = PSD.trans,
tableName = this.name;
function supplyIdbStore(resolve, reject, trans) {
fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);
}
return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore);
},
//
// Table Public Methods
//
get: function (key, cb) {
var self = this;
return this._idbstore(READONLY, function (resolve, reject, idbstore) {
fake && resolve(self.schema.instanceTemplate);
var req = idbstore.get(key);
req.onerror = eventRejectHandler(reject);
req.onsuccess = wrap(function () {
resolve(self.hook.reading.fire(req.result));
}, reject);
}).then(cb);
},
where: function (indexName) {
return new WhereClause(this, indexName);
},
count: function (cb) {
return this.toCollection().count(cb);
},
offset: function (offset) {
return this.toCollection().offset(offset);
},
limit: function (numRows) {
return this.toCollection().limit(numRows);
},
reverse: function () {
return this.toCollection().reverse();
},
filter: function (filterFunction) {
return this.toCollection().and(filterFunction);
},
each: function (fn) {
return this.toCollection().each(fn);
},
toArray: function (cb) {
return this.toCollection().toArray(cb);
},
orderBy: function (index) {
return new this._collClass(new WhereClause(this, index));
},
toCollection: function () {
return new this._collClass(new WhereClause(this));
},
mapToClass: function (constructor, structure) {
/// <summary>
/// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making
/// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.
/// </summary>
/// <param name="constructor">Constructor function representing the class.</param>
/// <param name="structure" optional="true">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], password}</param>
this.schema.mappedClass = constructor;
var instanceTemplate = Object.create(constructor.prototype);
if (structure) {
// structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.
applyStructure(instanceTemplate, structure);
}
this.schema.instanceTemplate = instanceTemplate;
// Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class
// no matter which method to use for reading (Table.get() or Table.where(...)... )
var readHook = function (obj) {
if (!obj) return obj; // No valid object. (Value is null). Return as is.
// Create a new object that derives from constructor:
var res = Object.create(constructor.prototype);
// Clone members:
for (var m in obj) {
if (hasOwn(obj, m)) try {
res[m] = obj[m];
} catch (_) {}
}return res;
};
if (this.schema.readHook) {
this.hook.reading.unsubscribe(this.schema.readHook);
}
this.schema.readHook = readHook;
this.hook("reading", readHook);
return constructor;
},
defineClass: function (structure) {
/// <summary>
/// Define all members of the class that represents the table. This will help code completion of when objects are read from the database
/// as well as making it possible to extend the prototype of the returned constructor function.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
return this.mapToClass(Dexie.defineClass(structure), structure);
}
});
//
//
//
// WriteableTable Class (extends Table)
//
//
//
function WriteableTable(name, tableSchema, collClass) {
Table.call(this, name, tableSchema, collClass || WriteableCollection);
}
function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {
return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) {
errorList.push(e);
done && done();
});
}
function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {
// If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],
// else keysOrTuples must be just an array of keys: [key1, key2, ...].
return new Promise(function (resolve, reject) {
var len = keysOrTuples.length,
lastItem = len - 1;
if (len === 0) return resolve();
if (!hasDeleteHook) {
for (var i = 0; i < len; ++i) {
var req = idbstore.delete(keysOrTuples[i]);
req.onerror = wrap(eventRejectHandler(reject));
if (i === lastItem) req.onsuccess = wrap(function () {
return resolve();
});
}
} else {
var hookCtx,
errorHandler = hookedEventRejectHandler(reject),
successHandler = hookedEventSuccessHandler(null);
tryCatch(function () {
for (var i = 0; i < len; ++i) {
hookCtx = { onsuccess: null, onerror: null };
var tuple = keysOrTuples[i];
deletingHook.call(hookCtx, tuple[0], tuple[1], trans);
var req = idbstore.delete(tuple[0]);
req._hookCtx = hookCtx;
req.onerror = errorHandler;
if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler;
}
}, function (err) {
hookCtx.onerror && hookCtx.onerror(err);
throw err;
});
}
}).uncaught(dbUncaught);
}
derive(WriteableTable).from(Table).extend({
bulkDelete: function (keys$$1) {
if (this.hook.deleting.fire === nop) {
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
resolve(bulkDelete(idbstore, trans, keys$$1, false, nop));
});
} else {
return this.where(':id').anyOf(keys$$1).delete().then(function () {}); // Resolve with undefined.
}
},
bulkPut: function (objects, keys$$1) {
var _this = this;
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");
if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");
if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
if (objects.length === 0) return resolve(); // Caller provided empty list.
var done = function (result) {
if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));
};
var req,
errorList = [],
errorHandler,
numObjs = objects.length,
table = _this;
if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) {
//
// Standard Bulk (no 'creating' or 'updating' hooks to care about)
//
errorHandler = BulkErrorHandlerCatchAll(errorList);
for (var i = 0, l = objects.length; i < l; ++i) {
req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]);
req.onerror = errorHandler;
}
// Only need to catch success or error on the last operation
// according to the IDB spec.
req.onerror = BulkErrorHandlerCatchAll(errorList, done);
req.onsuccess = eventSuccessHandler(done);
} else {
var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) {
return getByKeyPath(o, idbstore.keyPath);
});
// Generate map of {[key]: object}
var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) {
return key != null && [key, objects[i]];
});
var promise = !effectiveKeys ?
// Auto-incremented key-less objects only without any keys argument.
table.bulkAdd(objects) :
// Keys provided. Either as inbound in provided objects, or as a keys argument.
// Begin with updating those that exists in DB:
table.where(':id').anyOf(effectiveKeys.filter(function (key) {
return key != null;
})).modify(function () {
this.value = objectLookup[this.primKey];
objectLookup[this.primKey] = null; // Mark as "don't add this"
}).catch(ModifyError, function (e) {
errorList = e.failures; // No need to concat here. These are the first errors added.
}).then(function () {
// Now, let's examine which items didnt exist so we can add them:
var objsToAdd = [],
keysToAdd = keys$$1 && [];
// Iterate backwards. Why? Because if same key was used twice, just add the last one.
for (var i = effectiveKeys.length - 1; i >= 0; --i) {
var key = effectiveKeys[i];
if (key == null || objectLookup[key]) {
objsToAdd.push(objects[i]);
keys$$1 && keysToAdd.push(key);
if (key != null) objectLookup[key] = null; // Mark as "dont add again"
}
}
// The items are in reverse order so reverse them before adding.
// Could be important in order to get auto-incremented keys the way the caller
// would expect. Could have used unshift instead of push()/reverse(),
// but: http://jsperf.com/unshift-vs-reverse
objsToAdd.reverse();
keys$$1 && keysToAdd.reverse();
return table.bulkAdd(objsToAdd, keysToAdd);
}).then(function (lastAddedKey) {
// Resolve with key of the last object in given arguments to bulkPut():
var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.
return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;
});
promise.then(done).catch(BulkError, function (e) {
// Concat failure from ModifyError and reject using our 'done' method.
errorList = errorList.concat(e.failures);
done();
}).catch(reject);
}
}, "locked"); // If called from transaction scope, lock transaction til all steps are done.
},
bulkAdd: function (objects, keys$$1) {
var self = this,
creatingHook = this.hook.creating.fire;
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");
if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");
if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
if (objects.length === 0) return resolve(); // Caller provided empty list.
function done(result) {
if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));
}
var req,
errorList = [],
errorHandler,
successHandler,
numObjs = objects.length;
if (creatingHook !== nop) {
//
// There are subscribers to hook('creating')
// Must behave as documented.
//
var keyPath = idbstore.keyPath,
hookCtx;
errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);
successHandler = hookedEventSuccessHandler(null);
tryCatch(function () {
for (var i = 0, l = objects.length; i < l; ++i) {
hookCtx = { onerror: null, onsuccess: null };
var key = keys$$1 && keys$$1[i];
var obj = objects[i],
effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,
keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);
if (effectiveKey == null && keyToUse != null) {
if (keyPath) {
obj = deepClone(obj);
setByKeyPath(obj, keyPath, keyToUse);
} else {
key = keyToUse;
}
}
req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);
req._hookCtx = hookCtx;
if (i < l - 1) {
req.onerror = errorHandler;
if (hookCtx.onsuccess) req.onsuccess = successHandler;
}
}
}, function (err) {
hookCtx.onerror && hookCtx.onerror(err);
throw err;
});
req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);
req.onsuccess = hookedEventSuccessHandler(done);
} else {
//
// Standard Bulk (no 'creating' hook to care about)
//
errorHandler = BulkErrorHandlerCatchAll(errorList);
for (var i = 0, l = objects.length; i < l; ++i) {
req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]);
req.onerror = errorHandler;
}
// Only need to catch success or error on the last operation
// according to the IDB spec.
req.onerror = BulkErrorHandlerCatchAll(errorList, done);
req.onsuccess = eventSuccessHandler(done);
}
});
},
add: function (obj, key) {
/// <summary>
/// Add an object to the database. In case an object with same primary key already exists, the object will not be added.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert</param>
/// <param name="key" optional="true">Primary key</param>
var creatingHook = this.hook.creating.fire;
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
var hookCtx = { onsuccess: null, onerror: null };
if (creatingHook !== nop) {
var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined;
var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key.
if (effectiveKey == null && keyToUse != null) {
// Using "==" and "!=" to check for either null or undefined!
if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse;
}
}
try {
var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);
req._hookCtx = hookCtx;
req.onerror = hookedEventRejectHandler(reject);
req.onsuccess = hookedEventSuccessHandler(function (result) {
// TODO: Remove these two lines in next major release (2.0?)
// It's no good practice to have side effects on provided parameters
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, result);
resolve(result);
});
} catch (e) {
if (hookCtx.onerror) hookCtx.onerror(e);
throw e;
}
});
},
put: function (obj, key) {
/// <summary>
/// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert or update</param>
/// <param name="key" optional="true">Primary key</param>
var self = this,
creatingHook = this.hook.creating.fire,
updatingHook = this.hook.updating.fire;
if (creatingHook !== nop || updatingHook !== nop) {
//
// People listens to when("creating") or when("updating") events!
// We must know whether the put operation results in an CREATE or UPDATE.
//
return this._trans(READWRITE, function (resolve, reject, trans) {
// Since key is optional, make sure we get it from obj if not provided
var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath);
if (effectiveKey == null) {
// "== null" means checking for either null or undefined.
// No primary key. Must use add().
self.add(obj).then(resolve, reject);
} else {
// Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().
trans._lock(); // Needed because operation is splitted into modify() and add().
// clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.
obj = deepClone(obj);
self.where(":id").equals(effectiveKey).modify(function () {
// Replace extisting value with our object
// CRUD event firing handled in WriteableCollection.modify()
this.value = obj;
}).then(function (count) {
if (count === 0) {
// Object's key was not found. Add the object instead.
// CRUD event firing will be done in add()
return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.
} else {
return effectiveKey; // Resolve with the provided key.
}
}).finally(function () {
trans._unlock();
}).then(resolve, reject);
}
});
} else {
// Use the standard IDB put() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);
req.onerror = eventRejectHandler(reject);
req.onsuccess = function (ev) {
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);
resolve(req.result);
};
});
}
},
'delete': function (key) {
/// <param name="key">Primary key of the object to delete</param>
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.
return this.where(":id").equals(key).delete();
} else {
// No one listens. Use standard IDB delete() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.delete(key);
req.onerror = eventRejectHandler(reject);
req.onsuccess = function () {
resolve(req.result);
};
});
}
},
clear: function () {
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.
return this.toCollection().delete();
} else {
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.clear();
req.onerror = eventRejectHandler(reject);
req.onsuccess = function () {
resolve(req.result);
};
});
}
},
update: function (keyOrObject, modifications) {
if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object.");
if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {
// object to modify. Also modify given object with the modifications:
keys(modifications).forEach(function (keyPath) {
setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);
});
var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);
if (key === undefined) return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key"), dbUncaught);
return this.where(":id").equals(key).modify(modifications);
} else {
// key to modify
return this.where(":id").equals(keyOrObject).modify(modifications);
}
}
});
//
//
//
// Transaction Class
//
//
//
function Transaction(mode, storeNames, dbschema, parent) {
var _this2 = this;
/// <summary>
/// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.
/// </summary>
/// <param name="mode" type="String">Any of "readwrite" or "readonly"</param>
/// <param name="storeNames" type="Array">Array of table names to operate on</param>
this.db = db;
this.mode = mode;
this.storeNames = storeNames;
this.idbtrans = null;
this.on = Events(this, "complete", "error", "abort");
this.parent = parent || null;
this.active = true;
this._tables = null;
this._reculock = 0;
this._blockedFuncs = [];
this._psd = null;
this._dbschema = dbschema;
this._resolve = null;
this._reject = null;
this._completion = new Promise(function (resolve, reject) {
_this2._resolve = resolve;
_this2._reject = reject;
}).uncaught(dbUncaught);
this._completion.then(function () {
_this2.on.complete.fire();
}, function (e) {
_this2.on.error.fire(e);
_this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort();
_this2.active = false;
return rejection(e); // Indicate we actually DO NOT catch this error.
});
}
props(Transaction.prototype, {
//
// Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)
//
_lock: function () {
assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.
// Temporary set all requests into a pending queue if they are called before database is ready.
++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)
if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;
return this;
},
_unlock: function () {
assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.
if (--this._reculock === 0) {
if (!PSD.global) PSD.lockOwnerFor = null;
while (this._blockedFuncs.length > 0 && !this._locked()) {
var fnAndPSD = this._blockedFuncs.shift();
try {
usePSD(fnAndPSD[1], fnAndPSD[0]);
} catch (e) {}
}
}
return this;
},
_locked: function () {
// Checks if any write-lock is applied on this transaction.
// To simplify the Dexie API for extension implementations, we support recursive locks.
// This is accomplished by using "Promise Specific Data" (PSD).
// PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).
// PSD is local to code executing on top of the call stacks of any of any code executed by Promise():
// * callback given to the Promise() constructor (function (resolve, reject){...})
// * callbacks given to then()/catch()/finally() methods (function (value){...})
// If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.
// Derivation is done so that the inner PSD __proto__ points to the outer PSD.
// PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.
return this._reculock && PSD.lockOwnerFor !== this;
},
create: function (idbtrans) {
var _this3 = this;
assert(!this.idbtrans);
if (!idbtrans && !idbdb) {
switch (dbOpenError && dbOpenError.name) {
case "DatabaseClosedError":
// Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()
throw new exceptions.DatabaseClosed(dbOpenError);
case "MissingAPIError":
// Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()
throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);
default:
// Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!
throw new exceptions.OpenFailed(dbOpenError);
}
}
if (!this.active) throw new exceptions.TransactionInactive();
assert(this._completion._state === null);
idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);
idbtrans.onerror = wrap(function (ev) {
preventDefault(ev); // Prohibit default bubbling to window.error
_this3._reject(idbtrans.error);
});
idbtrans.onabort = wrap(function (ev) {
preventDefault(ev);
_this3.active && _this3._reject(new exceptions.Abort());
_this3.active = false;
_this3.on("abort").fire(ev);
});
idbtrans.oncomplete = wrap(function () {
_this3.active = false;
_this3._resolve();
});
return this;
},
_promise: function (mode, fn, bWriteLock) {
var self = this;
var p = self._locked() ?
// Read lock always. Transaction is write-locked. Wait for mutex.
new Promise(function (resolve, reject) {
self._blockedFuncs.push([function () {
self._promise(mode, fn, bWriteLock).then(resolve, reject);
}, PSD]);
}) : newScope(function () {
var p_ = self.active ? new Promise(function (resolve, reject) {
if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly");
if (!self.idbtrans && mode) self.create();
if (bWriteLock) self._lock(); // Write lock if write operation is requested
fn(resolve, reject, self);
}) : rejection(new exceptions.TransactionInactive());
if (self.active && bWriteLock) p_.finally(function () {
self._unlock();
});
return p_;
});
p._lib = true;
return p.uncaught(dbUncaught);
},
//
// Transaction Public Properties and Methods
//
abort: function () {
this.active && this._reject(new exceptions.Abort());
this.active = false;
},
tables: {
get: deprecated("Transaction.tables", function () {
return arrayToObject(this.storeNames, function (name) {
return [name, allTables[name]];
});
}, "Use db.tables()")
},
complete: deprecated("Transaction.complete()", function (cb) {
return this.on("complete", cb);
}),
error: deprecated("Transaction.error()", function (cb) {
return this.on("error", cb);
}),
table: deprecated("Transaction.table()", function (name) {
if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction");
return allTables[name];
})
});
//
//
//
// WhereClause
//
//
//
function WhereClause(table, index, orCollection) {
/// <param name="table" type="Table"></param>
/// <param name="index" type="String" optional="true"></param>
/// <param name="orCollection" type="Collection" optional="true"></param>
this._ctx = {
table: table,
index: index === ":id" ? null : index,
collClass: table._collClass,
or: orCollection
};
}
props(WhereClause.prototype, function () {
// WhereClause private methods
function fail(collectionOrWhereClause, err, T) {
var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause;
collection._ctx.error = T ? new T(err) : new TypeError(err);
return collection;
}
function emptyCollection(whereClause) {
return new whereClause._ctx.collClass(whereClause, function () {
return IDBKeyRange.only("");
}).limit(0);
}
function upperFactory(dir) {
return dir === "next" ? function (s) {
return s.toUpperCase();
} : function (s) {
return s.toLowerCase();
};
}
function lowerFactory(dir) {
return dir === "next" ? function (s) {
return s.toLowerCase();
} : function (s) {
return s.toUpperCase();
};
}
function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {
var length = Math.min(key.length, lowerNeedle.length);
var llp = -1;
for (var i = 0; i < length; ++i) {
var lwrKeyChar = lowerKey[i];
if (lwrKeyChar !== lowerNeedle[i]) {
if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);
if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);
if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);
return null;
}
if (cmp(key[i], lwrKeyChar) < 0) llp = i;
}
if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length);
if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length);
return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1);
}
function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {
/// <param name="needles" type="Array" elementType="String"></param>
var upper,
lower,
compare,
upperNeedles,
lowerNeedles,
direction,
nextKeySuffix,
needlesLen = needles.length;
if (!needles.every(function (s) {
return typeof s === 'string';
})) {
return fail(whereClause, STRING_EXPECTED);
}
function initDirection(dir) {
upper = upperFactory(dir);
lower = lowerFactory(dir);
compare = dir === "next" ? simpleCompare : simpleCompareReverse;
var needleBounds = needles.map(function (needle) {
return { lower: lower(needle), upper: upper(needle) };
}).sort(function (a, b) {
return compare(a.lower, b.lower);
});
upperNeedles = needleBounds.map(function (nb) {
return nb.upper;
});
lowerNeedles = needleBounds.map(function (nb) {
return nb.lower;
});
direction = dir;
nextKeySuffix = dir === "next" ? "" : suffix;
}
initDirection("next");
var c = new whereClause._ctx.collClass(whereClause, function () {
return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix);
});
c._ondirectionchange = function (direction) {
// This event onlys occur before filter is called the first time.
initDirection(direction);
};
var firstPossibleNeedle = 0;
c._addAlgorithm(function (cursor, advance, resolve) {
/// <param name="cursor" type="IDBCursor"></param>
/// <param name="advance" type="Function"></param>
/// <param name="resolve" type="Function"></param>
var key = cursor.key;
if (typeof key !== 'string') return false;
var lowerKey = lower(key);
if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {
return true;
} else {
var lowestPossibleCasing = null;
for (var i = firstPossibleNeedle; i < needlesLen; ++i) {
var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);
if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {
lowestPossibleCasing = casing;
}
}
if (lowestPossibleCasing !== null) {
advance(function () {
cursor.continue(lowestPossibleCasing + nextKeySuffix);
});
} else {
advance(resolve);
}
return false;
}
});
return c;
}
//
// WhereClause public methods
//
return {
between: function (lower, upper, includeLower, includeUpper) {
/// <summary>
/// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.
/// </summary>
/// <param name="lower"></param>
/// <param name="upper"></param>
/// <param name="includeLower" optional="true">Whether items that equals lower should be included. Default true.</param>
/// <param name="includeUpper" optional="true">Whether items that equals upper should be included. Default false.</param>
/// <returns type="Collection"></returns>
includeLower = includeLower !== false; // Default to true
includeUpper = includeUpper === true; // Default to false
try {
if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.
return new this._ctx.collClass(this, function () {
return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper);
});
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
},
equals: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.only(value);
});
},
above: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.lowerBound(value, true);
});
},
aboveOrEqual: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.lowerBound(value);
});
},
below: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.upperBound(value, true);
});
},
belowOrEqual: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.upperBound(value);
});
},
startsWith: function (str) {
/// <param name="str" type="String"></param>
if (typeof str !== 'string') return fail(this, STRING_EXPECTED);
return this.between(str, str + maxString, true, true);
},
startsWithIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
if (str === "") return this.startsWith(str);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return x.indexOf(a[0]) === 0;
}, [str], maxString);
},
equalsIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
return addIgnoreCaseAlgorithm(this, function (x, a) {
return x === a[0];
}, [str], "");
},
anyOfIgnoreCase: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return emptyCollection(this);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return a.indexOf(x) !== -1;
}, set, "");
},
startsWithAnyOfIgnoreCase: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return emptyCollection(this);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return a.some(function (n) {
return x.indexOf(n) === 0;
});
}, set, maxString);
},
anyOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
var compare = ascending;
try {
set.sort(compare);
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
if (set.length === 0) return emptyCollection(this);
var c = new this._ctx.collClass(this, function () {
return IDBKeyRange.bound(set[0], set[set.length - 1]);
});
c._ondirectionchange = function (direction) {
compare = direction === "next" ? ascending : descending;
set.sort(compare);
};
var i = 0;
c._addAlgorithm(function (cursor, advance, resolve) {
var key = cursor.key;
while (compare(key, set[i]) > 0) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === set.length) {
// There is no next. Stop searching.
advance(resolve);
return false;
}
}
if (compare(key, set[i]) === 0) {
// The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.
return true;
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
advance(function () {
cursor.continue(set[i]);
});
return false;
}
});
return c;
},
notEqual: function (value) {
return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false });
},
noneOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection.
try {
set.sort(ascending);
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
// Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]]
var ranges = set.reduce(function (res, val) {
return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]];
}, null);
ranges.push([set[set.length - 1], maxKey]);
return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });
},
/** Filter out values withing given set of ranges.
* Example, give children and elders a rebate of 50%:
*
* db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});
*
* @param {(string|number|Date|Array)[][]} ranges
* @param {{includeLowers: boolean, includeUppers: boolean}} options
*/
inAnyRange: function (ranges, options) {
var ctx = this._ctx;
if (ranges.length === 0) return emptyCollection(this);
if (!ranges.every(function (range) {
return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;
})) {
return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument);
}
var includeLowers = !options || options.includeLowers !== false; // Default to true
var includeUppers = options && options.includeUppers === true; // Default to false
function addRange(ranges, newRange) {
for (var i = 0, l = ranges.length; i < l; ++i) {
var range = ranges[i];
if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {
range[0] = min(range[0], newRange[0]);
range[1] = max(range[1], newRange[1]);
break;
}
}
if (i === l) ranges.push(newRange);
return ranges;
}
var sortDirection = ascending;
function rangeSorter(a, b) {
return sortDirection(a[0], b[0]);
}
// Join overlapping ranges
var set;
try {
set = ranges.reduce(addRange, []);
set.sort(rangeSorter);
} catch (ex) {
return fail(this, INVALID_KEY_ARGUMENT);
}
var i = 0;
var keyIsBeyondCurrentEntry = includeUppers ? function (key) {
return ascending(key, set[i][1]) > 0;
} : function (key) {
return ascending(key, set[i][1]) >= 0;
};
var keyIsBeforeCurrentEntry = includeLowers ? function (key) {
return descending(key, set[i][0]) > 0;
} : function (key) {
return descending(key, set[i][0]) >= 0;
};
function keyWithinCurrentRange(key) {
return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);
}
var checkKey = keyIsBeyondCurrentEntry;
var c = new ctx.collClass(this, function () {
return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);
});
c._ondirectionchange = function (direction) {
if (direction === "next") {
checkKey = keyIsBeyondCurrentEntry;
sortDirection = ascending;
} else {
checkKey = keyIsBeforeCurrentEntry;
sortDirection = descending;
}
set.sort(rangeSorter);
};
c._addAlgorithm(function (cursor, advance, resolve) {
var key = cursor.key;
while (checkKey(key)) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === set.length) {
// There is no next. Stop searching.
advance(resolve);
return false;
}
}
if (keyWithinCurrentRange(key)) {
// The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.
return true;
} else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) {
// includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.
// Continue to next key but don't include this one.
return false;
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
advance(function () {
if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]);
});
return false;
}
});
return c;
},
startsWithAnyOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (!set.every(function (s) {
return typeof s === 'string';
})) {
return fail(this, "startsWithAnyOf() only works with strings");
}
if (set.length === 0) return emptyCollection(this);
return this.inAnyRange(set.map(function (str) {
return [str, str + maxString];
}));
}
};
});
//
//
//
// Collection Class
//
//
//
function Collection(whereClause, keyRangeGenerator) {
/// <summary>
///
/// </summary>
/// <param name="whereClause" type="WhereClause">Where clause instance</param>
/// <param name="keyRangeGenerator" value="function(){ return IDBKeyRange.bound(0,1);}" optional="true"></param>
var keyRange = null,
error = null;
if (keyRangeGenerator) try {
keyRange = keyRangeGenerator();
} catch (ex) {
error = ex;
}
var whereCtx = whereClause._ctx,
table = whereCtx.table;
this._ctx = {
table: table,
index: whereCtx.index,
isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name,
range: keyRange,
keysOnly: false,
dir: "next",
unique: "",
algorithm: null,
filter: null,
replayFilter: null,
justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all)
isMatch: null,
offset: 0,
limit: Infinity,
error: error, // If set, any promise must be rejected with this error
or: whereCtx.or,
valueMapper: table.hook.reading.fire
};
}
function isPlainKeyRange(ctx, ignoreLimitFilter) {
return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);
}
props(Collection.prototype, function () {
//
// Collection Private Functions
//
function addFilter(ctx, fn) {
ctx.filter = combine(ctx.filter, fn);
}
function addReplayFilter(ctx, factory, isLimitFilter) {
var curr = ctx.replayFilter;
ctx.replayFilter = curr ? function () {
return combine(curr(), factory());
} : factory;
ctx.justLimit = isLimitFilter && !curr;
}
function addMatchFilter(ctx, fn) {
ctx.isMatch = combine(ctx.isMatch, fn);
}
/** @param ctx {
* isPrimKey: boolean,
* table: Table,
* index: string
* }
* @param store IDBObjectStore
**/
function getIndexOrStore(ctx, store) {
if (ctx.isPrimKey) return store;
var indexSpec = ctx.table.schema.idxByName[ctx.index];
if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed");
return store.index(indexSpec.name);
}
/** @param ctx {
* isPrimKey: boolean,
* table: Table,
* index: string,
* keysOnly: boolean,
* range?: IDBKeyRange,
* dir: "next" | "prev"
* }
*/
function openCursor(ctx, store) {
var idxOrStore = getIndexOrStore(ctx, store);
return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);
}
function iter(ctx, fn, resolve, reject, idbstore) {
var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;
if (!ctx.or) {
iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);
} else (function () {
var set = {};
var resolved = 0;
function resolveboth() {
if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.
}
function union(item, cursor, advance) {
if (!filter || filter(cursor, advance, resolveboth, reject)) {
var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
if (!hasOwn(set, key)) {
set[key] = true;
fn(item, cursor, advance);
}
}
}
ctx.or._iterate(union, resolveboth, reject, idbstore);
iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);
})();
}
function getInstanceTemplate(ctx) {
return ctx.table.schema.instanceTemplate;
}
return {
//
// Collection Protected Functions
//
_read: function (fn, cb) {
var ctx = this._ctx;
if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {
reject(ctx.error);
});else return ctx.table._idbstore(READONLY, fn).then(cb);
},
_write: function (fn) {
var ctx = this._ctx;
if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {
reject(ctx.error);
});else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.
},
_addAlgorithm: function (fn) {
var ctx = this._ctx;
ctx.algorithm = combine(ctx.algorithm, fn);
},
_iterate: function (fn, resolve, reject, idbstore) {
return iter(this._ctx, fn, resolve, reject, idbstore);
},
clone: function (props$$1) {
var rv = Object.create(this.constructor.prototype),
ctx = Object.create(this._ctx);
if (props$$1) extend(ctx, props$$1);
rv._ctx = ctx;
return rv;
},
raw: function () {
this._ctx.valueMapper = null;
return this;
},
//
// Collection Public methods
//
each: function (fn) {
var ctx = this._ctx;
if (fake) {
var item = getInstanceTemplate(ctx),
primKeyPath = ctx.table.schema.primKey.keyPath,
key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),
primaryKey = getByKeyPath(item, primKeyPath);
fn(item, { key: key, primaryKey: primaryKey });
}
return this._read(function (resolve, reject, idbstore) {
iter(ctx, fn, resolve, reject, idbstore);
});
},
count: function (cb) {
if (fake) return Promise.resolve(0).then(cb);
var ctx = this._ctx;
if (isPlainKeyRange(ctx, true)) {
// This is a plain key range. We can use the count() method if the index.
return this._read(function (resolve, reject, idbstore) {
var idx = getIndexOrStore(ctx, idbstore);
var req = ctx.range ? idx.count(ctx.range) : idx.count();
req.onerror = eventRejectHandler(reject);
req.onsuccess = function (e) {
resolve(Math.min(e.target.result, ctx.limit));
};
}, cb);
} else {
// Algorithms, filters or expressions are applied. Need to count manually.
var count = 0;
return this._read(function (resolve, reject, idbstore) {
iter(ctx, function () {
++count;return false;
}, function () {
resolve(count);
}, reject, idbstore);
}, cb);
}
},
sortBy: function (keyPath, cb) {
/// <param name="keyPath" type="String"></param>
var parts = keyPath.split('.').reverse(),
lastPart = parts[0],
lastIndex = parts.length - 1;
function getval(obj, i) {
if (i) return getval(obj[parts[i]], i - 1);
return obj[lastPart];
}
var order = this._ctx.dir === "next" ? 1 : -1;
function sorter(a, b) {
var aVal = getval(a, lastIndex),
bVal = getval(b, lastIndex);
return aVal < bVal ? -order : aVal > bVal ? order : 0;
}
return this.toArray(function (a) {
return a.sort(sorter);
}).then(cb);
},
toArray: function (cb) {
var ctx = this._ctx;
return this._read(function (resolve, reject, idbstore) {
fake && resolve([getInstanceTemplate(ctx)]);
if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {
// Special optimation if we could use IDBObjectStore.getAll() or
// IDBKeyRange.getAll():
var readingHook = ctx.table.hook.reading.fire;
var idxOrStore = getIndexOrStore(ctx, idbstore);
var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range);
req.onerror = eventRejectHandler(reject);
req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) {
try {
resolve(res.map(readingHook));
} catch (e) {
reject(e);
}
}));
} else {
// Getting array through a cursor.
var a = [];
iter(ctx, function (item) {
a.push(item);
}, function arrayComplete() {
resolve(a);
}, reject, idbstore);
}
}, cb);
},
offset: function (offset) {
var ctx = this._ctx;
if (offset <= 0) return this;
ctx.offset += offset; // For count()
if (isPlainKeyRange(ctx)) {
addReplayFilter(ctx, function () {
var offsetLeft = offset;
return function (cursor, advance) {
if (offsetLeft === 0) return true;
if (offsetLeft === 1) {
--offsetLeft;return false;
}
advance(function () {
cursor.advance(offsetLeft);
offsetLeft = 0;
});
return false;
};
});
} else {
addReplayFilter(ctx, function () {
var offsetLeft = offset;
return function () {
return --offsetLeft < 0;
};
});
}
return this;
},
limit: function (numRows) {
this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()
addReplayFilter(this._ctx, function () {
var rowsLeft = numRows;
return function (cursor, advance, resolve) {
if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included
return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.
};
}, true);
return this;
},
until: function (filterFunction, bIncludeStopEntry) {
var ctx = this._ctx;
fake && filterFunction(getInstanceTemplate(ctx));
addFilter(this._ctx, function (cursor, advance, resolve) {
if (filterFunction(cursor.value)) {
advance(resolve);
return bIncludeStopEntry;
} else {
return true;
}
});
return this;
},
first: function (cb) {
return this.limit(1).toArray(function (a) {
return a[0];
}).then(cb);
},
last: function (cb) {
return this.reverse().first(cb);
},
filter: function (filterFunction) {
/// <param name="jsFunctionFilter" type="Function">function(val){return true/false}</param>
fake && filterFunction(getInstanceTemplate(this._ctx));
addFilter(this._ctx, function (cursor) {
return filterFunction(cursor.value);
});
// match filters not used in Dexie.js but can be used by 3rd part libraries to test a
// collection for a match without querying DB. Used by Dexie.Observable.
addMatchFilter(this._ctx, filterFunction);
return this;
},
and: function (filterFunction) {
return this.filter(filterFunction);
},
or: function (indexName) {
return new WhereClause(this._ctx.table, indexName, this);
},
reverse: function () {
this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev";
if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);
return this;
},
desc: function () {
return this.reverse();
},
eachKey: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
return this.each(function (val, cursor) {
cb(cursor.key, cursor);
});
},
eachUniqueKey: function (cb) {
this._ctx.unique = "unique";
return this.eachKey(cb);
},
eachPrimaryKey: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
return this.each(function (val, cursor) {
cb(cursor.primaryKey, cursor);
});
},
keys: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
var a = [];
return this.each(function (item, cursor) {
a.push(cursor.key);
}).then(function () {
return a;
}).then(cb);
},
primaryKeys: function (cb) {
var ctx = this._ctx;
if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {
// Special optimation if we could use IDBObjectStore.getAllKeys() or
// IDBKeyRange.getAllKeys():
return this._read(function (resolve, reject, idbstore) {
var idxOrStore = getIndexOrStore(ctx, idbstore);
var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range);
req.onerror = eventRejectHandler(reject);
req.onsuccess = eventSuccessHandler(resolve);
}).then(cb);
}
ctx.keysOnly = !ctx.isMatch;
var a = [];
return this.each(function (item, cursor) {
a.push(cursor.primaryKey);
}).then(function () {
return a;
}).then(cb);
},
uniqueKeys: function (cb) {
this._ctx.unique = "unique";
return this.keys(cb);
},
firstKey: function (cb) {
return this.limit(1).keys(function (a) {
return a[0];
}).then(cb);
},
lastKey: function (cb) {
return this.reverse().firstKey(cb);
},
distinct: function () {
var ctx = this._ctx,
idx = ctx.index && ctx.table.schema.idxByName[ctx.index];
if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.
var set = {};
addFilter(this._ctx, function (cursor) {
var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
var found = hasOwn(set, strKey);
set[strKey] = true;
return !found;
});
return this;
}
};
});
//
//
// WriteableCollection Class
//
//
function WriteableCollection() {
Collection.apply(this, arguments);
}
derive(WriteableCollection).from(Collection).extend({
//
// WriteableCollection Public Methods
//
modify: function (changes) {
var self = this,
ctx = this._ctx,
hook = ctx.table.hook,
updatingHook = hook.updating.fire,
deletingHook = hook.deleting.fire;
fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);
return this._write(function (resolve, reject, idbstore, trans) {
var modifyer;
if (typeof changes === 'function') {
// Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)
if (updatingHook === nop && deletingHook === nop) {
// Noone cares about what is being changed. Just let the modifier function be the given argument as is.
modifyer = changes;
} else {
// People want to know exactly what is being modified or deleted.
// Let modifyer be a proxy function that finds out what changes the caller is actually doing
// and call the hooks accordingly!
modifyer = function (item) {
var origItem = deepClone(item); // Clone the item first so we can compare laters.
if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)
if (!hasOwn(this, "value")) {
// The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.
deletingHook.call(this, this.primKey, item, trans);
} else {
// No deletion. Check what was changed
var objectDiff = getObjectDiff(origItem, this.value);
var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);
if (additionalChanges) {
// Hook want to apply additional modifications. Make sure to fullfill the will of the hook.
item = this.value;
keys(additionalChanges).forEach(function (keyPath) {
setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
});
}
}
};
}
} else if (updatingHook === nop) {
// changes is a set of {keyPath: value} and no one is listening to the updating hook.
var keyPaths = keys(changes);
var numKeys = keyPaths.length;
modifyer = function (item) {
var anythingModified = false;
for (var i = 0; i < numKeys; ++i) {
var keyPath = keyPaths[i],
val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
anythingModified = true;
}
}
return anythingModified;
};
} else {
// changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and
// allow it to add additional modifications to make.
var origChanges = changes;
changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.
modifyer = function (item) {
var anythingModified = false;
var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);
if (additionalChanges) extend(changes, additionalChanges);
keys(changes).forEach(function (keyPath) {
var val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, val);
anythingModified = true;
}
});
if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration
return anythingModified;
};
}
var count = 0;
var successCount = 0;
var iterationComplete = false;
var failures = [];
var failKeys = [];
var currentKey = null;
function modifyItem(item, cursor) {
currentKey = cursor.primaryKey;
var thisContext = {
primKey: cursor.primaryKey,
value: item,
onsuccess: null,
onerror: null
};
function onerror(e) {
failures.push(e);
failKeys.push(thisContext.primKey);
checkFinished();
return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction
}
if (modifyer.call(thisContext, item, thisContext) !== false) {
// If a callback explicitely returns false, do not perform the update!
var bDelete = !hasOwn(thisContext, "value");
++count;
tryCatch(function () {
var req = bDelete ? cursor.delete() : cursor.update(thisContext.value);
req._hookCtx = thisContext;
req.onerror = hookedEventRejectHandler(onerror);
req.onsuccess = hookedEventSuccessHandler(function () {
++successCount;
checkFinished();
});
}, onerror);
} else if (thisContext.onsuccess) {
// Hook will expect either onerror or onsuccess to always be called!
thisContext.onsuccess(thisContext.value);
}
}
function doReject(e) {
if (e) {
failures.push(e);
failKeys.push(currentKey);
}
return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys));
}
function checkFinished() {
if (iterationComplete && successCount + failures.length === count) {
if (failures.length > 0) doReject();else resolve(successCount);
}
}
self.clone().raw()._iterate(modifyItem, function () {
iterationComplete = true;
checkFinished();
}, doReject, idbstore);
});
},
'delete': function () {
var _this4 = this;
var ctx = this._ctx,
range = ctx.range,
deletingHook = ctx.table.hook.deleting.fire,
hasDeleteHook = deletingHook !== nop;
if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear().
{
// May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)
// For chromium, this is the way most optimized version.
// For IE/Edge, this could hang the indexedDB engine and make operating system instable
// (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)
return this._write(function (resolve, reject, idbstore) {
// Our API contract is to return a count of deleted items, so we have to count() before delete().
var onerror = eventRejectHandler(reject),
countReq = range ? idbstore.count(range) : idbstore.count();
countReq.onerror = onerror;
countReq.onsuccess = function () {
var count = countReq.result;
tryCatch(function () {
var delReq = range ? idbstore.delete(range) : idbstore.clear();
delReq.onerror = onerror;
delReq.onsuccess = function () {
return resolve(count);
};
}, function (err) {
return reject(err);
});
};
});
}
// Default version to use when collection is not a vanilla IDBKeyRange on the primary key.
// Divide into chunks to not starve RAM.
// If has delete hook, we will have to collect not just keys but also objects, so it will use
// more memory and need lower chunk size.
var CHUNKSIZE = hasDeleteHook ? 2000 : 10000;
return this._write(function (resolve, reject, idbstore, trans) {
var totalCount = 0;
// Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.
var collection = _this4.clone({
keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers)
.distinct() // In case multiEntry is used, never delete same key twice because resulting count
// would become larger than actual delete count.
.limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc)
var keysOrTuples = [];
// We're gonna do things on as many chunks that are needed.
// Use recursion of nextChunk function:
var nextChunk = function () {
return collection.each(hasDeleteHook ? function (val, cursor) {
// Somebody subscribes to hook('deleting'). Collect all primary keys and their values,
// so that the hook can be called with its values in bulkDelete().
keysOrTuples.push([cursor.primaryKey, cursor.value]);
} : function (val, cursor) {
// No one subscribes to hook('deleting'). Collect only primary keys:
keysOrTuples.push(cursor.primaryKey);
}).then(function () {
// Chromium deletes faster when doing it in sort order.
hasDeleteHook ? keysOrTuples.sort(function (a, b) {
return ascending(a[0], b[0]);
}) : keysOrTuples.sort(ascending);
return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);
}).then(function () {
var count = keysOrTuples.length;
totalCount += count;
keysOrTuples = [];
return count < CHUNKSIZE ? totalCount : nextChunk();
});
};
resolve(nextChunk());
});
}
});
//
//
//
// ------------------------- Help functions ---------------------------
//
//
//
function lowerVersionFirst(a, b) {
return a._cfg.version - b._cfg.version;
}
function setApiOnPlace(objs, tableNames, mode, dbschema) {
tableNames.forEach(function (tableName) {
var tableInstance = db._tableFactory(mode, dbschema[tableName]);
objs.forEach(function (obj) {
tableName in obj || (obj[tableName] = tableInstance);
});
});
}
function removeTablesApi(objs) {
objs.forEach(function (obj) {
for (var key in obj) {
if (obj[key] instanceof Table) delete obj[key];
}
});
}
function iterate(req, filter, fn, resolve, reject, valueMapper) {
// Apply valueMapper (hook('reading') or mappped class)
var mappedFn = valueMapper ? function (x, c, a) {
return fn(valueMapper(x), c, a);
} : fn;
// Wrap fn with PSD and microtick stuff from Promise.
var wrappedFn = wrap(mappedFn, reject);
if (!req.onerror) req.onerror = eventRejectHandler(reject);
if (filter) {
req.onsuccess = trycatcher(function filter_record() {
var cursor = req.result;
if (cursor) {
var c = function () {
cursor.continue();
};
if (filter(cursor, function (advancer) {
c = advancer;
}, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) {
c = advancer;
});
c();
} else {
resolve();
}
}, reject);
} else {
req.onsuccess = trycatcher(function filter_record() {
var cursor = req.result;
if (cursor) {
var c = function () {
cursor.continue();
};
wrappedFn(cursor.value, cursor, function (advancer) {
c = advancer;
});
c();
} else {
resolve();
}
}, reject);
}
}
function parseIndexSyntax(indexes) {
/// <param name="indexes" type="String"></param>
/// <returns type="Array" elementType="IndexSpec"></returns>
var rv = [];
indexes.split(',').forEach(function (index) {
index = index.trim();
var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*"
// Let keyPath of "[a+b]" be ["a","b"]:
var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name;
rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index)));
});
return rv;
}
function cmp(key1, key2) {
return indexedDB.cmp(key1, key2);
}
function min(a, b) {
return cmp(a, b) < 0 ? a : b;
}
function max(a, b) {
return cmp(a, b) > 0 ? a : b;
}
function ascending(a, b) {
return indexedDB.cmp(a, b);
}
function descending(a, b) {
return indexedDB.cmp(b, a);
}
function simpleCompare(a, b) {
return a < b ? -1 : a === b ? 0 : 1;
}
function simpleCompareReverse(a, b) {
return a > b ? -1 : a === b ? 0 : 1;
}
function combine(filter1, filter2) {
return filter1 ? filter2 ? function () {
return filter1.apply(this, arguments) && filter2.apply(this, arguments);
} : filter1 : filter2;
}
function readGlobalSchema() {
db.verno = idbdb.version / 10;
db._dbSchema = globalSchema = {};
dbStoreNames = slice(idbdb.objectStoreNames, 0);
if (dbStoreNames.length === 0) return; // Database contains no stores.
var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');
dbStoreNames.forEach(function (storeName) {
var store = trans.objectStore(storeName),
keyPath = store.keyPath,
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);
var indexes = [];
for (var j = 0; j < store.indexNames.length; ++j) {
var idbindex = store.index(store.indexNames[j]);
keyPath = idbindex.keyPath;
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);
indexes.push(index);
}
globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});
});
setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema);
}
function adjustToExistingIndexNames(schema, idbtrans) {
/// <summary>
/// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db
/// </summary>
/// <param name="schema" type="Object">Map between name and TableSchema</param>
/// <param name="idbtrans" type="IDBTransaction"></param>
var storeNames = idbtrans.db.objectStoreNames;
for (var i = 0; i < storeNames.length; ++i) {
var storeName = storeNames[i];
var store = idbtrans.objectStore(storeName);
hasGetAll = 'getAll' in store;
for (var j = 0; j < store.indexNames.length; ++j) {
var indexName = store.indexNames[j];
var keyPath = store.index(indexName).keyPath;
var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]";
if (schema[storeName]) {
var indexSpec = schema[storeName].idxByName[dexieName];
if (indexSpec) indexSpec.name = indexName;
}
}
}
}
function fireOnBlocked(ev) {
db.on("blocked").fire(ev);
// Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari:
connections.filter(function (c) {
return c.name === db.name && c !== db && !c._vcFired;
}).map(function (c) {
return c.on("versionchange").fire(ev);
});
}
extend(this, {
Collection: Collection,
Table: Table,
Transaction: Transaction,
Version: Version,
WhereClause: WhereClause,
WriteableCollection: WriteableCollection,
WriteableTable: WriteableTable
});
init();
addons.forEach(function (fn) {
fn(db);
});
}
var fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())
var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())
function parseType(type) {
if (typeof type === 'function') {
return new type();
} else if (isArray(type)) {
return [parseType(type[0])];
} else if (type && typeof type === 'object') {
var rv = {};
applyStructure(rv, type);
return rv;
} else {
return type;
}
}
function applyStructure(obj, structure) {
keys(structure).forEach(function (member) {
var value = parseType(structure[member]);
obj[member] = value;
});
return obj;
}
function eventSuccessHandler(done) {
return function (ev) {
done(ev.target.result);
};
}
function hookedEventSuccessHandler(resolve) {
// wrap() is needed when calling hooks because the rare scenario of:
// * hook does a db operation that fails immediately (IDB throws exception)
// For calling db operations on correct transaction, wrap makes sure to set PSD correctly.
// wrap() will also execute in a virtual tick.
// * If not wrapped in a virtual tick, direct exception will launch a new physical tick.
// * If this was the last event in the bulk, the promise will resolve after a physical tick
// and the transaction will have committed already.
// If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,
// because it is always marked with _lib = true when created using Transaction._promise().
return wrap(function (event) {
var req = event.target,
result = req.result,
ctx = req._hookCtx,
// Contains the hook error handler. Put here instead of closure to boost performance.
hookSuccessHandler = ctx && ctx.onsuccess;
hookSuccessHandler && hookSuccessHandler(result);
resolve && resolve(result);
}, resolve);
}
function eventRejectHandler(reject) {
return function (event) {
preventDefault(event);
reject(event.target.error);
return false;
};
}
function hookedEventRejectHandler(reject) {
return wrap(function (event) {
// See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.
var req = event.target,
err = req.error,
ctx = req._hookCtx,
// Contains the hook error handler. Put here instead of closure to boost performance.
hookErrorHandler = ctx && ctx.onerror;
hookErrorHandler && hookErrorHandler(err);
preventDefault(event);
reject(err);
return false;
});
}
function preventDefault(event) {
if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.
event.stopPropagation();
if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.
event.preventDefault();
}
function globalDatabaseList(cb) {
var val,
localStorage = Dexie.dependencies.localStorage;
if (!localStorage) return cb([]); // Envs without localStorage support
try {
val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]");
} catch (e) {
val = [];
}
if (cb(val)) {
localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));
}
}
function awaitIterator(iterator) {
var callNext = function (result) {
return iterator.next(result);
},
doThrow = function (error) {
return iterator.throw(error);
},
onSuccess = step(callNext),
onError = step(doThrow);
function step(getNext) {
return function (val) {
var next = getNext(val),
value = next.value;
return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError);
};
}
return step(callNext)();
}
//
// IndexSpec struct
//
function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {
/// <param name="name" type="String"></param>
/// <param name="keyPath" type="String"></param>
/// <param name="unique" type="Boolean"></param>
/// <param name="multi" type="Boolean"></param>
/// <param name="auto" type="Boolean"></param>
/// <param name="compound" type="Boolean"></param>
/// <param name="dotted" type="Boolean"></param>
this.name = name;
this.keyPath = keyPath;
this.unique = unique;
this.multi = multi;
this.auto = auto;
this.compound = compound;
this.dotted = dotted;
var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']';
this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc;
}
//
// TableSchema struct
//
function TableSchema(name, primKey, indexes, instanceTemplate) {
/// <param name="name" type="String"></param>
/// <param name="primKey" type="IndexSpec"></param>
/// <param name="indexes" type="Array" elementType="IndexSpec"></param>
/// <param name="instanceTemplate" type="Object"></param>
this.name = name;
this.primKey = primKey || new IndexSpec();
this.indexes = indexes || [new IndexSpec()];
this.instanceTemplate = instanceTemplate;
this.mappedClass = null;
this.idxByName = arrayToObject(indexes, function (index) {
return [index.name, index];
});
}
// Used in when defining dependencies later...
// (If IndexedDBShim is loaded, prefer it before standard indexedDB)
var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {};
function safariMultiStoreFix(storeNames) {
return storeNames.length === 1 ? storeNames[0] : storeNames;
}
function getNativeGetDatabaseNamesFn(indexedDB) {
var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);
return fn && fn.bind(indexedDB);
}
// Export Error classes
props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};
//
// Static methods and properties
//
props(Dexie, {
//
// Static delete() method.
//
delete: function (databaseName) {
var db = new Dexie(databaseName),
promise = db.delete();
promise.onblocked = function (fn) {
db.on("blocked", fn);
return this;
};
return promise;
},
//
// Static exists() method.
//
exists: function (name) {
return new Dexie(name).open().then(function (db) {
db.close();
return true;
}).catch(Dexie.NoSuchDatabaseError, function () {
return false;
});
},
//
// Static method for retrieving a list of all existing databases at current host.
//
getDatabaseNames: function (cb) {
return new Promise(function (resolve, reject) {
var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB);
if (getDatabaseNames) {
// In case getDatabaseNames() becomes standard, let's prepare to support it:
var req = getDatabaseNames();
req.onsuccess = function (event) {
resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array<String>
};
req.onerror = eventRejectHandler(reject);
} else {
globalDatabaseList(function (val) {
resolve(val);
return false;
});
}
}).then(cb);
},
defineClass: function (structure) {
/// <summary>
/// Create a javascript constructor based on given template for which properties to expect in the class.
/// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
// Default constructor able to copy given properties into this object.
function Class(properties) {
/// <param name="properties" type="Object" optional="true">Properties to initialize object with.
/// </param>
properties ? extend(this, properties) : fake && applyStructure(this, structure);
}
return Class;
},
applyStructure: applyStructure,
ignoreTransaction: function (scopeFunc) {
// In case caller is within a transaction but needs to create a separate transaction.
// Example of usage:
//
// Let's say we have a logger function in our app. Other application-logic should be unaware of the
// logger function and not need to include the 'logentries' table in all transaction it performs.
// The logging should always be done in a separate transaction and not be dependant on the current
// running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.
//
// Dexie.ignoreTransaction(function() {
// db.logentries.add(newLogEntry);
// });
//
// Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction
// in current Promise-scope.
//
// An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an
// API for this because
// 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().
// 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().
// 3) setImmediate() is not supported in the ES standard.
// 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.
return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.
scopeFunc(); // No need to change scope because there is no ongoing transaction.
},
vip: function (fn) {
// To be used by subscribers to the on('ready') event.
// This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.
// This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD
// from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since
// the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.
// Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()
// the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by
// the caller will not resolve until database is opened.
return newScope(function () {
PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.
return fn();
});
},
async: function (generatorFn) {
return function () {
try {
var rv = awaitIterator(generatorFn.apply(this, arguments));
if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);
return rv;
} catch (e) {
return rejection(e);
}
};
},
spawn: function (generatorFn, args, thiz) {
try {
var rv = awaitIterator(generatorFn.apply(thiz, args || []));
if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);
return rv;
} catch (e) {
return rejection(e);
}
},
// Dexie.currentTransaction property
currentTransaction: {
get: function () {
return PSD.trans || null;
}
},
// Export our Promise implementation since it can be handy as a standalone Promise implementation
Promise: Promise,
// Dexie.debug proptery:
// Dexie.debug = false
// Dexie.debug = true
// Dexie.debug = "dexie" - don't hide dexie's stack frames.
debug: {
get: function () {
return debug;
},
set: function (value) {
setDebug(value, value === 'dexie' ? function () {
return true;
} : dexieStackFrameFilter);
}
},
// Export our derive/extend/override methodology
derive: derive,
extend: extend,
props: props,
override: override,
// Export our Events() function - can be handy as a toolkit
Events: Events,
events: { get: deprecated(function () {
return Events;
}) }, // Backward compatible lowercase version.
// Utilities
getByKeyPath: getByKeyPath,
setByKeyPath: setByKeyPath,
delByKeyPath: delByKeyPath,
shallowClone: shallowClone,
deepClone: deepClone,
getObjectDiff: getObjectDiff,
asap: asap,
maxKey: maxKey,
// Addon registry
addons: [],
// Global DB connection list
connections: connections,
MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.
errnames: errnames,
// Export other static classes
IndexSpec: IndexSpec,
TableSchema: TableSchema,
//
// Dependencies
//
// These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.
//
// In node.js, however, these properties must be set "manually" before instansiating a new Dexie().
// For node.js, you need to require indexeddb-js or similar and then set these deps.
//
dependencies: {
// Required:
indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,
IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange
},
// API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.
semVer: DEXIE_VERSION,
version: DEXIE_VERSION.split('.').map(function (n) {
return parseInt(n);
}).reduce(function (p, c, i) {
return p + c / Math.pow(10, i * 2);
}),
fakeAutoComplete: fakeAutoComplete,
// https://github.com/dfahlander/Dexie.js/issues/186
// typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return
// x.default. Workaround: Set Dexie.default = Dexie.
default: Dexie
});
tryCatch(function () {
// Optional dependencies
// localStorage
Dexie.dependencies.localStorage = (typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage;
});
// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.
Promise.rejectionMapper = mapError;
// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.
doFakeAutoComplete(function () {
Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;
Dexie.fake = fake = true;
});
return Dexie;
})));
//# sourceMappingURL=dexie.js.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35), __webpack_require__(80).setImmediate))
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Dexie = __webpack_require__(152);
var _write = __webpack_require__(185);
var pushable = __webpack_require__(162);
var toBuffer = __webpack_require__(187);
var defer = __webpack_require__(161);
var toWindow = __webpack_require__(184).recent;
var pull = __webpack_require__(75);
module.exports = function () {
function IdbBlobStore(dbname) {
_classCallCheck(this, IdbBlobStore);
this.path = dbname || 'pull-blob-store-' + Math.random().toString().slice(2, 10);
this.db = new Dexie(this.path);
// Setup database
this.db.version(1).stores(_defineProperty({}, this.path, '++,key,blob'));
}
_createClass(IdbBlobStore, [{
key: 'write',
value: function write(key, cb) {
var _this = this;
cb = cb || function () {};
var d = defer();
if (!key) {
cb(new Error('Missing key'));
return d;
}
this.remove(key, function (err) {
if (err) {
return cb(err);
}
var table = _this.table;
d.resolve(pull(toWindow(100, 10), _write(writer, reduce, 100, cb)));
function writer(data, cb) {
var blobs = data.map(function (blob) {
return {
key: key,
blob: blob
};
});
table.bulkPut(blobs).then(function () {
return cb();
}).catch(cb);
}
function reduce(queue, data) {
queue = queue || [];
if (!Array.isArray(data)) {
data = [data];
}
data = data.map(ensureBuffer);
if (!queue.length || last(queue).length > 99) {
queue.push(Buffer.concat(data));
} else {
queue[lastIndex(queue)] = Buffer.concat(last(queue).concat(data));
}
return queue;
}
});
return d;
}
}, {
key: 'read',
value: function read(key) {
var _this2 = this;
var p = pushable();
if (!key) {
p.end(new Error('Missing key'));
return p;
}
this.exists(key, function (err, exists) {
if (err) {
return p.end(err);
}
if (!exists) {
return p.end(new Error('Not found'));
}
_this2.table.where('key').equals(key).each(function (val) {
return p.push(toBuffer(val.blob));
}).catch(function (err) {
return p.end(err);
}).then(function () {
return p.end();
});
});
return p;
}
}, {
key: 'exists',
value: function exists(key, cb) {
cb = cb || function () {};
if (!key) {
return cb(new Error('Missing key'));
}
this.table.where('key').equals(key).count().then(function (val) {
return cb(null, Boolean(val));
}).catch(cb);
}
}, {
key: 'remove',
value: function remove(key, cb) {
cb = cb || function () {};
if (!key) {
return cb(new Error('Missing key'));
}
var coll = this.table.where('key').equals(key);
coll.count(function (count) {
return count > 0 ? coll.delete() : null;
}).then(function () {
return cb();
}).catch(cb);
}
}, {
key: 'table',
get: function get() {
return this.db[this.path];
}
}]);
return IdbBlobStore;
}();
function lastIndex(arr) {
return arr.length - 1;
}
function last(arr) {
return arr[lastIndex(arr)];
}
function ensureBuffer(data) {
return Buffer.isBuffer(data) ? data : Buffer.from(data);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 154 */
/***/ (function(module, exports) {
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
}
/***/ }),
/* 155 */
/***/ (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
}
}
/***/ }),
/* 156 */
/***/ (function(module, exports) {
module.exports = isTypedArray
isTypedArray.strict = isStrictTypedArray
isTypedArray.loose = isLooseTypedArray
var toString = Object.prototype.toString
var names = {
'[object Int8Array]': true
, '[object Int16Array]': true
, '[object Int32Array]': true
, '[object Uint8Array]': true
, '[object Uint8ClampedArray]': true
, '[object Uint16Array]': true
, '[object Uint32Array]': true
, '[object Float32Array]': true
, '[object Float64Array]': true
}
function isTypedArray(arr) {
return (
isStrictTypedArray(arr)
|| isLooseTypedArray(arr)
)
}
function isStrictTypedArray(arr) {
return (
arr instanceof Int8Array
|| arr instanceof Int16Array
|| arr instanceof Int32Array
|| arr instanceof Uint8Array
|| arr instanceof Uint8ClampedArray
|| arr instanceof Uint16Array
|| arr instanceof Uint32Array
|| arr instanceof Float32Array
|| arr instanceof Float64Array
)
}
function isLooseTypedArray(arr) {
return names[toString.call(arr)]
}
/***/ }),
/* 157 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(setImmediate) {
module.exports = function () {
var next = typeof setImmediate === 'undefined' ? setTimeout : setImmediate
var locked = {}
function _releaser (key, exec) {
return function (done) {
return function () {
_release(key, exec)
if (done) done.apply(null, arguments)
}
}
}
function _release (key, exec) {
var i = locked[key].indexOf(exec) //should usually be 0
if(!~i) return
locked[key].splice(i, 1)
//note, that the next locker isn't triggered until next tick,
//so it's always after the released callback
if(isLocked(key))
next(function () {
locked[key][0](_releaser(key, locked[key][0]))
})
else
delete locked[key]
}
function _lock(key, exec) {
if(isLocked(key))
return locked[key].push(exec), false
return locked[key] = [exec], true
}
function lock(key, exec) {
if(Array.isArray(key)) {
var keys = key.length, locks = []
var l = {}
function releaser (done) {
return function () {
var args = [].slice.call(arguments)
for(var key in l)
_release(key, l[key])
done.apply(this, args)
}
}
key.forEach(function (key) {
var n = 0
function ready () {
if(n++) return
if(!--keys)
//all the keys are ready!
exec(releaser)
}
l[key] = ready
if(_lock(key, ready)) ready()
})
return
}
if(_lock(key, exec))
exec(_releaser(key, exec))
}
function isLocked (key) {
return Array.isArray(locked[key]) ? !! locked[key].length : false
}
lock.isLocked = isLocked
return lock
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(80).setImmediate))
/***/ }),
/* 159 */
/***/ (function(module, exports) {
var looper = module.exports = function (fun) {
return function next (a, b, c) {
var loop = true, returned = false, sync = false
do {
sync = true; loop = false
fun.call(function (x, y, z) {
if(sync) {
a = x; b = y; c = z
loop = true
}
else
next(x, y, z)
}, a, b, c)
sync = false
} while(loop)
}
}
/***/ }),
/* 160 */
/***/ (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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(34)))
/***/ }),
/* 161 */
/***/ (function(module, exports) {
module.exports = function (stream) {
var read, started = false, id = Math.random()
function consume (_read) {
if(!_read) throw new Error('must be passed a readable')
read = _read
if(started) stream(read)
}
consume.resolve =
consume.ready =
consume.start = function (_stream) {
started = true; stream = _stream || stream
if(read) stream(read)
return consume
}
return consume
}
/***/ }),
/* 162 */
/***/ (function(module, exports) {
module.exports = pullPushable
function pullPushable (onClose) {
// create a buffer for data
// that have been pushed
// but not yet pulled.
var buffer = []
// a pushable is a source stream
// (abort, cb) => cb(end, data)
//
// when pushable is pulled,
// keep references to abort and cb
// so we can call back after
// .end(end) or .push(data)
var abort, cb
function read (_abort, _cb) {
if (_abort) {
abort = _abort
// if there is already a cb waiting, abort it.
if (cb) callback(abort)
}
cb = _cb
drain()
}
var ended
read.end = function (end) {
ended = ended || end || true
// attempt to drain
drain()
}
read.push = function (data) {
if (ended) return
// if sink already waiting,
// we can call back directly.
if (cb) {
callback(abort, data)
return
}
// otherwise push data and
// attempt to drain
buffer.push(data)
drain()
}
return read
// `drain` calls back to (if any) waiting
// sink with abort, end, or next data.
function drain () {
if (!cb) return
if (abort) callback(abort)
else if (!buffer.length && ended) callback(ended)
else if (buffer.length) callback(null, buffer.shift())
}
// `callback` calls back to waiting sink,
// and removes references to sink cb.
function callback (err, val) {
var _cb = cb
// if error and pushable passed onClose, call it
// the first time this stream ends or errors.
if (err && onClose) {
var c = onClose
onClose = null
c(err === true ? null : err)
}
cb = null
_cb(err, val)
}
}
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function pull (a) {
var length = arguments.length
if (typeof a === 'function' && a.length === 1) {
var args = new Array(length)
for(var i = 0; i < length; i++)
args[i] = arguments[i]
return function (read) {
if (args == null) {
throw new TypeError("partial sink should only be called once!")
}
// Grab the reference after the check, because it's always an array now
// (engines like that kind of consistency).
var ref = args
args = null
// Prioritize common case of small number of pulls.
switch (length) {
case 1: return pull(read, ref[0])
case 2: return pull(read, ref[0], ref[1])
case 3: return pull(read, ref[0], ref[1], ref[2])
case 4: return pull(read, ref[0], ref[1], ref[2], ref[3])
default:
ref.unshift(read)
return pull.apply(null, ref)
}
}
}
var read = a
if (read && typeof read.source === 'function') {
read = read.source
}
for (var i = 1; i < length; i++) {
var s = arguments[i]
if (typeof s === 'function') {
read = s(read)
} else if (s && typeof s === 'object') {
s.sink(read)
read = s.source
}
}
return read
}
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(51)
module.exports = function collect (cb) {
return reduce(function (arr, item) {
arr.push(item)
return arr
}, [], cb)
}
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(51)
module.exports = function concat (cb) {
return reduce(function (a, b) {
return a + b
}, '', cb)
}
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function id (e) { return e }
var prop = __webpack_require__(25)
var drain = __webpack_require__(24)
module.exports = function find (test, cb) {
var ended = false
if(!cb)
cb = test, test = id
else
test = prop(test) || id
return drain(function (data) {
if(test(data)) {
ended = true
cb(null, data)
return false
}
}, function (err) {
if(ended) return //already called back
cb(err === true ? null : err, null)
})
}
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
drain: __webpack_require__(24),
onEnd: __webpack_require__(169),
log: __webpack_require__(168),
find: __webpack_require__(166),
reduce: __webpack_require__(51),
collect: __webpack_require__(164),
concat: __webpack_require__(165)
}
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var drain = __webpack_require__(24)
module.exports = function log (done) {
return drain(function (data) {
console.log(data)
}, done)
}
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var drain = __webpack_require__(24)
module.exports = function onEnd (done) {
return drain(null, done)
}
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function count (max) {
var i = 0; max = max || Infinity
return function (end, cb) {
if(end) return cb && cb(end)
if(i > max)
return cb(true)
cb(null, i++)
}
}
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//a stream that ends immediately.
module.exports = function empty () {
return function (abort, cb) {
cb(true)
}
}
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//a stream that errors immediately.
module.exports = function error (err) {
return function (abort, cb) {
cb(err)
}
}
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
keys: __webpack_require__(175),
once: __webpack_require__(76),
values: __webpack_require__(52),
count: __webpack_require__(170),
infinite: __webpack_require__(174),
empty: __webpack_require__(171),
error: __webpack_require__(172)
}
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function infinite (generate) {
generate = generate || Math.random
return function (end, cb) {
if(end) return cb && cb(end)
return cb(null, generate())
}
}
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var values = __webpack_require__(52)
module.exports = function (object) {
return values(Object.keys(object))
}
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function id (e) { return e }
var prop = __webpack_require__(25)
module.exports = function asyncMap (map) {
if(!map) return id
map = prop(map)
var busy = false, abortCb, aborted
return function (read) {
return function next (abort, cb) {
if(aborted) return cb(aborted)
if(abort) {
aborted = abort
if(!busy) read(abort, cb)
else read(abort, function () {
//if we are still busy, wait for the mapper to complete.
if(busy) abortCb = cb
else cb(abort)
})
}
else
read(null, function (end, data) {
if(end) cb(end)
else if(aborted) cb(aborted)
else {
busy = true
map(data, function (err, data) {
busy = false
if(aborted) {
cb(aborted)
abortCb(aborted)
}
else if(err) next (err, cb)
else cb(null, data)
})
}
})
}
}
}
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var tester = __webpack_require__(79)
var filter = __webpack_require__(53)
module.exports = function filterNot (test) {
test = tester(test)
return filter(function (data) { return !test(data) })
}
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var values = __webpack_require__(52)
var once = __webpack_require__(76)
//convert a stream of arrays or streams into just a stream.
module.exports = function flatten () {
return function (read) {
var _read
return function (abort, cb) {
if (abort) { //abort the current stream, and then stream of streams.
_read ? _read(abort, function(err) {
read(err || abort, cb)
}) : read(abort, cb)
}
else if(_read) nextChunk()
else nextStream()
function nextChunk () {
_read(null, function (err, data) {
if (err === true) nextStream()
else if (err) {
read(true, function(abortErr) {
// TODO: what do we do with the abortErr?
cb(err)
})
}
else cb(null, data)
})
}
function nextStream () {
_read = null
read(null, function (end, stream) {
if(end)
return cb(end)
if(Array.isArray(stream) || stream && 'object' === typeof stream)
stream = values(stream)
else if('function' != typeof stream)
stream = once(stream)
_read = stream
nextChunk()
})
}
}
}
}
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
map: __webpack_require__(180),
asyncMap: __webpack_require__(176),
filter: __webpack_require__(53),
filterNot: __webpack_require__(177),
through: __webpack_require__(183),
take: __webpack_require__(182),
unique: __webpack_require__(77),
nonUnique: __webpack_require__(181),
flatten: __webpack_require__(178)
}
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function id (e) { return e }
var prop = __webpack_require__(25)
module.exports = function map (mapper) {
if(!mapper) return id
mapper = prop(mapper)
return function (read) {
return function (abort, cb) {
read(abort, function (end, data) {
try {
data = !end ? mapper(data) : null
} catch (err) {
return read(err, function () {
return cb(err)
})
}
cb(end, data)
})
}
}
}
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var unique = __webpack_require__(77)
//passes an item through when you see it for the second time.
module.exports = function nonUnique (field) {
return unique(field, true)
}
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//read a number of items and then stop.
module.exports = function take (test, opts) {
opts = opts || {}
var last = opts.last || false // whether the first item for which !test(item) should still pass
var ended = false
if('number' === typeof test) {
last = true
var n = test; test = function () {
return --n
}
}
return function (read) {
function terminate (cb) {
read(true, function (err) {
last = false; cb(err || true)
})
}
return function (end, cb) {
if(ended) last ? terminate(cb) : cb(ended)
else if(ended = end) read(ended, cb)
else
read(null, function (end, data) {
if(ended = ended || end) {
//last ? terminate(cb) :
cb(ended)
}
else if(!test(data)) {
ended = true
last ? cb(null, data) : terminate(cb)
}
else
cb(null, data)
})
}
}
}
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//a pass through stream that doesn't change the value.
module.exports = function through (op, onEnd) {
var a = false
function once (abort) {
if(a || !onEnd) return
a = true
onEnd(abort === true ? null : abort)
}
return function (read) {
return function (end, cb) {
if(end) once(end)
return read(end, function (end, data) {
if(!end) op && op(data)
else once(end)
cb(end, data)
})
}
}
}
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
var looper = __webpack_require__(159)
var window = module.exports = function (init, start) {
return function (read) {
start = start || function (start, data) {
return {start: start, data: data}
}
var windows = [], output = [], ended = null
var data, end
var j = 0
return function (abort, cb) {
if(output.length)
return cb(null, output.shift())
if(ended)
return cb(ended)
var i = 0
var k = j ++
read(abort, looper(function (end, data) {
var next = this
var reduce, update, once = false
if(end)
ended = end
function _update (end, _data) {
if(once) return
once = true
delete windows[windows.indexOf(update)]
output.push(start(data, _data))
}
if(!ended)
update = init(data, _update)
if(update)
windows.push(update)
else
//don't allow data unless a window started here!
once = true
windows.forEach(function (update, i) {
update(end, data)
})
if(output.length)
return cb(null, output.shift())
else if(ended)
return cb(ended)
else
read(null, next)
}))
}
}}
window.recent = function (size, time) {
var current = null
return window(function (data, cb) {
if(current) return
current = []
var timer
function done () {
var _current = current
current = null
clearTimeout(timer)
cb(null, _current)
}
if(time)
timer = setTimeout(done, time)
return function (end, data) {
if(end) return done()
current.push(data)
if(size != null && current.length >= size)
done()
}
}, function (_, data) {
return data
})
}
window.sliding = function (reduce, width) {
width = width || 10
var k = 0
return window(function (data, cb) {
var acc
var i = 0
var l = k++
return function (end, data) {
if(end) return
acc = reduce(acc, data)
if(width <= ++ i)
cb(null, acc)
}
})
}
/***/ }),
/* 185 */
/***/ (function(module, exports) {
//another idea: buffer 2* the max, but only call write with half of that,
//this could manage cases where the read ahead is latent. Hmm, we probably
//shouldn't guess at that here, just handle write latency.
//how would we measure this anyway?
function append (array, item) {
(array = array || []).push(item)
return array
}
module.exports = function (write, reduce, max, cb) {
reduce = reduce || append
var ended, _cb, _read
function reader (read) {
var queue = null, writing = false, length = 0
_read = read
if(ended) return read(ended, function (err) {
cb(err)
_cb && _cb()
})
var reading = false
function more () {
if(reading || ended) return
reading = true
read(null, function (err, data) {
reading = false
next(err, data)
})
}
function flush () {
if(writing) return
var _queue = queue
queue = null; writing = true; length = 0
write(_queue, function (err) {
writing = false
if(ended === true && !length) cb(err)
else if(ended && ended !== true) {
cb(ended)
_cb && _cb()
}
else if(err) read(ended = err, cb) //abort upstream.
else if(length) flush()
else more()
})
}
function next (end, data) {
if(ended) return
ended = end
if(!ended) {
queue = reduce(queue, data)
length = (queue && queue.length) || 0
if(queue != null) flush()
if(length < max) more()
}
else if(!writing) cb(ended === true ? null : ended)
}
reader.abort = function (__cb) {
_cb = function (end) {
__cb && __cb()
}
read(ended = new Error('aborted'), function (end) {
end = end === true ? null : end
if(!writing) {
cb && cb(end)
_cb && _cb(end)
}
})
}
more()
}
reader.abort = function (cb) {
ended = new Error('aborted before connecting')
_cb = function (err) {
cb && cb()
}
}
return reader
}
/***/ }),
/* 186 */
/***/ (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 68
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(exports, __webpack_require__(35), __webpack_require__(34)))
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {/**
* Convert a typed array to a Buffer without a copy
*
* Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* License: MIT
*
* `npm install typedarray-to-buffer`
*/
var isTypedArray = __webpack_require__(156).strict
module.exports = function typedarrayToBuffer (arr) {
if (isTypedArray(arr)) {
// To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer
var buf = new Buffer(arr.buffer)
if (arr.byteLength !== arr.buffer.byteLength) {
// Respect the "view", i.e. byteOffset and byteLength, without doing a copy
buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
}
return buf
} else {
// Pass through all other types to the `Buffer` constructor
return new Buffer(arr)
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer))
/***/ }),
/* 188 */
/***/ (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';
}
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
/* 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.
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) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
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__(188);
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__(155);
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);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35), __webpack_require__(34)))
/***/ }),
/* 190 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(13);
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventEmitter = __webpack_require__(36).EventEmitter;
var EventStore = __webpack_require__(54);
var FeedStore = __webpack_require__(84);
var KeyValueStore = __webpack_require__(85);
var CounterStore = __webpack_require__(82);
var DocumentStore = __webpack_require__(83);
var Pubsub = __webpack_require__(86);
var Cache = __webpack_require__(81);
var defaultNetworkName = 'Orbit DEV Network';
var OrbitDB = function () {
function OrbitDB(ipfs) {
var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
(0, _classCallCheck3.default)(this, OrbitDB);
this._ipfs = ipfs;
this._pubsub = options && options.broker ? new options.broker(ipfs) : new Pubsub(ipfs);
this.user = { id: id };
this.network = { name: defaultNetworkName };
this.events = new EventEmitter();
this.stores = {};
}
/* Databases */
(0, _createClass3.default)(OrbitDB, [{
key: 'feed',
value: function feed(dbname, options) {
return this._createStore(FeedStore, dbname, options);
}
}, {
key: 'eventlog',
value: function eventlog(dbname, options) {
return this._createStore(EventStore, dbname, options);
}
}, {
key: 'kvstore',
value: function kvstore(dbname, options) {
return this._createStore(KeyValueStore, dbname, options);
}
}, {
key: 'counter',
value: function counter(dbname, options) {
return this._createStore(CounterStore, dbname, options);
}
}, {
key: 'docstore',
value: function docstore(dbname, options) {
return this._createStore(DocumentStore, dbname, options);
}
}, {
key: 'disconnect',
value: function disconnect() {
var _this = this;
if (this._pubsub) this._pubsub.disconnect();
this.events.removeAllListeners('data');
(0, _keys2.default)(this.stores).map(function (e) {
return _this.stores[e];
}).forEach(function (store) {
store.events.removeAllListeners('data');
store.events.removeAllListeners('write');
store.events.removeAllListeners('close');
});
this.stores = {};
this.user = null;
this.network = null;
}
/* Private methods */
}, {
key: '_createStore',
value: function _createStore(Store, dbname) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { subscribe: true };
var store = new Store(this._ipfs, this.user.id, dbname, options);
this.stores[dbname] = store;
return this._subscribe(store, dbname, options.subscribe, options.cachePath);
}
}, {
key: '_subscribe',
value: function _subscribe(store, dbname) {
var subscribe = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var cachePath = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : './orbit-db';
store.events.on('data', this._onData.bind(this));
store.events.on('write', this._onWrite.bind(this));
store.events.on('close', this._onClose.bind(this));
if (subscribe && this._pubsub) this._pubsub.subscribe(dbname, this._onMessage.bind(this), this._onConnected.bind(this), store.options.maxHistory > 0);else store.loadHistory().catch(function (e) {
return console.error(e.stack);
});
Cache.loadCache(cachePath).then(function () {
var hash = Cache.get(dbname);
store.loadHistory(hash).catch(function (e) {
return console.error(e.stack);
});
});
return store;
}
/* Connected to the message broker */
}, {
key: '_onConnected',
value: function _onConnected(dbname, hash) {
// console.log(".CONNECTED", dbname, hash)
var store = this.stores[dbname];
store.loadHistory(hash).catch(function (e) {
return console.error(e.stack);
});
}
/* Replication request from the message broker */
}, {
key: '_onMessage',
value: function _onMessage(dbname, hash) {
var _this2 = this;
// console.log(".MESSAGE", dbname, hash)
var store = this.stores[dbname];
store.sync(hash).then(function (res) {
return Cache.set(dbname, res);
}).then(function () {
return _this2.events.emit('synced', dbname, hash);
}).catch(function (e) {
return console.error(e.stack);
});
}
/* Data events */
}, {
key: '_onWrite',
value: function _onWrite(dbname, hash) {
// 'New entry written to database...', after adding a new db entry locally
// console.log(".WRITE", dbname, hash, this.user.username)
if (!hash) throw new Error("Hash can't be null!");
if (this._pubsub) this._pubsub.publish(dbname, hash);
Cache.set(dbname, hash);
}
}, {
key: '_onData',
value: function _onData(dbname, items) {
// 'New database entry...', after a new entry was added to the database
// console.log(".SYNCED", dbname, items.length)
this.events.emit('data', dbname, items);
}
}, {
key: '_onClose',
value: function _onClose(dbname) {
if (this._pubsub) this._pubsub.unsubscribe(dbname);
delete this.stores[dbname];
}
}]);
return OrbitDB;
}();
module.exports = OrbitDB;
/***/ })
/******/ ]);
//# sourceMappingURL=orbitdb.js.map