From 714256a744e3555a243a539ddab627b5c5432d82 Mon Sep 17 00:00:00 2001 From: julian laplace Date: Tue, 8 Jul 2025 00:22:03 +0200 Subject: docs --- bundle.js | 78162 ++++++++++++++++++++++++++++++------------------------------ 1 file changed, 39081 insertions(+), 39081 deletions(-) (limited to 'bundle.js') diff --git a/bundle.js b/bundle.js index e5dd4b8..02e8d74 100644 --- a/bundle.js +++ b/bundle.js @@ -63,39297 +63,38041 @@ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 13); +/******/ return __webpack_require__(__webpack_require__.s = 270); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return Collection; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Iterable", function() { return Iterable; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "List", function() { return List; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Map", function() { return Map; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderedMap", function() { return OrderedMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderedSet", function() { return OrderedSet; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PairSorting", function() { return PairSorting; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Record", function() { return Record; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Repeat", function() { return Repeat; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Seq", function() { return Seq; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Set", function() { return Set; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Stack", function() { return Stack; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromJS", function() { return fromJS; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return get; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIn", function() { return getIn$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "has", function() { return has; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasIn", function() { return hasIn$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hash", function() { return hash; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "is", function() { return is; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAssociative", function() { return isAssociative; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCollection", function() { return isCollection; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isImmutable", function() { return isImmutable; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIndexed", function() { return isIndexed; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isKeyed", function() { return isKeyed; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isList", function() { return isList; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return isMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrdered", function() { return isOrdered; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrderedMap", function() { return isOrderedMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrderedSet", function() { return isOrderedSet; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlainObject", function() { return isPlainObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRecord", function() { return isRecord; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSeq", function() { return isSeq; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return isSet; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStack", function() { return isStack; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValueObject", function() { return isValueObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDeep", function() { return mergeDeep$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDeepWith", function() { return mergeDeepWith$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeWith", function() { return mergeWith; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "remove", function() { return remove; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeIn", function() { return removeIn; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "set", function() { return set; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setIn", function() { return setIn$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "update", function() { return update$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateIn", function() { return updateIn$1; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); -/** - * @license - * MIT License - * - * Copyright (c) 2014-present, Lee Byron and other 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. - */ -// Used for setting prototype methods that IE8 chokes on. -var DELETE = 'delete'; -// Constants describing the size of trie nodes. -var SHIFT = 5; // Resulted in best performance after ______? -var SIZE = 1 << SHIFT; -var MASK = SIZE - 1; -// A consistent shared value representing "not set" which equals nothing other -// than itself, and nothing that could be provided externally. -var NOT_SET = {}; -// Boolean references, Rough equivalent of `bool &`. -function MakeRef() { - return { value: false }; -} -function SetRef(ref) { - if (ref) { - ref.value = true; - } -} -// A function which returns a value representing an "owner" for transient writes -// to tries. The return value will only ever equal itself, and will not equal -// the return of any subsequent call of this function. -function OwnerID() { } -function ensureSize(iter) { - // @ts-expect-error size should exists on Collection - if (iter.size === undefined) { - // @ts-expect-error size should exists on Collection, __iterate does exist on Collection - iter.size = iter.__iterate(returnTrue); + +var globalThis = __webpack_require__(3); +var getOwnPropertyDescriptor = __webpack_require__(31).f; +var createNonEnumerableProperty = __webpack_require__(27); +var defineBuiltIn = __webpack_require__(17); +var defineGlobalProperty = __webpack_require__(152); +var copyConstructorProperties = __webpack_require__(79); +var isForced = __webpack_require__(101); + +/* + options.target - name of the target object + options.global - target is the global object + options.stat - export as static methods of target + options.proto - export as prototype methods of target + options.real - real prototype method for the `pure` version + options.forced - export even if the native feature is available + options.bind - bind methods to the target, required for the `pure` version + options.wrap - wrap constructors to preventing global pollution, required for the `pure` version + options.unsafe - use the simple assignment of property instead of delete + defineProperty + options.sham - add a flag to not completely full polyfills + options.enumerable - export as enumerable property + options.dontCallGetSet - prevent calling a getter on target + options.name - the .name of the function if it does not match the key +*/ +module.exports = function (options, source) { + var TARGET = options.target; + var GLOBAL = options.global; + var STATIC = options.stat; + var FORCED, target, key, targetProperty, sourceProperty, descriptor; + if (GLOBAL) { + target = globalThis; + } else if (STATIC) { + target = globalThis[TARGET] || defineGlobalProperty(TARGET, {}); + } else { + target = globalThis[TARGET] && globalThis[TARGET].prototype; + } + if (target) for (key in source) { + sourceProperty = source[key]; + if (options.dontCallGetSet) { + descriptor = getOwnPropertyDescriptor(target, key); + targetProperty = descriptor && descriptor.value; + } else targetProperty = target[key]; + FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); + // contained in target + if (!FORCED && targetProperty !== undefined) { + if (typeof sourceProperty == typeof targetProperty) continue; + copyConstructorProperties(sourceProperty, targetProperty); } - // @ts-expect-error size should exists on Collection - return iter.size; -} -function wrapIndex(iter, index) { - // This implements "is array index" which the ECMAString spec defines as: - // - // A String property name P is an array index if and only if - // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal - // to 2^32−1. - // - // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects - if (typeof index !== 'number') { - var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 - if ('' + uint32Index !== index || uint32Index === 4294967295) { - return NaN; - } - index = uint32Index; + // add a flag to not completely full polyfills + if (options.sham || (targetProperty && targetProperty.sham)) { + createNonEnumerableProperty(sourceProperty, 'sham', true); } - return index < 0 ? ensureSize(iter) + index : index; -} -function returnTrue() { - return true; -} -function wholeSlice(begin, end, size) { - return (((begin === 0 && !isNeg(begin)) || - (size !== undefined && begin <= -size)) && - (end === undefined || (size !== undefined && end >= size))); -} -function resolveBegin(begin, size) { - return resolveIndex(begin, size, 0); -} -function resolveEnd(end, size) { - return resolveIndex(end, size, size); -} -function resolveIndex(index, size, defaultIndex) { - // Sanitize indices using this shorthand for ToInt32(argument) - // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 - return index === undefined - ? defaultIndex - : isNeg(index) - ? size === Infinity - ? size - : Math.max(0, size + index) | 0 - : size === undefined || size === index - ? index - : Math.min(size, index) | 0; -} -function isNeg(value) { - // Account for -0 which is negative, but not less than 0. - return value < 0 || (value === 0 && 1 / value === -Infinity); -} - -// Note: value is unchanged to not break immutable-devtools. -var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@'; -/** - * True if `maybeCollection` is a Collection, or any of its subclasses. - * - * ```js - * import { isCollection, Map, List, Stack } from 'immutable'; - * - * isCollection([]); // false - * isCollection({}); // false - * isCollection(Map()); // true - * isCollection(List()); // true - * isCollection(Stack()); // true - * ``` - */ -function isCollection(maybeCollection) { - return Boolean(maybeCollection && - // @ts-expect-error: maybeCollection is typed as `{}`, need to change in 6.0 to `maybeCollection && typeof maybeCollection === 'object' && IS_COLLECTION_SYMBOL in maybeCollection` - maybeCollection[IS_COLLECTION_SYMBOL]); -} + defineBuiltIn(target, key, sourceProperty, options); + } +}; -var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@'; -/** - * True if `maybeKeyed` is a Collection.Keyed, or any of its subclasses. - * - * ```js - * import { isKeyed, Map, List, Stack } from 'immutable'; - * - * isKeyed([]); // false - * isKeyed({}); // false - * isKeyed(Map()); // true - * isKeyed(List()); // false - * isKeyed(Stack()); // false - * ``` - */ -function isKeyed(maybeKeyed) { - return Boolean(maybeKeyed && - // @ts-expect-error: maybeKeyed is typed as `{}`, need to change in 6.0 to `maybeKeyed && typeof maybeKeyed === 'object' && IS_KEYED_SYMBOL in maybeKeyed` - maybeKeyed[IS_KEYED_SYMBOL]); -} -var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@'; -/** - * True if `maybeIndexed` is a Collection.Indexed, or any of its subclasses. - * - * ```js - * import { isIndexed, Map, List, Stack, Set } from 'immutable'; - * - * isIndexed([]); // false - * isIndexed({}); // false - * isIndexed(Map()); // false - * isIndexed(List()); // true - * isIndexed(Stack()); // true - * isIndexed(Set()); // false - * ``` - */ -function isIndexed(maybeIndexed) { - return Boolean(maybeIndexed && - // @ts-expect-error: maybeIndexed is typed as `{}`, need to change in 6.0 to `maybeIndexed && typeof maybeIndexed === 'object' && IS_INDEXED_SYMBOL in maybeIndexed` - maybeIndexed[IS_INDEXED_SYMBOL]); -} +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * True if `maybeAssociative` is either a Keyed or Indexed Collection. - * - * ```js - * import { isAssociative, Map, List, Stack, Set } from 'immutable'; - * - * isAssociative([]); // false - * isAssociative({}); // false - * isAssociative(Map()); // true - * isAssociative(List()); // true - * isAssociative(Stack()); // true - * isAssociative(Set()); // false - * ``` - */ -function isAssociative(maybeAssociative) { - return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); -} +"use strict"; -var Collection = function Collection(value) { - // eslint-disable-next-line no-constructor-return - return isCollection(value) ? value : Seq(value); +module.exports = function (exec) { + try { + return !!exec(); + } catch (error) { + return true; + } }; -var KeyedCollection = /*@__PURE__*/(function (Collection) { - function KeyedCollection(value) { - // eslint-disable-next-line no-constructor-return - return isKeyed(value) ? value : KeyedSeq(value); - } - if ( Collection ) KeyedCollection.__proto__ = Collection; - KeyedCollection.prototype = Object.create( Collection && Collection.prototype ); - KeyedCollection.prototype.constructor = KeyedCollection; +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { - return KeyedCollection; -}(Collection)); +"use strict"; -var IndexedCollection = /*@__PURE__*/(function (Collection) { - function IndexedCollection(value) { - // eslint-disable-next-line no-constructor-return - return isIndexed(value) ? value : IndexedSeq(value); - } +var NATIVE_BIND = __webpack_require__(99); - if ( Collection ) IndexedCollection.__proto__ = Collection; - IndexedCollection.prototype = Object.create( Collection && Collection.prototype ); - IndexedCollection.prototype.constructor = IndexedCollection; +var FunctionPrototype = Function.prototype; +var call = FunctionPrototype.call; +// eslint-disable-next-line es/no-function-prototype-bind -- safe +var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); - return IndexedCollection; -}(Collection)); +module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) { + return function () { + return call.apply(fn, arguments); + }; +}; -var SetCollection = /*@__PURE__*/(function (Collection) { - function SetCollection(value) { - // eslint-disable-next-line no-constructor-return - return isCollection(value) && !isAssociative(value) ? value : SetSeq(value); - } - if ( Collection ) SetCollection.__proto__ = Collection; - SetCollection.prototype = Object.create( Collection && Collection.prototype ); - SetCollection.prototype.constructor = SetCollection; +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { - return SetCollection; -}(Collection)); +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var check = function (it) { + return it && it.Math === Math && it; +}; -Collection.Keyed = KeyedCollection; -Collection.Indexed = IndexedCollection; -Collection.Set = SetCollection; +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +module.exports = + // eslint-disable-next-line es/no-global-this -- safe + check(typeof globalThis == 'object' && globalThis) || + check(typeof window == 'object' && window) || + // eslint-disable-next-line no-restricted-globals -- safe + check(typeof self == 'object' && self) || + check(typeof global == 'object' && global) || + check(typeof this == 'object' && this) || + // eslint-disable-next-line no-new-func -- fallback + (function () { return this; })() || Function('return this')(); -var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@'; -/** - * True if `maybeSeq` is a Seq. - */ -function isSeq(maybeSeq) { - return Boolean(maybeSeq && - // @ts-expect-error: maybeSeq is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSeq === 'object' && MAYBE_SEQ_SYMBOL in maybeSeq` - maybeSeq[IS_SEQ_SYMBOL]); -} +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(259))) -var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; -/** - * True if `maybeRecord` is a Record. - */ -function isRecord(maybeRecord) { - return Boolean(maybeRecord && - // @ts-expect-error: maybeRecord is typed as `{}`, need to change in 6.0 to `maybeRecord && typeof maybeRecord === 'object' && IS_RECORD_SYMBOL in maybeRecord` - maybeRecord[IS_RECORD_SYMBOL]); -} +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * True if `maybeImmutable` is an Immutable Collection or Record. - * - * Note: Still returns true even if the collections is within a `withMutations()`. - * - * ```js - * import { isImmutable, Map, List, Stack } from 'immutable'; - * isImmutable([]); // false - * isImmutable({}); // false - * isImmutable(Map()); // true - * isImmutable(List()); // true - * isImmutable(Stack()); // true - * isImmutable(Map().asMutable()); // true - * ``` - */ -function isImmutable(maybeImmutable) { - return isCollection(maybeImmutable) || isRecord(maybeImmutable); -} +"use strict"; -var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@'; -function isOrdered(maybeOrdered) { - return Boolean(maybeOrdered && - // @ts-expect-error: maybeOrdered is typed as `{}`, need to change in 6.0 to `maybeOrdered && typeof maybeOrdered === 'object' && IS_ORDERED_SYMBOL in maybeOrdered` - maybeOrdered[IS_ORDERED_SYMBOL]); -} +var NATIVE_BIND = __webpack_require__(99); -var ITERATE_KEYS = 0; -var ITERATE_VALUES = 1; -var ITERATE_ENTRIES = 2; +var call = Function.prototype.call; +// eslint-disable-next-line es/no-function-prototype-bind -- safe +module.exports = NATIVE_BIND ? call.bind(call) : function () { + return call.apply(call, arguments); +}; -var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; -var FAUX_ITERATOR_SYMBOL = '@@iterator'; -var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { -var Iterator = function Iterator(next) { - this.next = next; -}; +"use strict"; -Iterator.prototype.toString = function toString () { - return '[Iterator]'; -}; +var isObject = __webpack_require__(8); -Iterator.KEYS = ITERATE_KEYS; -Iterator.VALUES = ITERATE_VALUES; -Iterator.ENTRIES = ITERATE_ENTRIES; +var $String = String; +var $TypeError = TypeError; -Iterator.prototype.inspect = Iterator.prototype.toSource = function () { - return this.toString(); -}; -Iterator.prototype[ITERATOR_SYMBOL] = function () { - return this; +// `Assert: Type(argument) is Object` +module.exports = function (argument) { + if (isObject(argument)) return argument; + throw new $TypeError($String(argument) + ' is not an object'); }; -function iteratorValue(type, k, v, iteratorResult) { - var value = - type === ITERATE_KEYS ? k : type === ITERATE_VALUES ? v : [k, v]; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - iteratorResult - ? (iteratorResult.value = value) - : (iteratorResult = { - value: value, - done: false, - }); - return iteratorResult; -} -function iteratorDone() { - return { value: undefined, done: true }; -} +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { -function hasIterator(maybeIterable) { - if (Array.isArray(maybeIterable)) { - // IE11 trick as it does not support `Symbol.iterator` - return true; - } +"use strict"; - return !!getIteratorFn(maybeIterable); -} +var fails = __webpack_require__(1); -function isIterator(maybeIterator) { - return maybeIterator && typeof maybeIterator.next === 'function'; -} +// Detect IE8's incomplete defineProperty implementation +module.exports = !fails(function () { + // eslint-disable-next-line es/no-object-defineproperty -- required for testing + return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7; +}); -function getIterator(iterable) { - var iteratorFn = getIteratorFn(iterable); - return iteratorFn && iteratorFn.call(iterable); -} -function getIteratorFn(iterable) { - var iteratorFn = - iterable && - ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || - iterable[FAUX_ITERATOR_SYMBOL]); - if (typeof iteratorFn === 'function') { - return iteratorFn; - } -} +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { -function isEntriesIterable(maybeIterable) { - var iteratorFn = getIteratorFn(maybeIterable); - return iteratorFn && iteratorFn === maybeIterable.entries; -} +"use strict"; -function isKeysIterable(maybeIterable) { - var iteratorFn = getIteratorFn(maybeIterable); - return iteratorFn && iteratorFn === maybeIterable.keys; -} +var globalThis = __webpack_require__(3); +var shared = __webpack_require__(92); +var hasOwn = __webpack_require__(13); +var uid = __webpack_require__(95); +var NATIVE_SYMBOL = __webpack_require__(94); +var USE_SYMBOL_AS_UID = __webpack_require__(249); -var hasOwnProperty = Object.prototype.hasOwnProperty; +var Symbol = globalThis.Symbol; +var WellKnownSymbolsStore = shared('wks'); +var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid; -function isArrayLike(value) { - if (Array.isArray(value) || typeof value === 'string') { - return true; - } - // @ts-expect-error "Type 'unknown' is not assignable to type 'boolean'" : convert to Boolean - return (value && - typeof value === 'object' && - // @ts-expect-error check that `'length' in value &&` - Number.isInteger(value.length) && - // @ts-expect-error check that `'length' in value &&` - value.length >= 0 && - // @ts-expect-error check that `'length' in value &&` - (value.length === 0 - ? // Only {length: 0} is considered Array-like. - Object.keys(value).length === 1 - : // An object is only Array-like if it has a property where the last value - // in the array-like may be found (which could be undefined). - // @ts-expect-error check that `'length' in value &&` - value.hasOwnProperty(value.length - 1))); -} - -var Seq = /*@__PURE__*/(function (Collection) { - function Seq(value) { - // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptySequence() - : isImmutable(value) - ? value.toSeq() - : seqFromValue(value); - } - - if ( Collection ) Seq.__proto__ = Collection; - Seq.prototype = Object.create( Collection && Collection.prototype ); - Seq.prototype.constructor = Seq; +module.exports = function (name) { + if (!hasOwn(WellKnownSymbolsStore, name)) { + WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name) + ? Symbol[name] + : createWellKnownSymbol('Symbol.' + name); + } return WellKnownSymbolsStore[name]; +}; - Seq.prototype.toSeq = function toSeq () { - return this; - }; - Seq.prototype.toString = function toString () { - return this.__toString('Seq {', '}'); - }; +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { - Seq.prototype.cacheResult = function cacheResult () { - if (!this._cache && this.__iterateUncached) { - this._cache = this.entrySeq().toArray(); - this.size = this._cache.length; - } - return this; - }; +"use strict"; - // abstract __iterateUncached(fn, reverse) +var isCallable = __webpack_require__(14); - Seq.prototype.__iterate = function __iterate (fn, reverse) { - var cache = this._cache; - if (cache) { - var size = cache.length; - var i = 0; - while (i !== size) { - var entry = cache[reverse ? size - ++i : i++]; - if (fn(entry[1], entry[0], this) === false) { - break; - } - } - return i; - } - return this.__iterateUncached(fn, reverse); - }; +module.exports = function (it) { + return typeof it == 'object' ? it !== null : isCallable(it); +}; - // abstract __iteratorUncached(type, reverse) - Seq.prototype.__iterator = function __iterator (type, reverse) { - var cache = this._cache; - if (cache) { - var size = cache.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var entry = cache[reverse ? size - ++i : i++]; - return iteratorValue(type, entry[0], entry[1]); - }); - } - return this.__iteratorUncached(type, reverse); - }; +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { - return Seq; -}(Collection)); +"use strict"; -var KeyedSeq = /*@__PURE__*/(function (Seq) { - function KeyedSeq(value) { - // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptySequence().toKeyedSeq() - : isCollection(value) - ? isKeyed(value) - ? value.toSeq() - : value.fromEntrySeq() - : isRecord(value) - ? value.toSeq() - : keyedSeqFromValue(value); - } +var classof = __webpack_require__(47); - if ( Seq ) KeyedSeq.__proto__ = Seq; - KeyedSeq.prototype = Object.create( Seq && Seq.prototype ); - KeyedSeq.prototype.constructor = KeyedSeq; +var $String = String; - KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () { - return this; - }; +module.exports = function (argument) { + if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string'); + return $String(argument); +}; - return KeyedSeq; -}(Seq)); -var IndexedSeq = /*@__PURE__*/(function (Seq) { - function IndexedSeq(value) { - // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptySequence() - : isCollection(value) - ? isKeyed(value) - ? value.entrySeq() - : value.toIndexedSeq() - : isRecord(value) - ? value.toSeq().entrySeq() - : indexedSeqFromValue(value); - } +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { - if ( Seq ) IndexedSeq.__proto__ = Seq; - IndexedSeq.prototype = Object.create( Seq && Seq.prototype ); - IndexedSeq.prototype.constructor = IndexedSeq; +"use strict"; - IndexedSeq.of = function of (/*...values*/) { - return IndexedSeq(arguments); - }; +var isCallable = __webpack_require__(14); +var tryToString = __webpack_require__(78); - IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () { - return this; - }; +var $TypeError = TypeError; - IndexedSeq.prototype.toString = function toString () { - return this.__toString('Seq [', ']'); - }; +// `Assert: IsCallable(argument) is true` +module.exports = function (argument) { + if (isCallable(argument)) return argument; + throw new $TypeError(tryToString(argument) + ' is not a function'); +}; - return IndexedSeq; -}(Seq)); -var SetSeq = /*@__PURE__*/(function (Seq) { - function SetSeq(value) { - // eslint-disable-next-line no-constructor-return - return ( - isCollection(value) && !isAssociative(value) ? value : IndexedSeq(value) - ).toSetSeq(); - } +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { - if ( Seq ) SetSeq.__proto__ = Seq; - SetSeq.prototype = Object.create( Seq && Seq.prototype ); - SetSeq.prototype.constructor = SetSeq; +"use strict"; - SetSeq.of = function of (/*...values*/) { - return SetSeq(arguments); - }; +var globalThis = __webpack_require__(3); +var isCallable = __webpack_require__(14); - SetSeq.prototype.toSetSeq = function toSetSeq () { - return this; - }; +var aFunction = function (argument) { + return isCallable(argument) ? argument : undefined; +}; - return SetSeq; -}(Seq)); +module.exports = function (namespace, method) { + return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method]; +}; -Seq.isSeq = isSeq; -Seq.Keyed = KeyedSeq; -Seq.Set = SetSeq; -Seq.Indexed = IndexedSeq; -Seq.prototype[IS_SEQ_SYMBOL] = true; +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { -// #pragma Root Sequences +"use strict"; -var ArraySeq = /*@__PURE__*/(function (IndexedSeq) { - function ArraySeq(array) { - this._array = array; - this.size = array.length; - } +var NATIVE_ARRAY_BUFFER = __webpack_require__(110); +var DESCRIPTORS = __webpack_require__(6); +var globalThis = __webpack_require__(3); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var hasOwn = __webpack_require__(13); +var classof = __webpack_require__(47); +var tryToString = __webpack_require__(78); +var createNonEnumerableProperty = __webpack_require__(27); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltInAccessor = __webpack_require__(23); +var isPrototypeOf = __webpack_require__(36); +var getPrototypeOf = __webpack_require__(35); +var setPrototypeOf = __webpack_require__(49); +var wellKnownSymbol = __webpack_require__(7); +var uid = __webpack_require__(95); +var InternalStateModule = __webpack_require__(21); - if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq; - ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); - ArraySeq.prototype.constructor = ArraySeq; +var enforceInternalState = InternalStateModule.enforce; +var getInternalState = InternalStateModule.get; +var Int8Array = globalThis.Int8Array; +var Int8ArrayPrototype = Int8Array && Int8Array.prototype; +var Uint8ClampedArray = globalThis.Uint8ClampedArray; +var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; +var TypedArray = Int8Array && getPrototypeOf(Int8Array); +var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); +var ObjectPrototype = Object.prototype; +var TypeError = globalThis.TypeError; - ArraySeq.prototype.get = function get (index, notSetValue) { - return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; - }; +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); +var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor'; +// Fixing native typed arrays in Opera Presto crashes the browser, see #595 +var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== 'Opera'; +var TYPED_ARRAY_TAG_REQUIRED = false; +var NAME, Constructor, Prototype; - ArraySeq.prototype.__iterate = function __iterate (fn, reverse) { - var array = this._array; - var size = array.length; - var i = 0; - while (i !== size) { - var ii = reverse ? size - ++i : i++; - if (fn(array[ii], ii, this) === false) { - break; - } - } - return i; - }; +var TypedArrayConstructorsList = { + Int8Array: 1, + Uint8Array: 1, + Uint8ClampedArray: 1, + Int16Array: 2, + Uint16Array: 2, + Int32Array: 4, + Uint32Array: 4, + Float32Array: 4, + Float64Array: 8 +}; - ArraySeq.prototype.__iterator = function __iterator (type, reverse) { - var array = this._array; - var size = array.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var ii = reverse ? size - ++i : i++; - return iteratorValue(type, ii, array[ii]); - }); - }; +var BigIntArrayConstructorsList = { + BigInt64Array: 8, + BigUint64Array: 8 +}; - return ArraySeq; -}(IndexedSeq)); +var isView = function isView(it) { + if (!isObject(it)) return false; + var klass = classof(it); + return klass === 'DataView' + || hasOwn(TypedArrayConstructorsList, klass) + || hasOwn(BigIntArrayConstructorsList, klass); +}; -var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) { - function ObjectSeq(object) { - var keys = Object.keys(object).concat( - Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [] - ); - this._object = object; - this._keys = keys; - this.size = keys.length; - } +var getTypedArrayConstructor = function (it) { + var proto = getPrototypeOf(it); + if (!isObject(proto)) return; + var state = getInternalState(proto); + return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto); +}; - if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq; - ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); - ObjectSeq.prototype.constructor = ObjectSeq; +var isTypedArray = function (it) { + if (!isObject(it)) return false; + var klass = classof(it); + return hasOwn(TypedArrayConstructorsList, klass) + || hasOwn(BigIntArrayConstructorsList, klass); +}; - ObjectSeq.prototype.get = function get (key, notSetValue) { - if (notSetValue !== undefined && !this.has(key)) { - return notSetValue; - } - return this._object[key]; - }; +var aTypedArray = function (it) { + if (isTypedArray(it)) return it; + throw new TypeError('Target is not a typed array'); +}; - ObjectSeq.prototype.has = function has (key) { - return hasOwnProperty.call(this._object, key); - }; +var aTypedArrayConstructor = function (C) { + if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C; + throw new TypeError(tryToString(C) + ' is not a typed array constructor'); +}; - ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) { - var object = this._object; - var keys = this._keys; - var size = keys.length; - var i = 0; - while (i !== size) { - var key = keys[reverse ? size - ++i : i++]; - if (fn(object[key], key, this) === false) { - break; - } +var exportTypedArrayMethod = function (KEY, property, forced, options) { + if (!DESCRIPTORS) return; + if (forced) for (var ARRAY in TypedArrayConstructorsList) { + var TypedArrayConstructor = globalThis[ARRAY]; + if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try { + delete TypedArrayConstructor.prototype[KEY]; + } catch (error) { + // old WebKit bug - some methods are non-configurable + try { + TypedArrayConstructor.prototype[KEY] = property; + } catch (error2) { /* empty */ } } - return i; - }; - - ObjectSeq.prototype.__iterator = function __iterator (type, reverse) { - var object = this._object; - var keys = this._keys; - var size = keys.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var key = keys[reverse ? size - ++i : i++]; - return iteratorValue(type, key, object[key]); - }); - }; - - return ObjectSeq; -}(KeyedSeq)); -ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true; - -var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) { - function CollectionSeq(collection) { - this._collection = collection; - this.size = collection.length || collection.size; } + if (!TypedArrayPrototype[KEY] || forced) { + defineBuiltIn(TypedArrayPrototype, KEY, forced ? property + : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options); + } +}; - if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq; - CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); - CollectionSeq.prototype.constructor = CollectionSeq; - - CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) { - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var collection = this._collection; - var iterator = getIterator(collection); - var iterations = 0; - if (isIterator(iterator)) { - var step; - while (!(step = iterator.next()).done) { - if (fn(step.value, iterations++, this) === false) { - break; - } - } - } - return iterations; - }; - - CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) { - if (reverse) { - return this.cacheResult().__iterator(type, reverse); +var exportTypedArrayStaticMethod = function (KEY, property, forced) { + var ARRAY, TypedArrayConstructor; + if (!DESCRIPTORS) return; + if (setPrototypeOf) { + if (forced) for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = globalThis[ARRAY]; + if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try { + delete TypedArrayConstructor[KEY]; + } catch (error) { /* empty */ } } - var collection = this._collection; - var iterator = getIterator(collection); - if (!isIterator(iterator)) { - return new Iterator(iteratorDone); + if (!TypedArray[KEY] || forced) { + // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable + try { + return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property); + } catch (error) { /* empty */ } + } else return; + } + for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = globalThis[ARRAY]; + if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { + defineBuiltIn(TypedArrayConstructor, KEY, property); } - var iterations = 0; - return new Iterator(function () { - var step = iterator.next(); - return step.done ? step : iteratorValue(type, iterations++, step.value); - }); - }; - - return CollectionSeq; -}(IndexedSeq)); - -// # pragma Helper functions - -var EMPTY_SEQ; + } +}; -function emptySequence() { - return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); +for (NAME in TypedArrayConstructorsList) { + Constructor = globalThis[NAME]; + Prototype = Constructor && Constructor.prototype; + if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; + else NATIVE_ARRAY_BUFFER_VIEWS = false; } -function keyedSeqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (seq) { - return seq.fromEntrySeq(); - } - if (typeof value === 'object') { - return new ObjectSeq(value); - } - throw new TypeError( - 'Expected Array or collection object of [k, v] entries, or keyed object: ' + - value - ); +for (NAME in BigIntArrayConstructorsList) { + Constructor = globalThis[NAME]; + Prototype = Constructor && Constructor.prototype; + if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; } -function indexedSeqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (seq) { - return seq; +// WebKit bug - typed arrays constructors prototype is Object.prototype +if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) { + // eslint-disable-next-line no-shadow -- safe + TypedArray = function TypedArray() { + throw new TypeError('Incorrect invocation'); + }; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray); } - throw new TypeError( - 'Expected Array or collection object of values: ' + value - ); } -function seqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (seq) { - return isEntriesIterable(value) - ? seq.fromEntrySeq() - : isKeysIterable(value) - ? seq.toSetSeq() - : seq; - } - if (typeof value === 'object') { - return new ObjectSeq(value); +if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { + TypedArrayPrototype = TypedArray.prototype; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype); } - throw new TypeError( - 'Expected Array or collection object of values, or keyed object: ' + value - ); -} - -function maybeIndexedSeqFromValue(value) { - return isArrayLike(value) - ? new ArraySeq(value) - : hasIterator(value) - ? new CollectionSeq(value) - : undefined; } -var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@'; -/** - * True if `maybeMap` is a Map. - * - * Also true for OrderedMaps. - */ -function isMap(maybeMap) { - return Boolean(maybeMap && - // @ts-expect-error: maybeMap is typed as `{}`, need to change in 6.0 to `maybeMap && typeof maybeMap === 'object' && IS_MAP_SYMBOL in maybeMap` - maybeMap[IS_MAP_SYMBOL]); +// WebKit bug - one more object in Uint8ClampedArray prototype chain +if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { + setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); } -/** - * True if `maybeOrderedMap` is an OrderedMap. - */ -function isOrderedMap(maybeOrderedMap) { - return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); +if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) { + TYPED_ARRAY_TAG_REQUIRED = true; + defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, { + configurable: true, + get: function () { + return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; + } + }); + for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) { + createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME); + } } -/** - * True if `maybeValue` is a JavaScript Object which has *both* `equals()` - * and `hashCode()` methods. - * - * Any two instances of *value objects* can be compared for value equality with - * `Immutable.is()` and can be used as keys in a `Map` or members in a `Set`. - */ -function isValueObject(maybeValue) { - return Boolean(maybeValue && - // @ts-expect-error: maybeValue is typed as `{}` - typeof maybeValue.equals === 'function' && - // @ts-expect-error: maybeValue is typed as `{}` - typeof maybeValue.hashCode === 'function'); -} +module.exports = { + NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, + TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG, + aTypedArray: aTypedArray, + aTypedArrayConstructor: aTypedArrayConstructor, + exportTypedArrayMethod: exportTypedArrayMethod, + exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, + getTypedArrayConstructor: getTypedArrayConstructor, + isView: isView, + isTypedArray: isTypedArray, + TypedArray: TypedArray, + TypedArrayPrototype: TypedArrayPrototype +}; -/** - * An extension of the "same-value" algorithm as [described for use by ES6 Map - * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) - * - * NaN is considered the same as NaN, however -0 and 0 are considered the same - * value, which is different from the algorithm described by - * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * This is extended further to allow Objects to describe the values they - * represent, by way of `valueOf` or `equals` (and `hashCode`). - * - * Note: because of this extension, the key equality of Immutable.Map and the - * value equality of Immutable.Set will differ from ES6 Map and Set. - * - * ### Defining custom values - * - * The easiest way to describe the value an object represents is by implementing - * `valueOf`. For example, `Date` represents a value by returning a unix - * timestamp for `valueOf`: - * - * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... - * var date2 = new Date(1234567890000); - * date1.valueOf(); // 1234567890000 - * assert( date1 !== date2 ); - * assert( Immutable.is( date1, date2 ) ); - * - * Note: overriding `valueOf` may have other implications if you use this object - * where JavaScript expects a primitive, such as implicit string coercion. - * - * For more complex types, especially collections, implementing `valueOf` may - * not be performant. An alternative is to implement `equals` and `hashCode`. - * - * `equals` takes another object, presumably of similar type, and returns true - * if it is equal. Equality is symmetrical, so the same result should be - * returned if this and the argument are flipped. - * - * assert( a.equals(b) === b.equals(a) ); - * - * `hashCode` returns a 32bit integer number representing the object which will - * be used to determine how to store the value object in a Map or Set. You must - * provide both or neither methods, one must not exist without the other. - * - * Also, an important relationship between these methods must be upheld: if two - * values are equal, they *must* return the same hashCode. If the values are not - * equal, they might have the same hashCode; this is called a hash collision, - * and while undesirable for performance reasons, it is acceptable. - * - * if (a.equals(b)) { - * assert( a.hashCode() === b.hashCode() ); - * } - * - * All Immutable collections are Value Objects: they implement `equals()` - * and `hashCode()`. - */ -function is(valueA, valueB) { - if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { - return true; - } - if (!valueA || !valueB) { - return false; - } - if (typeof valueA.valueOf === 'function' && - typeof valueB.valueOf === 'function') { - valueA = valueA.valueOf(); - valueB = valueB.valueOf(); - if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { - return true; - } - if (!valueA || !valueB) { - return false; - } - } - return !!(isValueObject(valueA) && - isValueObject(valueB) && - valueA.equals(valueB)); -} -var imul = - typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 - ? Math.imul - : function imul(a, b) { - a |= 0; // int - b |= 0; // int - var c = a & 0xffff; - var d = b & 0xffff; - // Shift by 0 fixes the sign on the high part. - return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int - }; +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { -// v8 has an optimization for storing 31-bit signed numbers. -// Values which have either 00 or 11 as the high order bits qualify. -// This function drops the highest order bit in a signed number, maintaining -// the sign bit. -function smi(i32) { - return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff); -} +"use strict"; -var defaultValueOf = Object.prototype.valueOf; +var uncurryThis = __webpack_require__(2); +var toObject = __webpack_require__(15); -function hash(o) { - // eslint-disable-next-line eqeqeq - if (o == null) { - return hashNullish(o); - } +var hasOwnProperty = uncurryThis({}.hasOwnProperty); - if (typeof o.hashCode === 'function') { - // Drop any high bits from accidentally long hash codes. - return smi(o.hashCode(o)); - } +// `HasOwnProperty` abstract operation +// https://tc39.es/ecma262/#sec-hasownproperty +// eslint-disable-next-line es/no-object-hasown -- safe +module.exports = Object.hasOwn || function hasOwn(it, key) { + return hasOwnProperty(toObject(it), key); +}; - var v = valueOf(o); - // eslint-disable-next-line eqeqeq - if (v == null) { - return hashNullish(v); - } +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { - switch (typeof v) { - case 'boolean': - // The hash values for built-in constants are a 1 value for each 5-byte - // shift region expect for the first, which encodes the value. This - // reduces the odds of a hash collision for these common values. - return v ? 0x42108421 : 0x42108420; - case 'number': - return hashNumber(v); - case 'string': - return v.length > STRING_HASH_CACHE_MIN_STRLEN - ? cachedHashString(v) - : hashString(v); - case 'object': - case 'function': - return hashJSObj(v); - case 'symbol': - return hashSymbol(v); - default: - if (typeof v.toString === 'function') { - return hashString(v.toString()); - } - throw new Error('Value type ' + typeof v + ' cannot be hashed.'); - } -} +"use strict"; -function hashNullish(nullish) { - return nullish === null ? 0x42108422 : /* undefined */ 0x42108423; -} +// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot +var documentAll = typeof document == 'object' && document.all; -// Compress arbitrarily large numbers into smi hashes. -function hashNumber(n) { - if (n !== n || n === Infinity) { - return 0; - } - var hash = n | 0; - if (hash !== n) { - hash ^= n * 0xffffffff; - } - while (n > 0xffffffff) { - n /= 0xffffffff; - hash ^= n; - } - return smi(hash); -} +// `IsCallable` abstract operation +// https://tc39.es/ecma262/#sec-iscallable +// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing +module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) { + return typeof argument == 'function' || argument === documentAll; +} : function (argument) { + return typeof argument == 'function'; +}; -function cachedHashString(string) { - var hashed = stringHashCache[string]; - if (hashed === undefined) { - hashed = hashString(string); - if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { - STRING_HASH_CACHE_SIZE = 0; - stringHashCache = {}; - } - STRING_HASH_CACHE_SIZE++; - stringHashCache[string] = hashed; - } - return hashed; -} -// http://jsperf.com/hashing-strings -function hashString(string) { - // This is the hash from JVM - // The hash code for a string is computed as - // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], - // where s[i] is the ith character of the string and n is the length of - // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 - // (exclusive) by dropping high bits. - var hashed = 0; - for (var ii = 0; ii < string.length; ii++) { - hashed = (31 * hashed + string.charCodeAt(ii)) | 0; - } - return smi(hashed); -} +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { -function hashSymbol(sym) { - var hashed = symbolMap[sym]; - if (hashed !== undefined) { - return hashed; - } +"use strict"; - hashed = nextHash(); +var requireObjectCoercible = __webpack_require__(20); - symbolMap[sym] = hashed; +var $Object = Object; - return hashed; -} +// `ToObject` abstract operation +// https://tc39.es/ecma262/#sec-toobject +module.exports = function (argument) { + return $Object(requireObjectCoercible(argument)); +}; -function hashJSObj(obj) { - var hashed; - if (usingWeakMap) { - hashed = weakMap.get(obj); - if (hashed !== undefined) { - return hashed; - } - } - hashed = obj[UID_HASH_KEY]; - if (hashed !== undefined) { - return hashed; - } +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { - if (!canDefineProperty) { - hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; - if (hashed !== undefined) { - return hashed; - } +"use strict"; - hashed = getIENodeHash(obj); - if (hashed !== undefined) { - return hashed; - } - } +module.exports = false; - hashed = nextHash(); - if (usingWeakMap) { - weakMap.set(obj, hashed); - } else if (isExtensible !== undefined && isExtensible(obj) === false) { - throw new Error('Non-extensible objects are not allowed as keys.'); - } else if (canDefineProperty) { - Object.defineProperty(obj, UID_HASH_KEY, { - enumerable: false, - configurable: false, - writable: false, - value: hashed, - }); - } else if ( - obj.propertyIsEnumerable !== undefined && - obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable - ) { - // Since we can't define a non-enumerable property on the object - // we'll hijack one of the less-used non-enumerable properties to - // save our hash on it. Since this is a function it will not show up in - // `JSON.stringify` which is what we want. - obj.propertyIsEnumerable = function () { - return this.constructor.prototype.propertyIsEnumerable.apply( - this, - arguments - ); - }; - obj.propertyIsEnumerable[UID_HASH_KEY] = hashed; - } else if (obj.nodeType !== undefined) { - // At this point we couldn't get the IE `uniqueID` to use as a hash - // and we couldn't use a non-enumerable property to exploit the - // dontEnum bug so we simply add the `UID_HASH_KEY` on the node - // itself. - obj[UID_HASH_KEY] = hashed; - } else { - throw new Error('Unable to set a non-enumerable property on object.'); - } +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { - return hashed; -} +"use strict"; -// Get references to ES5 object methods. -var isExtensible = Object.isExtensible; +var isCallable = __webpack_require__(14); +var definePropertyModule = __webpack_require__(19); +var makeBuiltIn = __webpack_require__(162); +var defineGlobalProperty = __webpack_require__(152); -// True if Object.defineProperty works as expected. IE8 fails this test. -var canDefineProperty = (function () { - try { - Object.defineProperty({}, '@', {}); - return true; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } catch (e) { - return false; - } -})(); +module.exports = function (O, key, value, options) { + if (!options) options = {}; + var simple = options.enumerable; + var name = options.name !== undefined ? options.name : key; + if (isCallable(value)) makeBuiltIn(value, name, options); + if (options.global) { + if (simple) O[key] = value; + else defineGlobalProperty(key, value); + } else { + try { + if (!options.unsafe) delete O[key]; + else if (O[key]) simple = true; + } catch (error) { /* empty */ } + if (simple) O[key] = value; + else definePropertyModule.f(O, key, { + value: value, + enumerable: false, + configurable: !options.nonConfigurable, + writable: !options.nonWritable + }); + } return O; +}; -// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it -// and avoid memory leaks from the IE cloneNode bug. -function getIENodeHash(node) { - if (node && node.nodeType > 0) { - switch (node.nodeType) { - case 1: // Element - return node.uniqueID; - case 9: // Document - return node.documentElement && node.documentElement.uniqueID; - } - } -} -function valueOf(obj) { - return obj.valueOf !== defaultValueOf && typeof obj.valueOf === 'function' - ? obj.valueOf(obj) - : obj; -} +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { -function nextHash() { - var nextHash = ++_objHashUID; - if (_objHashUID & 0x40000000) { - _objHashUID = 0; - } - return nextHash; -} +"use strict"; -// If possible, use a WeakMap. -var usingWeakMap = typeof WeakMap === 'function'; -var weakMap; -if (usingWeakMap) { - weakMap = new WeakMap(); -} +var toLength = __webpack_require__(45); -var symbolMap = Object.create(null); +// `LengthOfArrayLike` abstract operation +// https://tc39.es/ecma262/#sec-lengthofarraylike +module.exports = function (obj) { + return toLength(obj.length); +}; -var _objHashUID = 0; -var UID_HASH_KEY = '__immutablehash__'; -if (typeof Symbol === 'function') { - UID_HASH_KEY = Symbol(UID_HASH_KEY); -} +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { -var STRING_HASH_CACHE_MIN_STRLEN = 16; -var STRING_HASH_CACHE_MAX_SIZE = 255; -var STRING_HASH_CACHE_SIZE = 0; -var stringHashCache = {}; +"use strict"; -var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq) { - function ToKeyedSequence(indexed, useKeys) { - this._iter = indexed; - this._useKeys = useKeys; - this.size = indexed.size; - } +var DESCRIPTORS = __webpack_require__(6); +var IE8_DOM_DEFINE = __webpack_require__(213); +var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(250); +var anObject = __webpack_require__(5); +var toPropertyKey = __webpack_require__(63); - if ( KeyedSeq ) ToKeyedSequence.__proto__ = KeyedSeq; - ToKeyedSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); - ToKeyedSequence.prototype.constructor = ToKeyedSequence; +var $TypeError = TypeError; +// eslint-disable-next-line es/no-object-defineproperty -- safe +var $defineProperty = Object.defineProperty; +// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe +var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var ENUMERABLE = 'enumerable'; +var CONFIGURABLE = 'configurable'; +var WRITABLE = 'writable'; - ToKeyedSequence.prototype.get = function get (key, notSetValue) { - return this._iter.get(key, notSetValue); - }; +// `Object.defineProperty` method +// https://tc39.es/ecma262/#sec-object.defineproperty +exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { + anObject(O); + P = toPropertyKey(P); + anObject(Attributes); + if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { + var current = $getOwnPropertyDescriptor(O, P); + if (current && current[WRITABLE]) { + O[P] = Attributes.value; + Attributes = { + configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], + enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], + writable: false + }; + } + } return $defineProperty(O, P, Attributes); +} : $defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPropertyKey(P); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return $defineProperty(O, P, Attributes); + } catch (error) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; - ToKeyedSequence.prototype.has = function has (key) { - return this._iter.has(key); - }; - ToKeyedSequence.prototype.valueSeq = function valueSeq () { - return this._iter.valueSeq(); - }; +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { - ToKeyedSequence.prototype.reverse = function reverse () { - var this$1$1 = this; +"use strict"; - var reversedSequence = reverseFactory(this, true); - if (!this._useKeys) { - reversedSequence.valueSeq = function () { return this$1$1._iter.toSeq().reverse(); }; - } - return reversedSequence; - }; +var isNullOrUndefined = __webpack_require__(57); - ToKeyedSequence.prototype.map = function map (mapper, context) { - var this$1$1 = this; +var $TypeError = TypeError; - var mappedSequence = mapFactory(this, mapper, context); - if (!this._useKeys) { - mappedSequence.valueSeq = function () { return this$1$1._iter.toSeq().map(mapper, context); }; - } - return mappedSequence; - }; +// `RequireObjectCoercible` abstract operation +// https://tc39.es/ecma262/#sec-requireobjectcoercible +module.exports = function (it) { + if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it); + return it; +}; - ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; - return this._iter.__iterate(function (v, k) { return fn(v, k, this$1$1); }, reverse); - }; +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { - ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) { - return this._iter.__iterator(type, reverse); - }; +"use strict"; - return ToKeyedSequence; -}(KeyedSeq)); -ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true; +var NATIVE_WEAK_MAP = __webpack_require__(251); +var globalThis = __webpack_require__(3); +var isObject = __webpack_require__(8); +var createNonEnumerableProperty = __webpack_require__(27); +var hasOwn = __webpack_require__(13); +var shared = __webpack_require__(132); +var sharedKey = __webpack_require__(131); +var hiddenKeys = __webpack_require__(100); -var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq) { - function ToIndexedSequence(iter) { - this._iter = iter; - this.size = iter.size; - } +var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; +var TypeError = globalThis.TypeError; +var WeakMap = globalThis.WeakMap; +var set, get, has; - if ( IndexedSeq ) ToIndexedSequence.__proto__ = IndexedSeq; - ToIndexedSequence.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); - ToIndexedSequence.prototype.constructor = ToIndexedSequence; +var enforce = function (it) { + return has(it) ? get(it) : set(it, {}); +}; - ToIndexedSequence.prototype.includes = function includes (value) { - return this._iter.includes(value); +var getterFor = function (TYPE) { + return function (it) { + var state; + if (!isObject(it) || (state = get(it)).type !== TYPE) { + throw new TypeError('Incompatible receiver, ' + TYPE + ' required'); + } return state; }; +}; - ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; - - var i = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - reverse && ensureSize(this); - return this._iter.__iterate( - function (v) { return fn(v, reverse ? this$1$1.size - ++i : i++, this$1$1); }, - reverse - ); +if (NATIVE_WEAK_MAP || shared.state) { + var store = shared.state || (shared.state = new WeakMap()); + /* eslint-disable no-self-assign -- prototype methods protection */ + store.get = store.get; + store.has = store.has; + store.set = store.set; + /* eslint-enable no-self-assign -- prototype methods protection */ + set = function (it, metadata) { + if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); + metadata.facade = it; + store.set(it, metadata); + return metadata; }; - - ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) { - var this$1$1 = this; - - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - var i = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - reverse && ensureSize(this); - return new Iterator(function () { - var step = iterator.next(); - return step.done - ? step - : iteratorValue( - type, - reverse ? this$1$1.size - ++i : i++, - step.value, - step - ); - }); + get = function (it) { + return store.get(it) || {}; + }; + has = function (it) { + return store.has(it); + }; +} else { + var STATE = sharedKey('state'); + hiddenKeys[STATE] = true; + set = function (it, metadata) { + if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); + metadata.facade = it; + createNonEnumerableProperty(it, STATE, metadata); + return metadata; }; + get = function (it) { + return hasOwn(it, STATE) ? it[STATE] : {}; + }; + has = function (it) { + return hasOwn(it, STATE); + }; +} - return ToIndexedSequence; -}(IndexedSeq)); +module.exports = { + set: set, + get: get, + has: has, + enforce: enforce, + getterFor: getterFor +}; -var ToSetSequence = /*@__PURE__*/(function (SetSeq) { - function ToSetSequence(iter) { - this._iter = iter; - this.size = iter.size; - } - if ( SetSeq ) ToSetSequence.__proto__ = SetSeq; - ToSetSequence.prototype = Object.create( SetSeq && SetSeq.prototype ); - ToSetSequence.prototype.constructor = ToSetSequence; +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { - ToSetSequence.prototype.has = function has (key) { - return this._iter.includes(key); - }; +"use strict"; - ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; +var trunc = __webpack_require__(225); - return this._iter.__iterate(function (v) { return fn(v, v, this$1$1); }, reverse); - }; +// `ToIntegerOrInfinity` abstract operation +// https://tc39.es/ecma262/#sec-tointegerorinfinity +module.exports = function (argument) { + var number = +argument; + // eslint-disable-next-line no-self-compare -- NaN check + return number !== number || number === 0 ? 0 : trunc(number); +}; - ToSetSequence.prototype.__iterator = function __iterator (type, reverse) { - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - return new Iterator(function () { - var step = iterator.next(); - return step.done - ? step - : iteratorValue(type, step.value, step.value, step); - }); - }; - return ToSetSequence; -}(SetSeq)); +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { -var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq) { - function FromEntriesSequence(entries) { - this._iter = entries; - this.size = entries.size; - } +"use strict"; - if ( KeyedSeq ) FromEntriesSequence.__proto__ = KeyedSeq; - FromEntriesSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); - FromEntriesSequence.prototype.constructor = FromEntriesSequence; +var makeBuiltIn = __webpack_require__(162); +var defineProperty = __webpack_require__(19); - FromEntriesSequence.prototype.entrySeq = function entrySeq () { - return this._iter.toSeq(); - }; +module.exports = function (target, name, descriptor) { + if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true }); + if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true }); + return defineProperty.f(target, name, descriptor); +}; - FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; - return this._iter.__iterate(function (entry) { - // Check if entry exists first so array access doesn't throw for holes - // in the parent iteration. - if (entry) { - validateEntry(entry); - var indexedCollection = isCollection(entry); - return fn( - indexedCollection ? entry.get(1) : entry[1], - indexedCollection ? entry.get(0) : entry[0], - this$1$1 - ); - } - }, reverse); - }; +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { - FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) { - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - return new Iterator(function () { - while (true) { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - // Check if entry exists first so array access doesn't throw for holes - // in the parent iteration. - if (entry) { - validateEntry(entry); - var indexedCollection = isCollection(entry); - return iteratorValue( - type, - indexedCollection ? entry.get(0) : entry[0], - indexedCollection ? entry.get(1) : entry[1], - step - ); - } - } - }); - }; +"use strict"; - return FromEntriesSequence; -}(KeyedSeq)); +var bind = __webpack_require__(43); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var tryToString = __webpack_require__(78); +var isArrayIteratorMethod = __webpack_require__(158); +var lengthOfArrayLike = __webpack_require__(18); +var isPrototypeOf = __webpack_require__(36); +var getIterator = __webpack_require__(83); +var getIteratorMethod = __webpack_require__(68); +var iteratorClose = __webpack_require__(29); -ToIndexedSequence.prototype.cacheResult = - ToKeyedSequence.prototype.cacheResult = - ToSetSequence.prototype.cacheResult = - FromEntriesSequence.prototype.cacheResult = - cacheResultThrough; +var $TypeError = TypeError; -function flipFactory(collection) { - var flipSequence = makeSequence(collection); - flipSequence._iter = collection; - flipSequence.size = collection.size; - flipSequence.flip = function () { return collection; }; - flipSequence.reverse = function () { - var reversedSequence = collection.reverse.apply(this); // super.reverse() - reversedSequence.flip = function () { return collection.reverse(); }; - return reversedSequence; - }; - flipSequence.has = function (key) { return collection.includes(key); }; - flipSequence.includes = function (key) { return collection.has(key); }; - flipSequence.cacheResult = cacheResultThrough; - flipSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; +var Result = function (stopped, result) { + this.stopped = stopped; + this.result = result; +}; - return collection.__iterate(function (v, k) { return fn(k, v, this$1$1) !== false; }, reverse); - }; - flipSequence.__iteratorUncached = function (type, reverse) { - if (type === ITERATE_ENTRIES) { - var iterator = collection.__iterator(type, reverse); - return new Iterator(function () { - var step = iterator.next(); - if (!step.done) { - var k = step.value[0]; - step.value[0] = step.value[1]; - step.value[1] = k; - } - return step; - }); - } - return collection.__iterator( - type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, - reverse - ); - }; - return flipSequence; -} +var ResultPrototype = Result.prototype; -function mapFactory(collection, mapper, context) { - var mappedSequence = makeSequence(collection); - mappedSequence.size = collection.size; - mappedSequence.has = function (key) { return collection.has(key); }; - mappedSequence.get = function (key, notSetValue) { - var v = collection.get(key, NOT_SET); - return v === NOT_SET - ? notSetValue - : mapper.call(context, v, key, collection); - }; - mappedSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; +module.exports = function (iterable, unboundFunction, options) { + var that = options && options.that; + var AS_ENTRIES = !!(options && options.AS_ENTRIES); + var IS_RECORD = !!(options && options.IS_RECORD); + var IS_ITERATOR = !!(options && options.IS_ITERATOR); + var INTERRUPTED = !!(options && options.INTERRUPTED); + var fn = bind(unboundFunction, that); + var iterator, iterFn, index, length, result, next, step; - return collection.__iterate( - function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1$1) !== false; }, - reverse - ); - }; - mappedSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - return new Iterator(function () { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var key = entry[0]; - return iteratorValue( - type, - key, - mapper.call(context, entry[1], key, collection), - step - ); - }); + var stop = function (condition) { + if (iterator) iteratorClose(iterator, 'normal'); + return new Result(true, condition); }; - return mappedSequence; -} - -function reverseFactory(collection, useKeys) { - var this$1$1 = this; - - var reversedSequence = makeSequence(collection); - reversedSequence._iter = collection; - reversedSequence.size = collection.size; - reversedSequence.reverse = function () { return collection; }; - if (collection.flip) { - reversedSequence.flip = function () { - var flipSequence = flipFactory(collection); - flipSequence.reverse = function () { return collection.flip(); }; - return flipSequence; - }; - } - reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); }; - reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); }; - reversedSequence.includes = function (value) { return collection.includes(value); }; - reversedSequence.cacheResult = cacheResultThrough; - reversedSequence.__iterate = function (fn, reverse) { - var this$1$1 = this; - var i = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - reverse && ensureSize(collection); - return collection.__iterate( - function (v, k) { return fn(v, useKeys ? k : reverse ? this$1$1.size - ++i : i++, this$1$1); }, - !reverse - ); - }; - reversedSequence.__iterator = function (type, reverse) { - var i = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - reverse && ensureSize(collection); - var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse); - return new Iterator(function () { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - return iteratorValue( - type, - useKeys ? entry[0] : reverse ? this$1$1.size - ++i : i++, - entry[1], - step - ); - }); + var callFn = function (value) { + if (AS_ENTRIES) { + anObject(value); + return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); + } return INTERRUPTED ? fn(value, stop) : fn(value); }; - return reversedSequence; -} -function filterFactory(collection, predicate, context, useKeys) { - var filterSequence = makeSequence(collection); - if (useKeys) { - filterSequence.has = function (key) { - var v = collection.get(key, NOT_SET); - return v !== NOT_SET && !!predicate.call(context, v, key, collection); - }; - filterSequence.get = function (key, notSetValue) { - var v = collection.get(key, NOT_SET); - return v !== NOT_SET && predicate.call(context, v, key, collection) - ? v - : notSetValue; - }; + if (IS_RECORD) { + iterator = iterable.iterator; + } else if (IS_ITERATOR) { + iterator = iterable; + } else { + iterFn = getIteratorMethod(iterable); + if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable'); + // optimisation for array iterators + if (isArrayIteratorMethod(iterFn)) { + for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) { + result = callFn(iterable[index]); + if (result && isPrototypeOf(ResultPrototype, result)) return result; + } return new Result(false); + } + iterator = getIterator(iterable, iterFn); } - filterSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; - - var iterations = 0; - collection.__iterate(function (v, k, c) { - if (predicate.call(context, v, k, c)) { - iterations++; - return fn(v, useKeys ? k : iterations - 1, this$1$1); - } - }, reverse); - return iterations; - }; - filterSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var iterations = 0; - return new Iterator(function () { - while (true) { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var key = entry[0]; - var value = entry[1]; - if (predicate.call(context, value, key, collection)) { - return iteratorValue(type, useKeys ? key : iterations++, value, step); - } - } - }); - }; - return filterSequence; -} - -function countByFactory(collection, grouper, context) { - var groups = Map().asMutable(); - collection.__iterate(function (v, k) { - groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; }); - }); - return groups.asImmutable(); -} - -function groupByFactory(collection, grouper, context) { - var isKeyedIter = isKeyed(collection); - var groups = (isOrdered(collection) ? OrderedMap() : Map()).asMutable(); - collection.__iterate(function (v, k) { - groups.update( - grouper.call(context, v, k, collection), - function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); } - ); - }); - var coerce = collectionClass(collection); - return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable(); -} -function partitionFactory(collection, predicate, context) { - var isKeyedIter = isKeyed(collection); - var groups = [[], []]; - collection.__iterate(function (v, k) { - groups[predicate.call(context, v, k, collection) ? 1 : 0].push( - isKeyedIter ? [k, v] : v - ); - }); - var coerce = collectionClass(collection); - return groups.map(function (arr) { return reify(collection, coerce(arr)); }); -} + next = IS_RECORD ? iterable.next : iterator.next; + while (!(step = call(next, iterator)).done) { + try { + result = callFn(step.value); + } catch (error) { + iteratorClose(iterator, 'throw', error); + } + if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result; + } return new Result(false); +}; -function sliceFactory(collection, begin, end, useKeys) { - var originalSize = collection.size; - if (wholeSlice(begin, end, originalSize)) { - return collection; - } +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { - // begin or end can not be resolved if they were provided as negative numbers and - // this collection's size is unknown. In that case, cache first so there is - // a known size and these do not resolve to NaN. - if (typeof originalSize === 'undefined' && (begin < 0 || end < 0)) { - return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys); - } +"use strict"; - var resolvedBegin = resolveBegin(begin, originalSize); - var resolvedEnd = resolveEnd(end, originalSize); +// toObject with fallback for non-array-like ES3 strings +var IndexedObject = __webpack_require__(84); +var requireObjectCoercible = __webpack_require__(20); - // Note: resolvedEnd is undefined when the original sequence's length is - // unknown and this slice did not supply an end and should contain all - // elements after resolvedBegin. - // In that case, resolvedSize will be NaN and sliceSize will remain undefined. - var resolvedSize = resolvedEnd - resolvedBegin; - var sliceSize; - if (resolvedSize === resolvedSize) { - sliceSize = resolvedSize < 0 ? 0 : resolvedSize; - } +module.exports = function (it) { + return IndexedObject(requireObjectCoercible(it)); +}; - var sliceSeq = makeSequence(collection); - // If collection.size is undefined, the size of the realized sliceSeq is - // unknown at this point unless the number of items to slice is 0 - sliceSeq.size = - sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined; +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { - if (!useKeys && isSeq(collection) && sliceSize >= 0) { - sliceSeq.get = function (index, notSetValue) { - index = wrapIndex(this, index); - return index >= 0 && index < sliceSize - ? collection.get(index + resolvedBegin, notSetValue) - : notSetValue; - }; - } +"use strict"; - sliceSeq.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; +var bind = __webpack_require__(43); +var uncurryThis = __webpack_require__(2); +var IndexedObject = __webpack_require__(84); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var arraySpeciesCreate = __webpack_require__(98); - if (sliceSize === 0) { - return 0; - } - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var skipped = 0; - var isSkipping = true; - var iterations = 0; - collection.__iterate(function (v, k) { - if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { - iterations++; - return ( - fn(v, useKeys ? k : iterations - 1, this$1$1) !== false && - iterations !== sliceSize - ); - } - }); - return iterations; - }; +var push = uncurryThis([].push); - sliceSeq.__iteratorUncached = function (type, reverse) { - if (sliceSize !== 0 && reverse) { - return this.cacheResult().__iterator(type, reverse); - } - // Don't bother instantiating parent iterator if taking 0. - if (sliceSize === 0) { - return new Iterator(iteratorDone); - } - var iterator = collection.__iterator(type, reverse); - var skipped = 0; - var iterations = 0; - return new Iterator(function () { - while (skipped++ < resolvedBegin) { - iterator.next(); - } - if (++iterations > sliceSize) { - return iteratorDone(); - } - var step = iterator.next(); - if (useKeys || type === ITERATE_VALUES || step.done) { - return step; - } - if (type === ITERATE_KEYS) { - return iteratorValue(type, iterations - 1, undefined, step); +// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation +var createMethod = function (TYPE) { + var IS_MAP = TYPE === 1; + var IS_FILTER = TYPE === 2; + var IS_SOME = TYPE === 3; + var IS_EVERY = TYPE === 4; + var IS_FIND_INDEX = TYPE === 6; + var IS_FILTER_REJECT = TYPE === 7; + var NO_HOLES = TYPE === 5 || IS_FIND_INDEX; + return function ($this, callbackfn, that, specificCreate) { + var O = toObject($this); + var self = IndexedObject(O); + var length = lengthOfArrayLike(self); + var boundFunction = bind(callbackfn, that); + var index = 0; + var create = specificCreate || arraySpeciesCreate; + var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined; + var value, result; + for (;length > index; index++) if (NO_HOLES || index in self) { + value = self[index]; + result = boundFunction(value, index, O); + if (TYPE) { + if (IS_MAP) target[index] = result; // map + else if (result) switch (TYPE) { + case 3: return true; // some + case 5: return value; // find + case 6: return index; // findIndex + case 2: push(target, value); // filter + } else switch (TYPE) { + case 4: return false; // every + case 7: push(target, value); // filterReject + } } - return iteratorValue(type, iterations - 1, step.value[1], step); - }); + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; }; +}; - return sliceSeq; -} +module.exports = { + // `Array.prototype.forEach` method + // https://tc39.es/ecma262/#sec-array.prototype.foreach + forEach: createMethod(0), + // `Array.prototype.map` method + // https://tc39.es/ecma262/#sec-array.prototype.map + map: createMethod(1), + // `Array.prototype.filter` method + // https://tc39.es/ecma262/#sec-array.prototype.filter + filter: createMethod(2), + // `Array.prototype.some` method + // https://tc39.es/ecma262/#sec-array.prototype.some + some: createMethod(3), + // `Array.prototype.every` method + // https://tc39.es/ecma262/#sec-array.prototype.every + every: createMethod(4), + // `Array.prototype.find` method + // https://tc39.es/ecma262/#sec-array.prototype.find + find: createMethod(5), + // `Array.prototype.findIndex` method + // https://tc39.es/ecma262/#sec-array.prototype.findIndex + findIndex: createMethod(6), + // `Array.prototype.filterReject` method + // https://github.com/tc39/proposal-array-filtering + filterReject: createMethod(7) +}; -function takeWhileFactory(collection, predicate, context) { - var takeSequence = makeSequence(collection); - takeSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var iterations = 0; - collection.__iterate( - function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1$1); } - ); - return iterations; - }; - takeSequence.__iteratorUncached = function (type, reverse) { - var this$1$1 = this; +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var iterating = true; - return new Iterator(function () { - if (!iterating) { - return iteratorDone(); - } - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var k = entry[0]; - var v = entry[1]; - if (!predicate.call(context, v, k, this$1$1)) { - iterating = false; - return iteratorDone(); - } - return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); - }); - }; - return takeSequence; -} +"use strict"; -function skipWhileFactory(collection, predicate, context, useKeys) { - var skipSequence = makeSequence(collection); - skipSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; +var DESCRIPTORS = __webpack_require__(6); +var definePropertyModule = __webpack_require__(19); +var createPropertyDescriptor = __webpack_require__(41); - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var isSkipping = true; - var iterations = 0; - collection.__iterate(function (v, k, c) { - if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { - iterations++; - return fn(v, useKeys ? k : iterations - 1, this$1$1); - } - }); - return iterations; - }; - skipSequence.__iteratorUncached = function (type, reverse) { - var this$1$1 = this; +module.exports = DESCRIPTORS ? function (object, key, value) { + return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var skipping = true; - var iterations = 0; - return new Iterator(function () { - var step; - var k; - var v; - do { - step = iterator.next(); - if (step.done) { - if (useKeys || type === ITERATE_VALUES) { - return step; - } - if (type === ITERATE_KEYS) { - return iteratorValue(type, iterations++, undefined, step); - } - return iteratorValue(type, iterations++, step.value[1], step); - } - var entry = step.value; - k = entry[0]; - v = entry[1]; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - skipping && (skipping = predicate.call(context, v, k, this$1$1)); - } while (skipping); - return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); - }); - }; - return skipSequence; -} -var ConcatSeq = /*@__PURE__*/(function (Seq) { - function ConcatSeq(iterables) { - this._wrappedIterables = iterables.flatMap(function (iterable) { - if (iterable._wrappedIterables) { - return iterable._wrappedIterables; - } - return [iterable]; - }); - this.size = this._wrappedIterables.reduce(function (sum, iterable) { - if (sum !== undefined) { - var size = iterable.size; - if (size !== undefined) { - return sum + size; - } - } - }, 0); - this[IS_KEYED_SYMBOL] = this._wrappedIterables[0][IS_KEYED_SYMBOL]; - this[IS_INDEXED_SYMBOL] = this._wrappedIterables[0][IS_INDEXED_SYMBOL]; - this[IS_ORDERED_SYMBOL] = this._wrappedIterables[0][IS_ORDERED_SYMBOL]; - } +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { - if ( Seq ) ConcatSeq.__proto__ = Seq; - ConcatSeq.prototype = Object.create( Seq && Seq.prototype ); - ConcatSeq.prototype.constructor = ConcatSeq; +"use strict"; - ConcatSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) { - if (this._wrappedIterables.length === 0) { - return; - } +var aCallable = __webpack_require__(10); +var isNullOrUndefined = __webpack_require__(57); - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } +// `GetMethod` abstract operation +// https://tc39.es/ecma262/#sec-getmethod +module.exports = function (V, P) { + var func = V[P]; + return isNullOrUndefined(func) ? undefined : aCallable(func); +}; - var iterableIndex = 0; - var useKeys = isKeyed(this); - var iteratorType = useKeys ? ITERATE_ENTRIES : ITERATE_VALUES; - var currentIterator = this._wrappedIterables[iterableIndex].__iterator( - iteratorType, - reverse - ); - var keepGoing = true; - var index = 0; - while (keepGoing) { - var next = currentIterator.next(); - while (next.done) { - iterableIndex++; - if (iterableIndex === this._wrappedIterables.length) { - return index; - } - currentIterator = this._wrappedIterables[iterableIndex].__iterator( - iteratorType, - reverse - ); - next = currentIterator.next(); - } - var fnResult = useKeys - ? fn(next.value[1], next.value[0], this) - : fn(next.value, index, this); - keepGoing = fnResult !== false; - index++; - } - return index; - }; +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { - ConcatSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) { - var this$1$1 = this; +"use strict"; - if (this._wrappedIterables.length === 0) { - return new Iterator(iteratorDone); - } +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var getMethod = __webpack_require__(28); - if (reverse) { - return this.cacheResult().__iterator(type, reverse); +module.exports = function (iterator, kind, value) { + var innerResult, innerError; + anObject(iterator); + try { + innerResult = getMethod(iterator, 'return'); + if (!innerResult) { + if (kind === 'throw') throw value; + return value; } + innerResult = call(innerResult, iterator); + } catch (error) { + innerError = true; + innerResult = error; + } + if (kind === 'throw') throw value; + if (innerError) throw innerResult; + anObject(innerResult); + return value; +}; - var iterableIndex = 0; - var currentIterator = this._wrappedIterables[iterableIndex].__iterator( - type, - reverse - ); - return new Iterator(function () { - var next = currentIterator.next(); - while (next.done) { - iterableIndex++; - if (iterableIndex === this$1$1._wrappedIterables.length) { - return next; - } - currentIterator = this$1$1._wrappedIterables[iterableIndex].__iterator( - type, - reverse - ); - next = currentIterator.next(); - } - return next; - }); - }; - return ConcatSeq; -}(Seq)); +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { -function concatFactory(collection, values) { - var isKeyedCollection = isKeyed(collection); - var iters = [collection] - .concat(values) - .map(function (v) { - if (!isCollection(v)) { - v = isKeyedCollection - ? keyedSeqFromValue(v) - : indexedSeqFromValue(Array.isArray(v) ? v : [v]); - } else if (isKeyedCollection) { - v = KeyedCollection(v); - } - return v; - }) - .filter(function (v) { return v.size !== 0; }); +"use strict"; - if (iters.length === 0) { - return collection; - } +/* global ActiveXObject -- old IE, WSH */ +var anObject = __webpack_require__(5); +var definePropertiesModule = __webpack_require__(165); +var enumBugKeys = __webpack_require__(153); +var hiddenKeys = __webpack_require__(100); +var html = __webpack_require__(212); +var documentCreateElement = __webpack_require__(118); +var sharedKey = __webpack_require__(131); - if (iters.length === 1) { - var singleton = iters[0]; - if ( - singleton === collection || - (isKeyedCollection && isKeyed(singleton)) || - (isIndexed(collection) && isIndexed(singleton)) - ) { - return singleton; - } - } +var GT = '>'; +var LT = '<'; +var PROTOTYPE = 'prototype'; +var SCRIPT = 'script'; +var IE_PROTO = sharedKey('IE_PROTO'); - return new ConcatSeq(iters); -} +var EmptyConstructor = function () { /* empty */ }; -function flattenFactory(collection, depth, useKeys) { - var flatSequence = makeSequence(collection); - flatSequence.__iterateUncached = function (fn, reverse) { - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var iterations = 0; - var stopped = false; - function flatDeep(iter, currentDepth) { - iter.__iterate(function (v, k) { - if ((!depth || currentDepth < depth) && isCollection(v)) { - flatDeep(v, currentDepth + 1); - } else { - iterations++; - if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) { - stopped = true; - } - } - return !stopped; - }, reverse); - } - flatDeep(collection, 0); - return iterations; - }; - flatSequence.__iteratorUncached = function (type, reverse) { - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(type, reverse); - var stack = []; - var iterations = 0; - return new Iterator(function () { - while (iterator) { - var step = iterator.next(); - if (step.done !== false) { - iterator = stack.pop(); - continue; - } - var v = step.value; - if (type === ITERATE_ENTRIES) { - v = v[1]; - } - if ((!depth || stack.length < depth) && isCollection(v)) { - stack.push(iterator); - iterator = v.__iterator(type, reverse); - } else { - return useKeys ? step : iteratorValue(type, iterations++, v, step); - } - } - return iteratorDone(); - }); - }; - return flatSequence; -} +var scriptTag = function (content) { + return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; +}; -function flatMapFactory(collection, mapper, context) { - var coerce = collectionClass(collection); - return collection - .toSeq() - .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); }) - .flatten(true); -} +// Create object with fake `null` prototype: use ActiveX Object with cleared prototype +var NullProtoObjectViaActiveX = function (activeXDocument) { + activeXDocument.write(scriptTag('')); + activeXDocument.close(); + var temp = activeXDocument.parentWindow.Object; + // eslint-disable-next-line no-useless-assignment -- avoid memory leak + activeXDocument = null; + return temp; +}; -function interposeFactory(collection, separator) { - var interposedSequence = makeSequence(collection); - interposedSequence.size = collection.size && collection.size * 2 - 1; - interposedSequence.__iterateUncached = function (fn, reverse) { - var this$1$1 = this; +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var NullProtoObjectViaIFrame = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = documentCreateElement('iframe'); + var JS = 'java' + SCRIPT + ':'; + var iframeDocument; + iframe.style.display = 'none'; + html.appendChild(iframe); + // https://github.com/zloirock/core-js/issues/475 + iframe.src = String(JS); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(scriptTag('document.F=Object')); + iframeDocument.close(); + return iframeDocument.F; +}; - var iterations = 0; - collection.__iterate( - function (v) { return (!iterations || fn(separator, iterations++, this$1$1) !== false) && - fn(v, iterations++, this$1$1) !== false; }, - reverse - ); - return iterations; - }; - interposedSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_VALUES, reverse); - var iterations = 0; - var step; - return new Iterator(function () { - if (!step || iterations % 2) { - step = iterator.next(); - if (step.done) { - return step; - } - } - return iterations % 2 - ? iteratorValue(type, iterations++, separator) - : iteratorValue(type, iterations++, step.value, step); - }); - }; - return interposedSequence; -} +// Check for document.domain and active x support +// No need to use active x approach when document.domain is not set +// see https://github.com/es-shims/es5-shim/issues/150 +// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 +// avoid IE GC bug +var activeXDocument; +var NullProtoObject = function () { + try { + activeXDocument = new ActiveXObject('htmlfile'); + } catch (error) { /* ignore */ } + NullProtoObject = typeof document != 'undefined' + ? document.domain && activeXDocument + ? NullProtoObjectViaActiveX(activeXDocument) // old IE + : NullProtoObjectViaIFrame() + : NullProtoObjectViaActiveX(activeXDocument); // WSH + var length = enumBugKeys.length; + while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; + return NullProtoObject(); +}; -function sortFactory(collection, comparator, mapper) { - if (!comparator) { - comparator = defaultComparator; - } - var isKeyedCollection = isKeyed(collection); - var index = 0; - var entries = collection - .toSeq() - .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; }) - .valueSeq() - .toArray(); - entries - .sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }) - .forEach( - isKeyedCollection - ? function (v, i) { - entries[i].length = 2; - } - : function (v, i) { - entries[i] = v[1]; - } - ); - return isKeyedCollection - ? KeyedSeq(entries) - : isIndexed(collection) - ? IndexedSeq(entries) - : SetSeq(entries); -} +hiddenKeys[IE_PROTO] = true; -function maxFactory(collection, comparator, mapper) { - if (!comparator) { - comparator = defaultComparator; - } - if (mapper) { - var entry = collection - .toSeq() - .map(function (v, k) { return [v, mapper(v, k, collection)]; }) - .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); }); - return entry && entry[0]; - } - return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); }); -} +// `Object.create` method +// https://tc39.es/ecma262/#sec-object.create +// eslint-disable-next-line es/no-object-create -- safe +module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + EmptyConstructor[PROTOTYPE] = anObject(O); + result = new EmptyConstructor(); + EmptyConstructor[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = NullProtoObject(); + return Properties === undefined ? result : definePropertiesModule.f(result, Properties); +}; -function maxCompare(comparator, a, b) { - var comp = comparator(b, a); - // b is considered the new max if the comparator declares them equal, but - // they are not equal and b is in fact a nullish value. - return ( - (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || - comp > 0 - ); -} -function zipWithFactory(keyIter, zipper, iters, zipAll) { - var zipSequence = makeSequence(keyIter); - var sizes = new ArraySeq(iters).map(function (i) { return i.size; }); - zipSequence.size = zipAll ? sizes.max() : sizes.min(); - // Note: this a generic base implementation of __iterate in terms of - // __iterator which may be more generically useful in the future. - zipSequence.__iterate = function (fn, reverse) { - /* generic: - var iterator = this.__iterator(ITERATE_ENTRIES, reverse); - var step; - var iterations = 0; - while (!(step = iterator.next()).done) { - iterations++; - if (fn(step.value[1], step.value[0], this) === false) { - break; - } - } - return iterations; - */ - // indexed: - var iterator = this.__iterator(ITERATE_VALUES, reverse); - var step; - var iterations = 0; - while (!(step = iterator.next()).done) { - if (fn(step.value, iterations++, this) === false) { - break; - } - } - return iterations; - }; - zipSequence.__iteratorUncached = function (type, reverse) { - var iterators = iters.map( - function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); } - ); - var iterations = 0; - var isDone = false; - return new Iterator(function () { - var steps; - if (!isDone) { - steps = iterators.map(function (i) { return i.next(); }); - isDone = zipAll - ? steps.every(function (s) { return s.done; }) - : steps.some(function (s) { return s.done; }); - } - if (isDone) { - return iteratorDone(); - } - return iteratorValue( - type, - iterations++, - zipper.apply( - null, - steps.map(function (s) { return s.value; }) - ) - ); - }); - }; - return zipSequence; -} +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { -// #pragma Helper Functions +"use strict"; -function reify(iter, seq) { - return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq); -} +var DESCRIPTORS = __webpack_require__(6); +var call = __webpack_require__(4); +var propertyIsEnumerableModule = __webpack_require__(126); +var createPropertyDescriptor = __webpack_require__(41); +var toIndexedObject = __webpack_require__(25); +var toPropertyKey = __webpack_require__(63); +var hasOwn = __webpack_require__(13); +var IE8_DOM_DEFINE = __webpack_require__(213); -function validateEntry(entry) { - if (entry !== Object(entry)) { - throw new TypeError('Expected [K, V] tuple: ' + entry); - } -} +// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe +var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; -function collectionClass(collection) { - return isKeyed(collection) - ? KeyedCollection - : isIndexed(collection) - ? IndexedCollection - : SetCollection; -} +// `Object.getOwnPropertyDescriptor` method +// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor +exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { + O = toIndexedObject(O); + P = toPropertyKey(P); + if (IE8_DOM_DEFINE) try { + return $getOwnPropertyDescriptor(O, P); + } catch (error) { /* empty */ } + if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); +}; -function makeSequence(collection) { - return Object.create( - (isKeyed(collection) - ? KeyedSeq - : isIndexed(collection) - ? IndexedSeq - : SetSeq - ).prototype - ); -} -function cacheResultThrough() { - if (this._iter.cacheResult) { - this._iter.cacheResult(); - this.size = this._iter.size; - return this; - } - return Seq.prototype.cacheResult.call(this); -} +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { -function defaultComparator(a, b) { - if (a === undefined && b === undefined) { - return 0; - } +"use strict"; - if (a === undefined) { - return 1; - } +var uncurryThis = __webpack_require__(2); - if (b === undefined) { - return -1; - } +var toString = uncurryThis({}.toString); +var stringSlice = uncurryThis(''.slice); - return a > b ? 1 : a < b ? -1 : 0; -} +module.exports = function (it) { + return stringSlice(toString(it), 8, -1); +}; -// http://jsperf.com/copy-array-inline -function arrCopy(arr, offset) { - offset = offset || 0; - var len = Math.max(0, arr.length - offset); - var newArr = new Array(len); - for (var ii = 0; ii < len; ii++) { - // @ts-expect-error We may want to guard for undefined values with `if (arr[ii + offset] !== undefined`, but ths should not happen by design - newArr[ii] = arr[ii + offset]; - } - return newArr; -} -function invariant(condition, error) { - if (!condition) - { throw new Error(error); } -} +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { -function assertNotInfinite(size) { - invariant(size !== Infinity, 'Cannot perform this action with an infinite size.'); -} +"use strict"; -function coerceKeyPath(keyPath) { - if (isArrayLike(keyPath) && typeof keyPath !== 'string') { - return keyPath; - } - if (isOrdered(keyPath)) { - return keyPath.toArray(); - } - throw new TypeError('Invalid keyPath: expected Ordered Collection or Array: ' + keyPath); -} +// `GetIteratorDirect(obj)` abstract operation +// https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect +module.exports = function (obj) { + return { + iterator: obj, + next: obj.next, + done: false + }; +}; -var toString = Object.prototype.toString; -function isPlainObject(value) { - // The base prototype's toString deals with Argument objects and native namespaces like Math - if (!value || - typeof value !== 'object' || - toString.call(value) !== '[object Object]') { - return false; - } - var proto = Object.getPrototypeOf(value); - if (proto === null) { - return true; - } - // Iteratively going up the prototype chain is needed for cross-realm environments (differing contexts, iframes, etc) - var parentProto = proto; - var nextProto = Object.getPrototypeOf(proto); - while (nextProto !== null) { - parentProto = nextProto; - nextProto = Object.getPrototypeOf(parentProto); - } - return parentProto === proto; -} -/** - * Returns true if the value is a potentially-persistent data structure, either - * provided by Immutable.js or a plain Array or Object. - */ -function isDataStructure(value) { - return (typeof value === 'object' && - (isImmutable(value) || Array.isArray(value) || isPlainObject(value))); -} +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Converts a value to a string, adding quotes if a string was provided. - */ -function quoteString(value) { - try { - return typeof value === 'string' ? JSON.stringify(value) : String(value); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } - catch (_ignoreError) { - return JSON.stringify(value); - } -} +"use strict"; -/** - * Returns true if the key is defined in the provided collection. - * - * A functional alternative to `collection.has(key)` which will also work with - * plain Objects and Arrays as an alternative for - * `collection.hasOwnProperty(key)`. - */ -function has(collection, key) { - return isImmutable(collection) - ? // @ts-expect-error key might be a number or symbol, which is not handled be Record key type - collection.has(key) - : // @ts-expect-error key might be anything else than PropertyKey, and will return false in that case but runtime is OK - isDataStructure(collection) && hasOwnProperty.call(collection, key); -} +var path = __webpack_require__(128); +var hasOwn = __webpack_require__(13); +var wrappedWellKnownSymbolModule = __webpack_require__(252); +var defineProperty = __webpack_require__(19).f; -function get(collection, key, notSetValue) { - return isImmutable(collection) - ? collection.get(key, notSetValue) - : !has(collection, key) - ? notSetValue - : // @ts-expect-error weird "get" here, - typeof collection.get === 'function' - ? // @ts-expect-error weird "get" here, - collection.get(key) - : // @ts-expect-error key is unknown here, - collection[key]; -} +module.exports = function (NAME) { + var Symbol = path.Symbol || (path.Symbol = {}); + if (!hasOwn(Symbol, NAME)) defineProperty(Symbol, NAME, { + value: wrappedWellKnownSymbolModule.f(NAME) + }); +}; -function shallowCopy(from) { - if (Array.isArray(from)) { - return arrCopy(from); - } - var to = {}; - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - return to; -} -function remove(collection, key) { - if (!isDataStructure(collection)) { - throw new TypeError('Cannot update non-data-structure value: ' + collection); - } - if (isImmutable(collection)) { - // @ts-expect-error weird "remove" here, - if (!collection.remove) { - throw new TypeError('Cannot update immutable value without .remove() method: ' + collection); - } - // @ts-expect-error weird "remove" here, - return collection.remove(key); - } - // @ts-expect-error assert that key is a string, a number or a symbol here - if (!hasOwnProperty.call(collection, key)) { - return collection; - } - var collectionCopy = shallowCopy(collection); - if (Array.isArray(collectionCopy)) { - // @ts-expect-error assert that key is a number here - collectionCopy.splice(key, 1); - } - else { - // @ts-expect-error assert that key is a string, a number or a symbol here - delete collectionCopy[key]; - } - return collectionCopy; -} +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { -function set(collection, key, value) { - if (!isDataStructure(collection)) { - throw new TypeError('Cannot update non-data-structure value: ' + collection); - } - if (isImmutable(collection)) { - // @ts-expect-error weird "set" here, - if (!collection.set) { - throw new TypeError('Cannot update immutable value without .set() method: ' + collection); - } - // @ts-expect-error weird "set" here, - return collection.set(key, value); - } - // @ts-expect-error mix of key and string here. Probably need a more fine type here - if (hasOwnProperty.call(collection, key) && value === collection[key]) { - return collection; - } - var collectionCopy = shallowCopy(collection); - // @ts-expect-error mix of key and string here. Probably need a more fine type here - collectionCopy[key] = value; - return collectionCopy; -} +"use strict"; -function updateIn$1(collection, keyPath, notSetValue, updater) { - if (!updater) { - // handle the fact that `notSetValue` is optional here, in that case `updater` is the updater function - // @ts-expect-error updater is a function here - updater = notSetValue; - notSetValue = undefined; - } - var updatedValue = updateInDeeply(isImmutable(collection), - // @ts-expect-error type issues with Record and mixed types - collection, coerceKeyPath(keyPath), 0, notSetValue, updater); - // @ts-expect-error mixed return type - return updatedValue === NOT_SET ? notSetValue : updatedValue; -} -function updateInDeeply(inImmutable, existing, keyPath, i, notSetValue, updater) { - var wasNotSet = existing === NOT_SET; - if (i === keyPath.length) { - var existingValue = wasNotSet ? notSetValue : existing; - // @ts-expect-error mixed type with optional value - var newValue = updater(existingValue); - // @ts-expect-error mixed type - return newValue === existingValue ? existing : newValue; - } - if (!wasNotSet && !isDataStructure(existing)) { - throw new TypeError('Cannot update within non-data-structure value in path [' + - Array.from(keyPath).slice(0, i).map(quoteString) + - ']: ' + - existing); - } - var key = keyPath[i]; - var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET); - var nextUpdated = updateInDeeply(nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting), - // @ts-expect-error mixed type - nextExisting, keyPath, i + 1, notSetValue, updater); - return nextUpdated === nextExisting - ? existing - : nextUpdated === NOT_SET - ? remove(existing, key) - : set(wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated); -} +var hasOwn = __webpack_require__(13); +var isCallable = __webpack_require__(14); +var toObject = __webpack_require__(15); +var sharedKey = __webpack_require__(131); +var CORRECT_PROTOTYPE_GETTER = __webpack_require__(151); -/** - * Returns a copy of the collection with the value at the key path set to the - * provided value. - * - * A functional alternative to `collection.setIn(keypath)` which will also - * work with plain Objects and Arrays. - */ -function setIn$1(collection, keyPath, value) { - return updateIn$1(collection, keyPath, NOT_SET, function () { return value; }); -} +var IE_PROTO = sharedKey('IE_PROTO'); +var $Object = Object; +var ObjectPrototype = $Object.prototype; -function setIn(keyPath, v) { - return setIn$1(this, keyPath, v); -} +// `Object.getPrototypeOf` method +// https://tc39.es/ecma262/#sec-object.getprototypeof +// eslint-disable-next-line es/no-object-getprototypeof -- safe +module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) { + var object = toObject(O); + if (hasOwn(object, IE_PROTO)) return object[IE_PROTO]; + var constructor = object.constructor; + if (isCallable(constructor) && object instanceof constructor) { + return constructor.prototype; + } return object instanceof $Object ? ObjectPrototype : null; +}; -/** - * Returns a copy of the collection with the value at the key path removed. - * - * A functional alternative to `collection.removeIn(keypath)` which will also - * work with plain Objects and Arrays. - */ -function removeIn(collection, keyPath) { - return updateIn$1(collection, keyPath, function () { return NOT_SET; }); -} -function deleteIn(keyPath) { - return removeIn(this, keyPath); -} +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { -function update$1(collection, key, notSetValue, updater) { - return updateIn$1( - // @ts-expect-error Index signature for type string is missing in type V[] - collection, [key], notSetValue, updater); -} +"use strict"; -function update(key, notSetValue, updater) { - return arguments.length === 1 - ? key(this) - : update$1(this, key, notSetValue, updater); -} +var uncurryThis = __webpack_require__(2); -function updateIn(keyPath, notSetValue, updater) { - return updateIn$1(this, keyPath, notSetValue, updater); -} +module.exports = uncurryThis({}.isPrototypeOf); -function merge$1() { - var iters = [], len = arguments.length; - while ( len-- ) iters[ len ] = arguments[ len ]; - return mergeIntoKeyedWith(this, iters); -} +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { -function mergeWith$1(merger) { - var iters = [], len = arguments.length - 1; - while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; +"use strict"; - if (typeof merger !== 'function') { - throw new TypeError('Invalid merger function: ' + merger); - } - return mergeIntoKeyedWith(this, iters, merger); -} +var wellKnownSymbol = __webpack_require__(7); +var create = __webpack_require__(30); +var defineProperty = __webpack_require__(19).f; -function mergeIntoKeyedWith(collection, collections, merger) { - var iters = []; - for (var ii = 0; ii < collections.length; ii++) { - var collection$1 = KeyedCollection(collections[ii]); - if (collection$1.size !== 0) { - iters.push(collection$1); - } - } - if (iters.length === 0) { - return collection; - } - if ( - collection.toSeq().size === 0 && - !collection.__ownerID && - iters.length === 1 - ) { - return isRecord(collection) - ? collection // Record is empty and will not be updated: return the same instance - : collection.constructor(iters[0]); - } - return collection.withMutations(function (collection) { - var mergeIntoCollection = merger - ? function (value, key) { - update$1(collection, key, NOT_SET, function (oldVal) { return oldVal === NOT_SET ? value : merger(oldVal, value, key); } - ); - } - : function (value, key) { - collection.set(key, value); - }; - for (var ii = 0; ii < iters.length; ii++) { - iters[ii].forEach(mergeIntoCollection); - } +var UNSCOPABLES = wellKnownSymbol('unscopables'); +var ArrayPrototype = Array.prototype; + +// Array.prototype[@@unscopables] +// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables +if (ArrayPrototype[UNSCOPABLES] === undefined) { + defineProperty(ArrayPrototype, UNSCOPABLES, { + configurable: true, + value: create(null) }); } -function merge(collection) { - var sources = [], len = arguments.length - 1; - while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; +// add a key to Array.prototype[@@unscopables] +module.exports = function (key) { + ArrayPrototype[UNSCOPABLES][key] = true; +}; - return mergeWithSources(collection, sources); -} -function mergeWith(merger, collection) { - var sources = [], len = arguments.length - 2; - while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; - - return mergeWithSources(collection, sources, merger); -} - -function mergeDeep$1(collection) { - var sources = [], len = arguments.length - 1; - while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; - - return mergeDeepWithSources(collection, sources); -} - -function mergeDeepWith$1(merger, collection) { - var sources = [], len = arguments.length - 2; - while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { - return mergeDeepWithSources(collection, sources, merger); -} +"use strict"; -function mergeDeepWithSources(collection, sources, merger) { - return mergeWithSources(collection, sources, deepMergerWith(merger)); -} +var defineProperty = __webpack_require__(19).f; +var hasOwn = __webpack_require__(13); +var wellKnownSymbol = __webpack_require__(7); -function mergeWithSources(collection, sources, merger) { - if (!isDataStructure(collection)) { - throw new TypeError( - 'Cannot merge into non-data-structure value: ' + collection - ); - } - if (isImmutable(collection)) { - return typeof merger === 'function' && collection.mergeWith - ? collection.mergeWith.apply(collection, [ merger ].concat( sources )) - : collection.merge - ? collection.merge.apply(collection, sources) - : collection.concat.apply(collection, sources); - } - var isArray = Array.isArray(collection); - var merged = collection; - var Collection = isArray ? IndexedCollection : KeyedCollection; - var mergeItem = isArray - ? function (value) { - // Copy on write - if (merged === collection) { - merged = shallowCopy(merged); - } - merged.push(value); - } - : function (value, key) { - var hasVal = hasOwnProperty.call(merged, key); - var nextVal = - hasVal && merger ? merger(merged[key], value, key) : value; - if (!hasVal || nextVal !== merged[key]) { - // Copy on write - if (merged === collection) { - merged = shallowCopy(merged); - } - merged[key] = nextVal; - } - }; - for (var i = 0; i < sources.length; i++) { - Collection(sources[i]).forEach(mergeItem); - } - return merged; -} +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); -function deepMergerWith(merger) { - function deepMerger(oldValue, newValue, key) { - return isDataStructure(oldValue) && - isDataStructure(newValue) && - areMergeable(oldValue, newValue) - ? mergeWithSources(oldValue, [newValue], deepMerger) - : merger - ? merger(oldValue, newValue, key) - : newValue; +module.exports = function (target, TAG, STATIC) { + if (target && !STATIC) target = target.prototype; + if (target && !hasOwn(target, TO_STRING_TAG)) { + defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG }); } - return deepMerger; -} +}; -/** - * It's unclear what the desired behavior is for merging two collections that - * fall into separate categories between keyed, indexed, or set-like, so we only - * consider them mergeable if they fall into the same category. - */ -function areMergeable(oldDataStructure, newDataStructure) { - var oldSeq = Seq(oldDataStructure); - var newSeq = Seq(newDataStructure); - // This logic assumes that a sequence can only fall into one of the three - // categories mentioned above (since there's no `isSetLike()` method). - return ( - isIndexed(oldSeq) === isIndexed(newSeq) && - isKeyed(oldSeq) === isKeyed(newSeq) - ); -} -function mergeDeep() { - var iters = [], len = arguments.length; - while ( len-- ) iters[ len ] = arguments[ len ]; +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { - return mergeDeepWithSources(this, iters); -} +"use strict"; -function mergeDeepWith(merger) { - var iters = [], len = arguments.length - 1; - while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; +var isPrototypeOf = __webpack_require__(36); - return mergeDeepWithSources(this, iters, merger); -} +var $TypeError = TypeError; -function mergeIn(keyPath) { - var iters = [], len = arguments.length - 1; - while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; +module.exports = function (it, Prototype) { + if (isPrototypeOf(Prototype, it)) return it; + throw new $TypeError('Incorrect invocation'); +}; - return updateIn$1(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); }); -} -function mergeDeepIn(keyPath) { - var iters = [], len = arguments.length - 1; - while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { - return updateIn$1(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); } - ); -} +"use strict"; -function withMutations(fn) { - var mutable = this.asMutable(); - fn(mutable); - return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; -} +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toString = __webpack_require__(9); -function asMutable() { - return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); -} +var quot = /"/g; +var replace = uncurryThis(''.replace); -function asImmutable() { - return this.__ensureOwner(); -} +// `CreateHTML` abstract operation +// https://tc39.es/ecma262/#sec-createhtml +module.exports = function (string, tag, attribute, value) { + var S = toString(requireObjectCoercible(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + replace(toString(value), quot, '"') + '"'; + return p1 + '>' + S + ''; +}; -function wasAltered() { - return this.__altered; -} -var Map = /*@__PURE__*/(function (KeyedCollection) { - function Map(value) { - // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptyMap() - : isMap(value) && !isOrdered(value) - ? value - : emptyMap().withMutations(function (map) { - var iter = KeyedCollection(value); - assertNotInfinite(iter.size); - iter.forEach(function (v, k) { return map.set(k, v); }); - }); - } +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { - if ( KeyedCollection ) Map.__proto__ = KeyedCollection; - Map.prototype = Object.create( KeyedCollection && KeyedCollection.prototype ); - Map.prototype.constructor = Map; +"use strict"; - Map.prototype.toString = function toString () { - return this.__toString('Map {', '}'); +module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value }; +}; - // @pragma Access - Map.prototype.get = function get (k, notSetValue) { - return this._root - ? this._root.get(0, undefined, k, notSetValue) - : notSetValue; - }; +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { - // @pragma Modification +"use strict"; - Map.prototype.set = function set (k, v) { - return updateMap(this, k, v); - }; +var NATIVE_BIND = __webpack_require__(99); - Map.prototype.remove = function remove (k) { - return updateMap(this, k, NOT_SET); - }; +var FunctionPrototype = Function.prototype; +var apply = FunctionPrototype.apply; +var call = FunctionPrototype.call; - Map.prototype.deleteAll = function deleteAll (keys) { - var collection = Collection(keys); +// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe +module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () { + return call.apply(apply, arguments); +}); - if (collection.size === 0) { - return this; - } - return this.withMutations(function (map) { - collection.forEach(function (key) { return map.remove(key); }); - }); - }; +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { - Map.prototype.clear = function clear () { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._root = null; - this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyMap(); - }; +"use strict"; - // @pragma Composition +var uncurryThis = __webpack_require__(67); +var aCallable = __webpack_require__(10); +var NATIVE_BIND = __webpack_require__(99); - Map.prototype.sort = function sort (comparator) { - // Late binding - return OrderedMap(sortFactory(this, comparator)); - }; +var bind = uncurryThis(uncurryThis.bind); - Map.prototype.sortBy = function sortBy (mapper, comparator) { - // Late binding - return OrderedMap(sortFactory(this, comparator, mapper)); +// optional / simple context binding +module.exports = function (fn, that) { + aCallable(fn); + return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) { + return fn.apply(that, arguments); }; +}; - Map.prototype.map = function map (mapper, context) { - var this$1$1 = this; - - return this.withMutations(function (map) { - map.forEach(function (value, key) { - map.set(key, mapper.call(context, value, key, this$1$1)); - }); - }); - }; - // @pragma Mutability +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { - Map.prototype.__iterator = function __iterator (type, reverse) { - return new MapIterator(this, type, reverse); - }; +"use strict"; - Map.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; +var fails = __webpack_require__(1); - var iterations = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - this._root && - this._root.iterate(function (entry) { - iterations++; - return fn(entry[1], entry[0], this$1$1); - }, reverse); - return iterations; - }; +// check the existence of a method, lowercase +// of a tag and escaping quotes in arguments +module.exports = function (METHOD_NAME) { + return fails(function () { + var test = ''[METHOD_NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }); +}; - Map.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyMap(); - } - this.__ownerID = ownerID; - this.__altered = false; - return this; - } - return makeMap(this.size, this._root, ownerID, this.__hash); - }; - return Map; -}(KeyedCollection)); +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { -Map.isMap = isMap; +"use strict"; -var MapPrototype = Map.prototype; -MapPrototype[IS_MAP_SYMBOL] = true; -MapPrototype[DELETE] = MapPrototype.remove; -MapPrototype.removeAll = MapPrototype.deleteAll; -MapPrototype.setIn = setIn; -MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn; -MapPrototype.update = update; -MapPrototype.updateIn = updateIn; -MapPrototype.merge = MapPrototype.concat = merge$1; -MapPrototype.mergeWith = mergeWith$1; -MapPrototype.mergeDeep = mergeDeep; -MapPrototype.mergeDeepWith = mergeDeepWith; -MapPrototype.mergeIn = mergeIn; -MapPrototype.mergeDeepIn = mergeDeepIn; -MapPrototype.withMutations = withMutations; -MapPrototype.wasAltered = wasAltered; -MapPrototype.asImmutable = asImmutable; -MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable; -MapPrototype['@@transducer/step'] = function (result, arr) { - return result.set(arr[0], arr[1]); -}; -MapPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; +var toIntegerOrInfinity = __webpack_require__(22); -// #pragma Trie Nodes +var min = Math.min; -var ArrayMapNode = function ArrayMapNode(ownerID, entries) { - this.ownerID = ownerID; - this.entries = entries; +// `ToLength` abstract operation +// https://tc39.es/ecma262/#sec-tolength +module.exports = function (argument) { + var len = toIntegerOrInfinity(argument); + return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; -ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { - var entries = this.entries; - for (var ii = 0, len = entries.length; ii < len; ii++) { - if (is(key, entries[ii][0])) { - return entries[ii][1]; - } - } - return notSetValue; -}; -ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - var removed = value === NOT_SET; +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { - var entries = this.entries; - var idx = 0; - var len = entries.length; - for (; idx < len; idx++) { - if (is(key, entries[idx][0])) { - break; - } - } - var exists = idx < len; +"use strict"; - if (exists ? entries[idx][1] === value : removed) { - return this; - } +var uncurryThis = __webpack_require__(2); - SetRef(didAlter); - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - (removed || !exists) && SetRef(didChangeSize); +module.exports = uncurryThis([].slice); - if (removed && entries.length === 1) { - return; // undefined - } - if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { - return createNodes(ownerID, entries, key, value); - } +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { - var isEditable = ownerID && ownerID === this.ownerID; - var newEntries = isEditable ? entries : arrCopy(entries); +"use strict"; - if (exists) { - if (removed) { - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - idx === len - 1 - ? newEntries.pop() - : (newEntries[idx] = newEntries.pop()); - } else { - newEntries[idx] = [key, value]; - } - } else { - newEntries.push([key, value]); - } +var TO_STRING_TAG_SUPPORT = __webpack_require__(178); +var isCallable = __webpack_require__(14); +var classofRaw = __webpack_require__(32); +var wellKnownSymbol = __webpack_require__(7); - if (isEditable) { - this.entries = newEntries; - return this; - } +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var $Object = Object; - return new ArrayMapNode(ownerID, newEntries); -}; +// ES3 wrong here +var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments'; -var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) { - this.ownerID = ownerID; - this.bitmap = bitmap; - this.nodes = nodes; +// fallback for IE11 Script Access Denied error +var tryGet = function (it, key) { + try { + return it[key]; + } catch (error) { /* empty */ } }; -BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK); - var bitmap = this.bitmap; - return (bitmap & bit) === 0 - ? notSetValue - : this.nodes[popCount(bitmap & (bit - 1))].get( - shift + SHIFT, - keyHash, - key, - notSetValue - ); +// getting tag from ES6+ `Object.prototype.toString` +module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { + var O, tag, result; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag + // builtinTag case + : CORRECT_ARGUMENTS ? classofRaw(O) + // ES3 arguments fallback + : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; }; -BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var bit = 1 << keyHashFrag; - var bitmap = this.bitmap; - var exists = (bitmap & bit) !== 0; - - if (!exists && value === NOT_SET) { - return this; - } - var idx = popCount(bitmap & (bit - 1)); - var nodes = this.nodes; - var node = exists ? nodes[idx] : undefined; - var newNode = updateNode( - node, - ownerID, - shift + SHIFT, - keyHash, - key, - value, - didChangeSize, - didAlter - ); +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { - if (newNode === node) { - return this; - } +"use strict"; - if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { - return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); - } +var $TypeError = TypeError; - if ( - exists && - !newNode && - nodes.length === 2 && - isLeafNode(nodes[idx ^ 1]) - ) { - return nodes[idx ^ 1]; - } +module.exports = function (passed, required) { + if (passed < required) throw new $TypeError('Not enough arguments'); + return passed; +}; - if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { - return newNode; - } - var isEditable = ownerID && ownerID === this.ownerID; - var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit; - var newNodes = exists - ? newNode - ? setAt(nodes, idx, newNode, isEditable) - : spliceOut(nodes, idx, isEditable) - : spliceIn(nodes, idx, newNode, isEditable); +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { - if (isEditable) { - this.bitmap = newBitmap; - this.nodes = newNodes; - return this; - } +"use strict"; - return new BitmapIndexedNode(ownerID, newBitmap, newNodes); -}; +/* eslint-disable no-proto -- safe */ +var uncurryThisAccessor = __webpack_require__(121); +var isObject = __webpack_require__(8); +var requireObjectCoercible = __webpack_require__(20); +var aPossiblePrototype = __webpack_require__(181); -var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) { - this.ownerID = ownerID; - this.count = count; - this.nodes = nodes; -}; +// `Object.setPrototypeOf` method +// https://tc39.es/ecma262/#sec-object.setprototypeof +// Works with __proto__ only. Old v8 can't work with null proto objects. +// eslint-disable-next-line es/no-object-setprototypeof -- safe +module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { + var CORRECT_SETTER = false; + var test = {}; + var setter; + try { + setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); + setter(test, []); + CORRECT_SETTER = test instanceof Array; + } catch (error) { /* empty */ } + return function setPrototypeOf(O, proto) { + requireObjectCoercible(O); + aPossiblePrototype(proto); + if (!isObject(O)) return O; + if (CORRECT_SETTER) setter(O, proto); + else O.__proto__ = proto; + return O; + }; +}() : undefined); -HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var node = this.nodes[idx]; - return node - ? node.get(shift + SHIFT, keyHash, key, notSetValue) - : notSetValue; + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var uncurryThis = __webpack_require__(2); + +// eslint-disable-next-line es/no-set -- safe +var SetPrototype = Set.prototype; + +module.exports = { + // eslint-disable-next-line es/no-set -- safe + Set: Set, + add: uncurryThis(SetPrototype.add), + has: uncurryThis(SetPrototype.has), + remove: uncurryThis(SetPrototype['delete']), + proto: SetPrototype }; -HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var removed = value === NOT_SET; - var nodes = this.nodes; - var node = nodes[idx]; - if (removed && !node) { - return this; - } +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { - var newNode = updateNode( - node, - ownerID, - shift + SHIFT, - keyHash, - key, - value, - didChangeSize, - didAlter - ); - if (newNode === node) { - return this; - } +"use strict"; - var newCount = this.count; - if (!node) { - newCount++; - } else if (!newNode) { - newCount--; - if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { - return packNodes(ownerID, nodes, newCount, idx); - } - } +var globalThis = __webpack_require__(3); - var isEditable = ownerID && ownerID === this.ownerID; - var newNodes = setAt(nodes, idx, newNode, isEditable); +var navigator = globalThis.navigator; +var userAgent = navigator && navigator.userAgent; - if (isEditable) { - this.count = newCount; - this.nodes = newNodes; - return this; - } +module.exports = userAgent ? String(userAgent) : ''; - return new HashArrayMapNode(ownerID, newCount, newNodes); -}; -var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entries = entries; -}; +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { -HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) { - var entries = this.entries; - for (var ii = 0, len = entries.length; ii < len; ii++) { - if (is(key, entries[ii][0])) { - return entries[ii][1]; - } - } - return notSetValue; -}; +"use strict"; -HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } +var globalThis = __webpack_require__(3); +var userAgent = __webpack_require__(51); - var removed = value === NOT_SET; +var process = globalThis.process; +var Deno = globalThis.Deno; +var versions = process && process.versions || Deno && Deno.version; +var v8 = versions && versions.v8; +var match, version; - if (keyHash !== this.keyHash) { - if (removed) { - return this; - } - SetRef(didAlter); - SetRef(didChangeSize); - return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); - } +if (v8) { + match = v8.split('.'); + // in old Chrome, versions of V8 isn't V8 = Chrome / 10 + // but their correct versions are not interesting for us + version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); +} - var entries = this.entries; - var idx = 0; - var len = entries.length; - for (; idx < len; idx++) { - if (is(key, entries[idx][0])) { - break; - } +// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0` +// so check `userAgent` even if `.v8` exists, but 0 +if (!version && userAgent) { + match = userAgent.match(/Edge\/(\d+)/); + if (!match || match[1] >= 74) { + match = userAgent.match(/Chrome\/(\d+)/); + if (match) version = +match[1]; } - var exists = idx < len; +} - if (exists ? entries[idx][1] === value : removed) { - return this; - } +module.exports = version; - SetRef(didAlter); - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - (removed || !exists) && SetRef(didChangeSize); - if (removed && len === 2) { - return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); - } +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { - var isEditable = ownerID && ownerID === this.ownerID; - var newEntries = isEditable ? entries : arrCopy(entries); +"use strict"; - if (exists) { - if (removed) { - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - idx === len - 1 - ? newEntries.pop() - : (newEntries[idx] = newEntries.pop()); - } else { - newEntries[idx] = [key, value]; - } - } else { - newEntries.push([key, value]); - } +var globalThis = __webpack_require__(3); - if (isEditable) { - this.entries = newEntries; - return this; +// https://github.com/tc39/ecma262/pull/3467 +module.exports = function (METHOD_NAME, ExpectedError) { + var Iterator = globalThis.Iterator; + var IteratorPrototype = Iterator && Iterator.prototype; + var method = IteratorPrototype && IteratorPrototype[METHOD_NAME]; + + var CLOSED = false; + + if (method) try { + method.call({ + next: function () { return { done: true }; }, + 'return': function () { CLOSED = true; } + }, -1); + } catch (error) { + // https://bugs.webkit.org/show_bug.cgi?id=291195 + if (!(error instanceof ExpectedError)) CLOSED = false; } - return new HashCollisionNode(ownerID, this.keyHash, newEntries); + if (!CLOSED) return method; }; -var ValueNode = function ValueNode(ownerID, keyHash, entry) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entry = entry; -}; -ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) { - return is(key, this.entry[0]) ? this.entry[1] : notSetValue; +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var fails = __webpack_require__(1); + +module.exports = function (METHOD_NAME, argument) { + var method = [][METHOD_NAME]; + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call -- required for testing + method.call(null, argument || function () { return 1; }, 1); + }); }; -ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - var removed = value === NOT_SET; - var keyMatch = is(key, this.entry[0]); - if (keyMatch ? value === this.entry[1] : removed) { - return this; - } - SetRef(didAlter); +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { - if (removed) { - SetRef(didChangeSize); - return; // undefined - } +"use strict"; - if (keyMatch) { - if (ownerID && ownerID === this.ownerID) { - this.entry[1] = value; - return this; - } - return new ValueNode(ownerID, this.keyHash, [key, value]); - } +var DESCRIPTORS = __webpack_require__(6); +var definePropertyModule = __webpack_require__(19); +var createPropertyDescriptor = __webpack_require__(41); - SetRef(didChangeSize); - return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); +module.exports = function (object, key, value) { + if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value)); + else object[key] = value; }; -// #pragma Iterators -ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = - function (fn, reverse) { - var entries = this.entries; - for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { - if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { - return false; - } - } - }; +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { -BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = - function (fn, reverse) { - var nodes = this.nodes; - for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { - var node = nodes[reverse ? maxIndex - ii : ii]; - if (node && node.iterate(fn, reverse) === false) { - return false; - } - } - }; +"use strict"; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ValueNode.prototype.iterate = function (fn, reverse) { - return fn(this.entry); +var defineBuiltIn = __webpack_require__(17); + +module.exports = function (target, src, options) { + for (var key in src) defineBuiltIn(target, key, src[key], options); + return target; }; -var MapIterator = /*@__PURE__*/(function (Iterator) { - function MapIterator(map, type, reverse) { - this._type = type; - this._reverse = reverse; - this._stack = map._root && mapIteratorFrame(map._root); - } - if ( Iterator ) MapIterator.__proto__ = Iterator; - MapIterator.prototype = Object.create( Iterator && Iterator.prototype ); - MapIterator.prototype.constructor = MapIterator; +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { - MapIterator.prototype.next = function next () { - var type = this._type; - var stack = this._stack; - while (stack) { - var node = stack.node; - var index = stack.index++; - var maxIndex = (void 0); - if (node.entry) { - if (index === 0) { - return mapIteratorValue(type, node.entry); - } - } else if (node.entries) { - maxIndex = node.entries.length - 1; - if (index <= maxIndex) { - return mapIteratorValue( - type, - node.entries[this._reverse ? maxIndex - index : index] - ); - } - } else { - maxIndex = node.nodes.length - 1; - if (index <= maxIndex) { - var subNode = node.nodes[this._reverse ? maxIndex - index : index]; - if (subNode) { - if (subNode.entry) { - return mapIteratorValue(type, subNode.entry); - } - stack = this._stack = mapIteratorFrame(subNode, stack); - } - continue; - } - } - stack = this._stack = this._stack.__prev; - } - return iteratorDone(); - }; +"use strict"; - return MapIterator; -}(Iterator)); +// we can't use just `it == null` since of `document.all` special case +// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec +module.exports = function (it) { + return it === null || it === undefined; +}; -function mapIteratorValue(type, entry) { - return iteratorValue(type, entry[0], entry[1]); -} -function mapIteratorFrame(node, prev) { - return { - node: node, - index: 0, - __prev: prev, - }; -} +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { -function makeMap(size, root, ownerID, hash) { - var map = Object.create(MapPrototype); - map.size = size; - map._root = root; - map.__ownerID = ownerID; - map.__hash = hash; - map.__altered = false; - return map; -} +"use strict"; -var EMPTY_MAP; -function emptyMap() { - return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); -} +var aCallable = __webpack_require__(10); -function updateMap(map, k, v) { - var newRoot; - var newSize; - if (!map._root) { - if (v === NOT_SET) { - return map; - } - newSize = 1; - newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); - } else { - var didChangeSize = MakeRef(); - var didAlter = MakeRef(); - newRoot = updateNode( - map._root, - map.__ownerID, - 0, - undefined, - k, - v, - didChangeSize, - didAlter - ); - if (!didAlter.value) { - return map; - } - newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0); - } - if (map.__ownerID) { - map.size = newSize; - map._root = newRoot; - map.__hash = undefined; - map.__altered = true; - return map; - } - return newRoot ? makeMap(newSize, newRoot) : emptyMap(); -} +var $TypeError = TypeError; -function updateNode( - node, - ownerID, - shift, - keyHash, - key, - value, - didChangeSize, - didAlter -) { - if (!node) { - if (value === NOT_SET) { - return node; - } - SetRef(didAlter); - SetRef(didChangeSize); - return new ValueNode(ownerID, keyHash, [key, value]); - } - return node.update( - ownerID, - shift, - keyHash, - key, - value, - didChangeSize, - didAlter - ); -} +var PromiseCapability = function (C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aCallable(resolve); + this.reject = aCallable(reject); +}; -function isLeafNode(node) { - return ( - node.constructor === ValueNode || node.constructor === HashCollisionNode - ); -} +// `NewPromiseCapability` abstract operation +// https://tc39.es/ecma262/#sec-newpromisecapability +module.exports.f = function (C) { + return new PromiseCapability(C); +}; -function mergeIntoNode(node, ownerID, shift, keyHash, entry) { - if (node.keyHash === keyHash) { - return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); - } - var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; - var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { - var newNode; - var nodes = - idx1 === idx2 - ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] - : ((newNode = new ValueNode(ownerID, keyHash, entry)), - idx1 < idx2 ? [node, newNode] : [newNode, node]); +"use strict"; - return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); -} +var toIntegerOrInfinity = __webpack_require__(22); -function createNodes(ownerID, entries, key, value) { - if (!ownerID) { - ownerID = new OwnerID(); - } - var node = new ValueNode(ownerID, hash(key), [key, value]); - for (var ii = 0; ii < entries.length; ii++) { - var entry = entries[ii]; - node = node.update(ownerID, 0, undefined, entry[0], entry[1]); - } - return node; -} +var max = Math.max; +var min = Math.min; -function packNodes(ownerID, nodes, count, excluding) { - var bitmap = 0; - var packedII = 0; - var packedNodes = new Array(count); - for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { - var node = nodes[ii]; - if (node !== undefined && ii !== excluding) { - bitmap |= bit; - packedNodes[packedII++] = node; - } - } - return new BitmapIndexedNode(ownerID, bitmap, packedNodes); -} +// Helper for a popular repeating case of the spec: +// Let integer be ? ToInteger(index). +// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). +module.exports = function (index, length) { + var integer = toIntegerOrInfinity(index); + return integer < 0 ? max(integer + length, 0) : min(integer, length); +}; -function expandNodes(ownerID, nodes, bitmap, including, node) { - var count = 0; - var expandedNodes = new Array(SIZE); - for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { - expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; - } - expandedNodes[including] = node; - return new HashArrayMapNode(ownerID, count + 1, expandedNodes); -} -function popCount(x) { - x -= (x >> 1) & 0x55555555; - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - x = (x + (x >> 4)) & 0x0f0f0f0f; - x += x >> 8; - x += x >> 16; - return x & 0x7f; -} - -function setAt(array, idx, val, canEdit) { - var newArray = canEdit ? array : arrCopy(array); - newArray[idx] = val; - return newArray; -} - -function spliceIn(array, idx, val, canEdit) { - var newLen = array.length + 1; - if (canEdit && idx + 1 === newLen) { - array[idx] = val; - return array; - } - var newArray = new Array(newLen); - var after = 0; - for (var ii = 0; ii < newLen; ii++) { - if (ii === idx) { - newArray[ii] = val; - after = -1; - } else { - newArray[ii] = array[ii + after]; - } - } - return newArray; -} - -function spliceOut(array, idx, canEdit) { - var newLen = array.length - 1; - if (canEdit && idx === newLen) { - array.pop(); - return array; - } - var newArray = new Array(newLen); - var after = 0; - for (var ii = 0; ii < newLen; ii++) { - if (ii === idx) { - after = 1; - } - newArray[ii] = array[ii + after]; - } - return newArray; -} - -var MAX_ARRAY_MAP_SIZE = SIZE / 4; -var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; -var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; - -var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@'; -/** - * True if `maybeList` is a List. - */ -function isList(maybeList) { - return Boolean(maybeList && - // @ts-expect-error: maybeList is typed as `{}`, need to change in 6.0 to `maybeList && typeof maybeList === 'object' && IS_LIST_SYMBOL in maybeList` - maybeList[IS_LIST_SYMBOL]); -} - -var List = /*@__PURE__*/(function (IndexedCollection) { - function List(value) { - var empty = emptyList(); - if (value === undefined || value === null) { - // eslint-disable-next-line no-constructor-return - return empty; - } - if (isList(value)) { - // eslint-disable-next-line no-constructor-return - return value; - } - var iter = IndexedCollection(value); - var size = iter.size; - if (size === 0) { - // eslint-disable-next-line no-constructor-return - return empty; - } - assertNotInfinite(size); - if (size > 0 && size < SIZE) { - // eslint-disable-next-line no-constructor-return - return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); - } - // eslint-disable-next-line no-constructor-return - return empty.withMutations(function (list) { - list.setSize(size); - iter.forEach(function (v, i) { return list.set(i, v); }); - }); - } - - if ( IndexedCollection ) List.__proto__ = IndexedCollection; - List.prototype = Object.create( IndexedCollection && IndexedCollection.prototype ); - List.prototype.constructor = List; +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { - List.of = function of (/*...values*/) { - return this(arguments); - }; +"use strict"; - List.prototype.toString = function toString () { - return this.__toString('List [', ']'); - }; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var call = __webpack_require__(4); +var DESCRIPTORS = __webpack_require__(6); +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(179); +var ArrayBufferViewCore = __webpack_require__(12); +var ArrayBufferModule = __webpack_require__(111); +var anInstance = __webpack_require__(39); +var createPropertyDescriptor = __webpack_require__(41); +var createNonEnumerableProperty = __webpack_require__(27); +var isIntegralNumber = __webpack_require__(159); +var toLength = __webpack_require__(45); +var toIndex = __webpack_require__(139); +var toOffset = __webpack_require__(247); +var toUint8Clamped = __webpack_require__(308); +var toPropertyKey = __webpack_require__(63); +var hasOwn = __webpack_require__(13); +var classof = __webpack_require__(47); +var isObject = __webpack_require__(8); +var isSymbol = __webpack_require__(73); +var create = __webpack_require__(30); +var isPrototypeOf = __webpack_require__(36); +var setPrototypeOf = __webpack_require__(49); +var getOwnPropertyNames = __webpack_require__(75).f; +var typedArrayFrom = __webpack_require__(248); +var forEach = __webpack_require__(26).forEach; +var setSpecies = __webpack_require__(91); +var defineBuiltInAccessor = __webpack_require__(23); +var definePropertyModule = __webpack_require__(19); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var arrayFromConstructorAndList = __webpack_require__(112); +var InternalStateModule = __webpack_require__(21); +var inheritIfRequired = __webpack_require__(70); - // @pragma Access +var getInternalState = InternalStateModule.get; +var setInternalState = InternalStateModule.set; +var enforceInternalState = InternalStateModule.enforce; +var nativeDefineProperty = definePropertyModule.f; +var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; +var RangeError = globalThis.RangeError; +var ArrayBuffer = ArrayBufferModule.ArrayBuffer; +var ArrayBufferPrototype = ArrayBuffer.prototype; +var DataView = ArrayBufferModule.DataView; +var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; +var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG; +var TypedArray = ArrayBufferViewCore.TypedArray; +var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype; +var isTypedArray = ArrayBufferViewCore.isTypedArray; +var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; +var WRONG_LENGTH = 'Wrong length'; - List.prototype.get = function get (index, notSetValue) { - index = wrapIndex(this, index); - if (index >= 0 && index < this.size) { - index += this._origin; - var node = listNodeFor(this, index); - return node && node.array[index & MASK]; +var addGetter = function (it, key) { + defineBuiltInAccessor(it, key, { + configurable: true, + get: function () { + return getInternalState(this)[key]; } - return notSetValue; - }; + }); +}; - // @pragma Modification +var isArrayBuffer = function (it) { + var klass; + return isPrototypeOf(ArrayBufferPrototype, it) || (klass = classof(it)) === 'ArrayBuffer' || klass === 'SharedArrayBuffer'; +}; - List.prototype.set = function set (index, value) { - return updateList(this, index, value); - }; +var isTypedArrayIndex = function (target, key) { + return isTypedArray(target) + && !isSymbol(key) + && key in target + && isIntegralNumber(+key) + && key >= 0; +}; - List.prototype.remove = function remove (index) { - return !this.has(index) - ? this - : index === 0 - ? this.shift() - : index === this.size - 1 - ? this.pop() - : this.splice(index, 1); - }; +var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { + key = toPropertyKey(key); + return isTypedArrayIndex(target, key) + ? createPropertyDescriptor(2, target[key]) + : nativeGetOwnPropertyDescriptor(target, key); +}; - List.prototype.insert = function insert (index, value) { - return this.splice(index, 0, value); - }; +var wrappedDefineProperty = function defineProperty(target, key, descriptor) { + key = toPropertyKey(key); + if (isTypedArrayIndex(target, key) + && isObject(descriptor) + && hasOwn(descriptor, 'value') + && !hasOwn(descriptor, 'get') + && !hasOwn(descriptor, 'set') + // TODO: add validation descriptor w/o calling accessors + && !descriptor.configurable + && (!hasOwn(descriptor, 'writable') || descriptor.writable) + && (!hasOwn(descriptor, 'enumerable') || descriptor.enumerable) + ) { + target[key] = descriptor.value; + return target; + } return nativeDefineProperty(target, key, descriptor); +}; - List.prototype.clear = function clear () { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = this._origin = this._capacity = 0; - this._level = SHIFT; - this._root = this._tail = this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyList(); - }; +if (DESCRIPTORS) { + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor; + definePropertyModule.f = wrappedDefineProperty; + addGetter(TypedArrayPrototype, 'buffer'); + addGetter(TypedArrayPrototype, 'byteOffset'); + addGetter(TypedArrayPrototype, 'byteLength'); + addGetter(TypedArrayPrototype, 'length'); + } - List.prototype.push = function push (/*...values*/) { - var values = arguments; - var oldSize = this.size; - return this.withMutations(function (list) { - setListBounds(list, 0, oldSize + values.length); - for (var ii = 0; ii < values.length; ii++) { - list.set(oldSize + ii, values[ii]); - } - }); - }; + $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { + getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, + defineProperty: wrappedDefineProperty + }); - List.prototype.pop = function pop () { - return setListBounds(this, 0, -1); - }; + module.exports = function (TYPE, wrapper, CLAMPED) { + var BYTES = TYPE.match(/\d+/)[0] / 8; + var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + TYPE; + var SETTER = 'set' + TYPE; + var NativeTypedArrayConstructor = globalThis[CONSTRUCTOR_NAME]; + var TypedArrayConstructor = NativeTypedArrayConstructor; + var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; + var exported = {}; - List.prototype.unshift = function unshift (/*...values*/) { - var values = arguments; - return this.withMutations(function (list) { - setListBounds(list, -values.length); - for (var ii = 0; ii < values.length; ii++) { - list.set(ii, values[ii]); - } - }); - }; + var getter = function (that, index) { + var data = getInternalState(that); + return data.view[GETTER](index * BYTES + data.byteOffset, true); + }; - List.prototype.shift = function shift () { - return setListBounds(this, 1); - }; + var setter = function (that, index, value) { + var data = getInternalState(that); + data.view[SETTER](index * BYTES + data.byteOffset, CLAMPED ? toUint8Clamped(value) : value, true); + }; - List.prototype.shuffle = function shuffle (random) { - if ( random === void 0 ) random = Math.random; + var addElement = function (that, index) { + nativeDefineProperty(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; - return this.withMutations(function (mutable) { - // implementation of the Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle - var current = mutable.size; - var destination; - var tmp; + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + TypedArrayConstructor = wrapper(function (that, data, offset, $length) { + anInstance(that, TypedArrayConstructorPrototype); + var index = 0; + var byteOffset = 0; + var buffer, byteLength, length; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new ArrayBuffer(byteLength); + } else if (isArrayBuffer(data)) { + buffer = data; + byteOffset = toOffset(offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw new RangeError(WRONG_LENGTH); + byteLength = $len - byteOffset; + if (byteLength < 0) throw new RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + byteOffset > $len) throw new RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (isTypedArray(data)) { + return arrayFromConstructorAndList(TypedArrayConstructor, data); + } else { + return call(typedArrayFrom, TypedArrayConstructor, data); + } + setInternalState(that, { + buffer: buffer, + byteOffset: byteOffset, + byteLength: byteLength, + length: length, + view: new DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); - while (current) { - destination = Math.floor(random() * current--); + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype); + } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) { + TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { + anInstance(dummy, TypedArrayConstructorPrototype); + return inheritIfRequired(function () { + if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); + if (isArrayBuffer(data)) return $length !== undefined + ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) + : typedArrayOffset !== undefined + ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) + : new NativeTypedArrayConstructor(data); + if (isTypedArray(data)) return arrayFromConstructorAndList(TypedArrayConstructor, data); + return call(typedArrayFrom, TypedArrayConstructor, data); + }(), dummy, TypedArrayConstructor); + }); - tmp = mutable.get(destination); - mutable.set(destination, mutable.get(current)); - mutable.set(current, tmp); - } - }); - }; + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { + if (!(key in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); + } + }); + TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; + } - // @pragma Composition + if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); + } - List.prototype.concat = function concat (/*...collections*/) { - var arguments$1 = arguments; + enforceInternalState(TypedArrayConstructorPrototype).TypedArrayConstructor = TypedArrayConstructor; - var seqs = []; - for (var i = 0; i < arguments.length; i++) { - var argument = arguments$1[i]; - var seq = IndexedCollection( - typeof argument !== 'string' && hasIterator(argument) - ? argument - : [argument] - ); - if (seq.size !== 0) { - seqs.push(seq); - } - } - if (seqs.length === 0) { - return this; - } - if (this.size === 0 && !this.__ownerID && seqs.length === 1) { - return this.constructor(seqs[0]); + if (TYPED_ARRAY_TAG) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); } - return this.withMutations(function (list) { - seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); }); - }); - }; - - List.prototype.setSize = function setSize (size) { - return setListBounds(this, 0, size); - }; - List.prototype.map = function map (mapper, context) { - var this$1$1 = this; + var FORCED = TypedArrayConstructor !== NativeTypedArrayConstructor; - return this.withMutations(function (list) { - for (var i = 0; i < this$1$1.size; i++) { - list.set(i, mapper.call(context, list.get(i), i, this$1$1)); - } - }); - }; + exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; - // @pragma Iteration + $({ global: true, constructor: true, forced: FORCED, sham: !NATIVE_ARRAY_BUFFER_VIEWS }, exported); - List.prototype.slice = function slice (begin, end) { - var size = this.size; - if (wholeSlice(begin, end, size)) { - return this; + if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); } - return setListBounds( - this, - resolveBegin(begin, size), - resolveEnd(end, size) - ); - }; - - List.prototype.__iterator = function __iterator (type, reverse) { - var index = reverse ? this.size : 0; - var values = iterateList(this, reverse); - return new Iterator(function () { - var value = values(); - return value === DONE - ? iteratorDone() - : iteratorValue(type, reverse ? --index : index++, value); - }); - }; - List.prototype.__iterate = function __iterate (fn, reverse) { - var index = reverse ? this.size : 0; - var values = iterateList(this, reverse); - var value; - while ((value = values()) !== DONE) { - if (fn(value, reverse ? --index : index++, this) === false) { - break; - } + if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); } - return index; - }; - List.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyList(); - } - this.__ownerID = ownerID; - this.__altered = false; - return this; - } - return makeList( - this._origin, - this._capacity, - this._level, - this._root, - this._tail, - ownerID, - this.__hash - ); + setSpecies(CONSTRUCTOR_NAME); }; +} else module.exports = function () { /* empty */ }; - return List; -}(IndexedCollection)); - -List.isList = isList; - -var ListPrototype = List.prototype; -ListPrototype[IS_LIST_SYMBOL] = true; -ListPrototype[DELETE] = ListPrototype.remove; -ListPrototype.merge = ListPrototype.concat; -ListPrototype.setIn = setIn; -ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn; -ListPrototype.update = update; -ListPrototype.updateIn = updateIn; -ListPrototype.mergeIn = mergeIn; -ListPrototype.mergeDeepIn = mergeDeepIn; -ListPrototype.withMutations = withMutations; -ListPrototype.wasAltered = wasAltered; -ListPrototype.asImmutable = asImmutable; -ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable; -ListPrototype['@@transducer/step'] = function (result, arr) { - return result.push(arr); -}; -ListPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; - -var VNode = function VNode(array, ownerID) { - this.array = array; - this.ownerID = ownerID; -}; -// TODO: seems like these methods are very similar +/***/ }), +/* 61 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) { - if ( - (index & ((1 << (level + SHIFT)) - 1)) === 0 || - this.array.length === 0 - ) { - return this; - } - var originIndex = (index >>> level) & MASK; - if (originIndex >= this.array.length) { - return new VNode([], ownerID); - } - var removingFirst = originIndex === 0; - var newChild; - if (level > 0) { - var oldChild = this.array[originIndex]; - newChild = - oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); - if (newChild === oldChild && removingFirst) { - return this; - } - } - if (removingFirst && !newChild) { - return this; - } - var editable = editableVNode(this, ownerID); - if (!removingFirst) { - for (var ii = 0; ii < originIndex; ii++) { - editable.array[ii] = undefined; - } - } - if (newChild) { - editable.array[originIndex] = newChild; - } - return editable; -}; - -VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) { - if ( - index === (level ? 1 << (level + SHIFT) : SIZE) || - this.array.length === 0 - ) { - return this; - } - var sizeIndex = ((index - 1) >>> level) & MASK; - if (sizeIndex >= this.array.length) { - return this; - } - - var newChild; - if (level > 0) { - var oldChild = this.array[sizeIndex]; - newChild = - oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); - if (newChild === oldChild && sizeIndex === this.array.length - 1) { - return this; - } - } - - var editable = editableVNode(this, ownerID); - editable.array.splice(sizeIndex + 1); - if (newChild) { - editable.array[sizeIndex] = newChild; - } - return editable; -}; - -var DONE = {}; - -function iterateList(list, reverse) { - var left = list._origin; - var right = list._capacity; - var tailPos = getTailOffset(right); - var tail = list._tail; - - return iterateNodeOrLeaf(list._root, list._level, 0); - - function iterateNodeOrLeaf(node, level, offset) { - return level === 0 - ? iterateLeaf(node, offset) - : iterateNode(node, level, offset); - } - - function iterateLeaf(node, offset) { - var array = offset === tailPos ? tail && tail.array : node && node.array; - var from = offset > left ? 0 : left - offset; - var to = right - offset; - if (to > SIZE) { - to = SIZE; +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return Collection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Iterable", function() { return Iterable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "List", function() { return List; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Map", function() { return Map; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderedMap", function() { return OrderedMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderedSet", function() { return OrderedSet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PairSorting", function() { return PairSorting; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Record", function() { return Record; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Repeat", function() { return Repeat; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Seq", function() { return Seq; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Set", function() { return Set; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Stack", function() { return Stack; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromJS", function() { return fromJS; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return get; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIn", function() { return getIn$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "has", function() { return has; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasIn", function() { return hasIn$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hash", function() { return hash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "is", function() { return is; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAssociative", function() { return isAssociative; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCollection", function() { return isCollection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isImmutable", function() { return isImmutable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIndexed", function() { return isIndexed; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isKeyed", function() { return isKeyed; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isList", function() { return isList; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return isMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrdered", function() { return isOrdered; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrderedMap", function() { return isOrderedMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOrderedSet", function() { return isOrderedSet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlainObject", function() { return isPlainObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRecord", function() { return isRecord; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSeq", function() { return isSeq; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return isSet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStack", function() { return isStack; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValueObject", function() { return isValueObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDeep", function() { return mergeDeep$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDeepWith", function() { return mergeDeepWith$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeWith", function() { return mergeWith; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "remove", function() { return remove; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeIn", function() { return removeIn; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "set", function() { return set; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setIn", function() { return setIn$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "update", function() { return update$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateIn", function() { return updateIn$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); +/** + * @license + * MIT License + * + * Copyright (c) 2014-present, Lee Byron and other 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. + */ +// Used for setting prototype methods that IE8 chokes on. +var DELETE = 'delete'; +// Constants describing the size of trie nodes. +var SHIFT = 5; // Resulted in best performance after ______? +var SIZE = 1 << SHIFT; +var MASK = SIZE - 1; +// A consistent shared value representing "not set" which equals nothing other +// than itself, and nothing that could be provided externally. +var NOT_SET = {}; +// Boolean references, Rough equivalent of `bool &`. +function MakeRef() { + return { value: false }; +} +function SetRef(ref) { + if (ref) { + ref.value = true; } - return function () { - if (from === to) { - return DONE; - } - var idx = reverse ? --to : from++; - return array && array[idx]; - }; - } - - function iterateNode(node, level, offset) { - var values; - var array = node && node.array; - var from = offset > left ? 0 : (left - offset) >> level; - var to = ((right - offset) >> level) + 1; - if (to > SIZE) { - to = SIZE; +} +// A function which returns a value representing an "owner" for transient writes +// to tries. The return value will only ever equal itself, and will not equal +// the return of any subsequent call of this function. +function OwnerID() { } +function ensureSize(iter) { + // @ts-expect-error size should exists on Collection + if (iter.size === undefined) { + // @ts-expect-error size should exists on Collection, __iterate does exist on Collection + iter.size = iter.__iterate(returnTrue); } - return function () { - while (true) { - if (values) { - var value = values(); - if (value !== DONE) { - return value; - } - values = null; - } - if (from === to) { - return DONE; + // @ts-expect-error size should exists on Collection + return iter.size; +} +function wrapIndex(iter, index) { + // This implements "is array index" which the ECMAString spec defines as: + // + // A String property name P is an array index if and only if + // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal + // to 2^32−1. + // + // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects + if (typeof index !== 'number') { + var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 + if ('' + uint32Index !== index || uint32Index === 4294967295) { + return NaN; } - var idx = reverse ? --to : from++; - values = iterateNodeOrLeaf( - array && array[idx], - level - SHIFT, - offset + (idx << level) - ); - } - }; - } + index = uint32Index; + } + return index < 0 ? ensureSize(iter) + index : index; +} +function returnTrue() { + return true; +} +function wholeSlice(begin, end, size) { + return (((begin === 0 && !isNeg(begin)) || + (size !== undefined && begin <= -size)) && + (end === undefined || (size !== undefined && end >= size))); +} +function resolveBegin(begin, size) { + return resolveIndex(begin, size, 0); +} +function resolveEnd(end, size) { + return resolveIndex(end, size, size); +} +function resolveIndex(index, size, defaultIndex) { + // Sanitize indices using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + return index === undefined + ? defaultIndex + : isNeg(index) + ? size === Infinity + ? size + : Math.max(0, size + index) | 0 + : size === undefined || size === index + ? index + : Math.min(size, index) | 0; +} +function isNeg(value) { + // Account for -0 which is negative, but not less than 0. + return value < 0 || (value === 0 && 1 / value === -Infinity); } -function makeList(origin, capacity, level, root, tail, ownerID, hash) { - var list = Object.create(ListPrototype); - list.size = capacity - origin; - list._origin = origin; - list._capacity = capacity; - list._level = level; - list._root = root; - list._tail = tail; - list.__ownerID = ownerID; - list.__hash = hash; - list.__altered = false; - return list; +// Note: value is unchanged to not break immutable-devtools. +var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@'; +/** + * True if `maybeCollection` is a Collection, or any of its subclasses. + * + * ```js + * import { isCollection, Map, List, Stack } from 'immutable'; + * + * isCollection([]); // false + * isCollection({}); // false + * isCollection(Map()); // true + * isCollection(List()); // true + * isCollection(Stack()); // true + * ``` + */ +function isCollection(maybeCollection) { + return Boolean(maybeCollection && + // @ts-expect-error: maybeCollection is typed as `{}`, need to change in 6.0 to `maybeCollection && typeof maybeCollection === 'object' && IS_COLLECTION_SYMBOL in maybeCollection` + maybeCollection[IS_COLLECTION_SYMBOL]); } -function emptyList() { - return makeList(0, 0, SHIFT); +var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@'; +/** + * True if `maybeKeyed` is a Collection.Keyed, or any of its subclasses. + * + * ```js + * import { isKeyed, Map, List, Stack } from 'immutable'; + * + * isKeyed([]); // false + * isKeyed({}); // false + * isKeyed(Map()); // true + * isKeyed(List()); // false + * isKeyed(Stack()); // false + * ``` + */ +function isKeyed(maybeKeyed) { + return Boolean(maybeKeyed && + // @ts-expect-error: maybeKeyed is typed as `{}`, need to change in 6.0 to `maybeKeyed && typeof maybeKeyed === 'object' && IS_KEYED_SYMBOL in maybeKeyed` + maybeKeyed[IS_KEYED_SYMBOL]); } -function updateList(list, index, value) { - index = wrapIndex(list, index); +var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@'; +/** + * True if `maybeIndexed` is a Collection.Indexed, or any of its subclasses. + * + * ```js + * import { isIndexed, Map, List, Stack, Set } from 'immutable'; + * + * isIndexed([]); // false + * isIndexed({}); // false + * isIndexed(Map()); // false + * isIndexed(List()); // true + * isIndexed(Stack()); // true + * isIndexed(Set()); // false + * ``` + */ +function isIndexed(maybeIndexed) { + return Boolean(maybeIndexed && + // @ts-expect-error: maybeIndexed is typed as `{}`, need to change in 6.0 to `maybeIndexed && typeof maybeIndexed === 'object' && IS_INDEXED_SYMBOL in maybeIndexed` + maybeIndexed[IS_INDEXED_SYMBOL]); +} - if (index !== index) { - return list; - } +/** + * True if `maybeAssociative` is either a Keyed or Indexed Collection. + * + * ```js + * import { isAssociative, Map, List, Stack, Set } from 'immutable'; + * + * isAssociative([]); // false + * isAssociative({}); // false + * isAssociative(Map()); // true + * isAssociative(List()); // true + * isAssociative(Stack()); // true + * isAssociative(Set()); // false + * ``` + */ +function isAssociative(maybeAssociative) { + return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); +} - if (index >= list.size || index < 0) { - return list.withMutations(function (list) { - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - index < 0 - ? setListBounds(list, index).set(0, value) - : setListBounds(list, 0, index + 1).set(index, value); - }); +var Collection = function Collection(value) { + // eslint-disable-next-line no-constructor-return + return isCollection(value) ? value : Seq(value); +}; + +var KeyedCollection = /*@__PURE__*/(function (Collection) { + function KeyedCollection(value) { + // eslint-disable-next-line no-constructor-return + return isKeyed(value) ? value : KeyedSeq(value); } - index += list._origin; + if ( Collection ) KeyedCollection.__proto__ = Collection; + KeyedCollection.prototype = Object.create( Collection && Collection.prototype ); + KeyedCollection.prototype.constructor = KeyedCollection; - var newTail = list._tail; - var newRoot = list._root; - var didAlter = MakeRef(); - if (index >= getTailOffset(list._capacity)) { - newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); - } else { - newRoot = updateVNode( - newRoot, - list.__ownerID, - list._level, - index, - value, - didAlter - ); - } + return KeyedCollection; +}(Collection)); - if (!didAlter.value) { - return list; +var IndexedCollection = /*@__PURE__*/(function (Collection) { + function IndexedCollection(value) { + // eslint-disable-next-line no-constructor-return + return isIndexed(value) ? value : IndexedSeq(value); } - if (list.__ownerID) { - list._root = newRoot; - list._tail = newTail; - list.__hash = undefined; - list.__altered = true; - return list; - } - return makeList(list._origin, list._capacity, list._level, newRoot, newTail); -} + if ( Collection ) IndexedCollection.__proto__ = Collection; + IndexedCollection.prototype = Object.create( Collection && Collection.prototype ); + IndexedCollection.prototype.constructor = IndexedCollection; -function updateVNode(node, ownerID, level, index, value, didAlter) { - var idx = (index >>> level) & MASK; - var nodeHas = node && idx < node.array.length; - if (!nodeHas && value === undefined) { - return node; + return IndexedCollection; +}(Collection)); + +var SetCollection = /*@__PURE__*/(function (Collection) { + function SetCollection(value) { + // eslint-disable-next-line no-constructor-return + return isCollection(value) && !isAssociative(value) ? value : SetSeq(value); } - var newNode; + if ( Collection ) SetCollection.__proto__ = Collection; + SetCollection.prototype = Object.create( Collection && Collection.prototype ); + SetCollection.prototype.constructor = SetCollection; - if (level > 0) { - var lowerNode = node && node.array[idx]; - var newLowerNode = updateVNode( - lowerNode, - ownerID, - level - SHIFT, - index, - value, - didAlter - ); - if (newLowerNode === lowerNode) { - return node; - } - newNode = editableVNode(node, ownerID); - newNode.array[idx] = newLowerNode; - return newNode; - } + return SetCollection; +}(Collection)); - if (nodeHas && node.array[idx] === value) { - return node; - } +Collection.Keyed = KeyedCollection; +Collection.Indexed = IndexedCollection; +Collection.Set = SetCollection; - if (didAlter) { - SetRef(didAlter); - } +var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@'; +/** + * True if `maybeSeq` is a Seq. + */ +function isSeq(maybeSeq) { + return Boolean(maybeSeq && + // @ts-expect-error: maybeSeq is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSeq === 'object' && MAYBE_SEQ_SYMBOL in maybeSeq` + maybeSeq[IS_SEQ_SYMBOL]); +} - newNode = editableVNode(node, ownerID); - if (value === undefined && idx === newNode.array.length - 1) { - newNode.array.pop(); - } else { - newNode.array[idx] = value; - } - return newNode; +var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; +/** + * True if `maybeRecord` is a Record. + */ +function isRecord(maybeRecord) { + return Boolean(maybeRecord && + // @ts-expect-error: maybeRecord is typed as `{}`, need to change in 6.0 to `maybeRecord && typeof maybeRecord === 'object' && IS_RECORD_SYMBOL in maybeRecord` + maybeRecord[IS_RECORD_SYMBOL]); } -function editableVNode(node, ownerID) { - if (ownerID && node && ownerID === node.ownerID) { - return node; - } - return new VNode(node ? node.array.slice() : [], ownerID); +/** + * True if `maybeImmutable` is an Immutable Collection or Record. + * + * Note: Still returns true even if the collections is within a `withMutations()`. + * + * ```js + * import { isImmutable, Map, List, Stack } from 'immutable'; + * isImmutable([]); // false + * isImmutable({}); // false + * isImmutable(Map()); // true + * isImmutable(List()); // true + * isImmutable(Stack()); // true + * isImmutable(Map().asMutable()); // true + * ``` + */ +function isImmutable(maybeImmutable) { + return isCollection(maybeImmutable) || isRecord(maybeImmutable); } -function listNodeFor(list, rawIndex) { - if (rawIndex >= getTailOffset(list._capacity)) { - return list._tail; - } - if (rawIndex < 1 << (list._level + SHIFT)) { - var node = list._root; - var level = list._level; - while (node && level > 0) { - node = node.array[(rawIndex >>> level) & MASK]; - level -= SHIFT; - } - return node; - } +var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@'; +function isOrdered(maybeOrdered) { + return Boolean(maybeOrdered && + // @ts-expect-error: maybeOrdered is typed as `{}`, need to change in 6.0 to `maybeOrdered && typeof maybeOrdered === 'object' && IS_ORDERED_SYMBOL in maybeOrdered` + maybeOrdered[IS_ORDERED_SYMBOL]); } -function setListBounds(list, begin, end) { - // Sanitize begin & end using this shorthand for ToInt32(argument) - // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 - if (begin !== undefined) { - begin |= 0; - } - if (end !== undefined) { - end |= 0; - } - var owner = list.__ownerID || new OwnerID(); - var oldOrigin = list._origin; - var oldCapacity = list._capacity; - var newOrigin = oldOrigin + begin; - var newCapacity = - end === undefined - ? oldCapacity - : end < 0 - ? oldCapacity + end - : oldOrigin + end; - if (newOrigin === oldOrigin && newCapacity === oldCapacity) { - return list; - } +var ITERATE_KEYS = 0; +var ITERATE_VALUES = 1; +var ITERATE_ENTRIES = 2; - // If it's going to end after it starts, it's empty. - if (newOrigin >= newCapacity) { - return list.clear(); - } +var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; - var newLevel = list._level; - var newRoot = list._root; +var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; - // New origin might need creating a higher root. - var offsetShift = 0; - while (newOrigin + offsetShift < 0) { - newRoot = new VNode( - newRoot && newRoot.array.length ? [undefined, newRoot] : [], - owner - ); - newLevel += SHIFT; - offsetShift += 1 << newLevel; - } - if (offsetShift) { - newOrigin += offsetShift; - oldOrigin += offsetShift; - newCapacity += offsetShift; - oldCapacity += offsetShift; - } +var Iterator = function Iterator(next) { + this.next = next; +}; - var oldTailOffset = getTailOffset(oldCapacity); - var newTailOffset = getTailOffset(newCapacity); +Iterator.prototype.toString = function toString () { + return '[Iterator]'; +}; - // New size might need creating a higher root. - while (newTailOffset >= 1 << (newLevel + SHIFT)) { - newRoot = new VNode( - newRoot && newRoot.array.length ? [newRoot] : [], - owner - ); - newLevel += SHIFT; - } +Iterator.KEYS = ITERATE_KEYS; +Iterator.VALUES = ITERATE_VALUES; +Iterator.ENTRIES = ITERATE_ENTRIES; - // Locate or create the new tail. - var oldTail = list._tail; - var newTail = - newTailOffset < oldTailOffset - ? listNodeFor(list, newCapacity - 1) - : newTailOffset > oldTailOffset - ? new VNode([], owner) - : oldTail; +Iterator.prototype.inspect = Iterator.prototype.toSource = function () { + return this.toString(); +}; +Iterator.prototype[ITERATOR_SYMBOL] = function () { + return this; +}; - // Merge Tail into tree. - if ( - oldTail && - newTailOffset > oldTailOffset && - newOrigin < oldCapacity && - oldTail.array.length - ) { - newRoot = editableVNode(newRoot, owner); - var node = newRoot; - for (var level = newLevel; level > SHIFT; level -= SHIFT) { - var idx = (oldTailOffset >>> level) & MASK; - node = node.array[idx] = editableVNode(node.array[idx], owner); - } - node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; - } +function iteratorValue(type, k, v, iteratorResult) { + var value = + type === ITERATE_KEYS ? k : type === ITERATE_VALUES ? v : [k, v]; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + iteratorResult + ? (iteratorResult.value = value) + : (iteratorResult = { + value: value, + done: false, + }); + return iteratorResult; +} - // If the size has been reduced, there's a chance the tail needs to be trimmed. - if (newCapacity < oldCapacity) { - newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); +function iteratorDone() { + return { value: undefined, done: true }; +} + +function hasIterator(maybeIterable) { + if (Array.isArray(maybeIterable)) { + // IE11 trick as it does not support `Symbol.iterator` + return true; } - // If the new origin is within the tail, then we do not need a root. - if (newOrigin >= newTailOffset) { - newOrigin -= newTailOffset; - newCapacity -= newTailOffset; - newLevel = SHIFT; - newRoot = null; - newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); + return !!getIteratorFn(maybeIterable); +} - // Otherwise, if the root has been trimmed, garbage collect. - } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { - offsetShift = 0; +function isIterator(maybeIterator) { + return maybeIterator && typeof maybeIterator.next === 'function'; +} - // Identify the new top root node of the subtree of the old root. - while (newRoot) { - var beginIndex = (newOrigin >>> newLevel) & MASK; - if ((beginIndex !== newTailOffset >>> newLevel) & MASK) { - break; - } - if (beginIndex) { - offsetShift += (1 << newLevel) * beginIndex; - } - newLevel -= SHIFT; - newRoot = newRoot.array[beginIndex]; - } +function getIterator(iterable) { + var iteratorFn = getIteratorFn(iterable); + return iteratorFn && iteratorFn.call(iterable); +} - // Trim the new sides of the new root. - if (newRoot && newOrigin > oldOrigin) { - newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); - } - if (newRoot && newTailOffset < oldTailOffset) { - newRoot = newRoot.removeAfter( - owner, - newLevel, - newTailOffset - offsetShift - ); - } - if (offsetShift) { - newOrigin -= offsetShift; - newCapacity -= offsetShift; - } +function getIteratorFn(iterable) { + var iteratorFn = + iterable && + ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || + iterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; } +} - if (list.__ownerID) { - list.size = newCapacity - newOrigin; - list._origin = newOrigin; - list._capacity = newCapacity; - list._level = newLevel; - list._root = newRoot; - list._tail = newTail; - list.__hash = undefined; - list.__altered = true; - return list; - } - return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); +function isEntriesIterable(maybeIterable) { + var iteratorFn = getIteratorFn(maybeIterable); + return iteratorFn && iteratorFn === maybeIterable.entries; } -function getTailOffset(size) { - return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT; +function isKeysIterable(maybeIterable) { + var iteratorFn = getIteratorFn(maybeIterable); + return iteratorFn && iteratorFn === maybeIterable.keys; } -var OrderedMap = /*@__PURE__*/(function (Map) { - function OrderedMap(value) { +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function isArrayLike(value) { + if (Array.isArray(value) || typeof value === 'string') { + return true; + } + // @ts-expect-error "Type 'unknown' is not assignable to type 'boolean'" : convert to Boolean + return (value && + typeof value === 'object' && + // @ts-expect-error check that `'length' in value &&` + Number.isInteger(value.length) && + // @ts-expect-error check that `'length' in value &&` + value.length >= 0 && + // @ts-expect-error check that `'length' in value &&` + (value.length === 0 + ? // Only {length: 0} is considered Array-like. + Object.keys(value).length === 1 + : // An object is only Array-like if it has a property where the last value + // in the array-like may be found (which could be undefined). + // @ts-expect-error check that `'length' in value &&` + value.hasOwnProperty(value.length - 1))); +} + +var Seq = /*@__PURE__*/(function (Collection) { + function Seq(value) { // eslint-disable-next-line no-constructor-return return value === undefined || value === null - ? emptyOrderedMap() - : isOrderedMap(value) - ? value - : emptyOrderedMap().withMutations(function (map) { - var iter = KeyedCollection(value); - assertNotInfinite(iter.size); - iter.forEach(function (v, k) { return map.set(k, v); }); - }); + ? emptySequence() + : isImmutable(value) + ? value.toSeq() + : seqFromValue(value); } - if ( Map ) OrderedMap.__proto__ = Map; - OrderedMap.prototype = Object.create( Map && Map.prototype ); - OrderedMap.prototype.constructor = OrderedMap; + if ( Collection ) Seq.__proto__ = Collection; + Seq.prototype = Object.create( Collection && Collection.prototype ); + Seq.prototype.constructor = Seq; - OrderedMap.of = function of (/*...values*/) { - return this(arguments); + Seq.prototype.toSeq = function toSeq () { + return this; }; - OrderedMap.prototype.toString = function toString () { - return this.__toString('OrderedMap {', '}'); + Seq.prototype.toString = function toString () { + return this.__toString('Seq {', '}'); }; - // @pragma Access - - OrderedMap.prototype.get = function get (k, notSetValue) { - var index = this._map.get(k); - return index !== undefined ? this._list.get(index)[1] : notSetValue; + Seq.prototype.cacheResult = function cacheResult () { + if (!this._cache && this.__iterateUncached) { + this._cache = this.entrySeq().toArray(); + this.size = this._cache.length; + } + return this; }; - // @pragma Modification + // abstract __iterateUncached(fn, reverse) - OrderedMap.prototype.clear = function clear () { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._map.clear(); - this._list.clear(); - this.__altered = true; - return this; + Seq.prototype.__iterate = function __iterate (fn, reverse) { + var cache = this._cache; + if (cache) { + var size = cache.length; + var i = 0; + while (i !== size) { + var entry = cache[reverse ? size - ++i : i++]; + if (fn(entry[1], entry[0], this) === false) { + break; + } + } + return i; } - return emptyOrderedMap(); + return this.__iterateUncached(fn, reverse); }; - OrderedMap.prototype.set = function set (k, v) { - return updateOrderedMap(this, k, v); - }; + // abstract __iteratorUncached(type, reverse) - OrderedMap.prototype.remove = function remove (k) { - return updateOrderedMap(this, k, NOT_SET); + Seq.prototype.__iterator = function __iterator (type, reverse) { + var cache = this._cache; + if (cache) { + var size = cache.length; + var i = 0; + return new Iterator(function () { + if (i === size) { + return iteratorDone(); + } + var entry = cache[reverse ? size - ++i : i++]; + return iteratorValue(type, entry[0], entry[1]); + }); + } + return this.__iteratorUncached(type, reverse); }; - OrderedMap.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; + return Seq; +}(Collection)); - return this._list.__iterate( - function (entry) { return entry && fn(entry[1], entry[0], this$1$1); }, - reverse - ); - }; +var KeyedSeq = /*@__PURE__*/(function (Seq) { + function KeyedSeq(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptySequence().toKeyedSeq() + : isCollection(value) + ? isKeyed(value) + ? value.toSeq() + : value.fromEntrySeq() + : isRecord(value) + ? value.toSeq() + : keyedSeqFromValue(value); + } - OrderedMap.prototype.__iterator = function __iterator (type, reverse) { - return this._list.fromEntrySeq().__iterator(type, reverse); - }; + if ( Seq ) KeyedSeq.__proto__ = Seq; + KeyedSeq.prototype = Object.create( Seq && Seq.prototype ); + KeyedSeq.prototype.constructor = KeyedSeq; - OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - var newMap = this._map.__ensureOwner(ownerID); - var newList = this._list.__ensureOwner(ownerID); - if (!ownerID) { - if (this.size === 0) { - return emptyOrderedMap(); - } - this.__ownerID = ownerID; - this.__altered = false; - this._map = newMap; - this._list = newList; - return this; - } - return makeOrderedMap(newMap, newList, ownerID, this.__hash); + KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () { + return this; }; - return OrderedMap; -}(Map)); + return KeyedSeq; +}(Seq)); -OrderedMap.isOrderedMap = isOrderedMap; +var IndexedSeq = /*@__PURE__*/(function (Seq) { + function IndexedSeq(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptySequence() + : isCollection(value) + ? isKeyed(value) + ? value.entrySeq() + : value.toIndexedSeq() + : isRecord(value) + ? value.toSeq().entrySeq() + : indexedSeqFromValue(value); + } -OrderedMap.prototype[IS_ORDERED_SYMBOL] = true; -OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; + if ( Seq ) IndexedSeq.__proto__ = Seq; + IndexedSeq.prototype = Object.create( Seq && Seq.prototype ); + IndexedSeq.prototype.constructor = IndexedSeq; -function makeOrderedMap(map, list, ownerID, hash) { - var omap = Object.create(OrderedMap.prototype); - omap.size = map ? map.size : 0; - omap._map = map; - omap._list = list; - omap.__ownerID = ownerID; - omap.__hash = hash; - omap.__altered = false; - return omap; -} + IndexedSeq.of = function of (/*...values*/) { + return IndexedSeq(arguments); + }; -var EMPTY_ORDERED_MAP; -function emptyOrderedMap() { - return ( - EMPTY_ORDERED_MAP || - (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())) - ); -} + IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () { + return this; + }; -function updateOrderedMap(omap, k, v) { - var map = omap._map; - var list = omap._list; - var i = map.get(k); - var has = i !== undefined; - var newMap; - var newList; - if (v === NOT_SET) { - // removed - if (!has) { - return omap; - } - if (list.size >= SIZE && list.size >= map.size * 2) { - newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; }); - newMap = newList - .toKeyedSeq() - .map(function (entry) { return entry[0]; }) - .flip() - .toMap(); - if (omap.__ownerID) { - newMap.__ownerID = newList.__ownerID = omap.__ownerID; - } - } else { - newMap = map.remove(k); - newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); - } - } else if (has) { - if (v === list.get(i)[1]) { - return omap; - } - newMap = map; - newList = list.set(i, [k, v]); - } else { - newMap = map.set(k, list.size); - newList = list.set(list.size, [k, v]); - } - if (omap.__ownerID) { - omap.size = newMap.size; - omap._map = newMap; - omap._list = newList; - omap.__hash = undefined; - omap.__altered = true; - return omap; - } - return makeOrderedMap(newMap, newList); -} + IndexedSeq.prototype.toString = function toString () { + return this.__toString('Seq [', ']'); + }; -var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@'; -/** - * True if `maybeStack` is a Stack. - */ -function isStack(maybeStack) { - return Boolean(maybeStack && - // @ts-expect-error: maybeStack is typed as `{}`, need to change in 6.0 to `maybeStack && typeof maybeStack === 'object' && MAYBE_STACK_SYMBOL in maybeStack` - maybeStack[IS_STACK_SYMBOL]); -} + return IndexedSeq; +}(Seq)); -var Stack = /*@__PURE__*/(function (IndexedCollection) { - function Stack(value) { +var SetSeq = /*@__PURE__*/(function (Seq) { + function SetSeq(value) { // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptyStack() - : isStack(value) - ? value - : emptyStack().pushAll(value); + return ( + isCollection(value) && !isAssociative(value) ? value : IndexedSeq(value) + ).toSetSeq(); } - if ( IndexedCollection ) Stack.__proto__ = IndexedCollection; - Stack.prototype = Object.create( IndexedCollection && IndexedCollection.prototype ); - Stack.prototype.constructor = Stack; + if ( Seq ) SetSeq.__proto__ = Seq; + SetSeq.prototype = Object.create( Seq && Seq.prototype ); + SetSeq.prototype.constructor = SetSeq; - Stack.of = function of (/*...values*/) { - return this(arguments); + SetSeq.of = function of (/*...values*/) { + return SetSeq(arguments); }; - Stack.prototype.toString = function toString () { - return this.__toString('Stack [', ']'); + SetSeq.prototype.toSetSeq = function toSetSeq () { + return this; }; - // @pragma Access + return SetSeq; +}(Seq)); - Stack.prototype.get = function get (index, notSetValue) { - var head = this._head; - index = wrapIndex(this, index); - while (head && index--) { - head = head.next; - } - return head ? head.value : notSetValue; - }; +Seq.isSeq = isSeq; +Seq.Keyed = KeyedSeq; +Seq.Set = SetSeq; +Seq.Indexed = IndexedSeq; - Stack.prototype.peek = function peek () { - return this._head && this._head.value; - }; +Seq.prototype[IS_SEQ_SYMBOL] = true; - // @pragma Modification +// #pragma Root Sequences - Stack.prototype.push = function push (/*...values*/) { - var arguments$1 = arguments; +var ArraySeq = /*@__PURE__*/(function (IndexedSeq) { + function ArraySeq(array) { + this._array = array; + this.size = array.length; + } - if (arguments.length === 0) { - return this; - } - var newSize = this.size + arguments.length; - var head = this._head; - for (var ii = arguments.length - 1; ii >= 0; ii--) { - head = { - value: arguments$1[ii], - next: head, - }; - } - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; - } - return makeStack(newSize, head); + if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq; + ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); + ArraySeq.prototype.constructor = ArraySeq; + + ArraySeq.prototype.get = function get (index, notSetValue) { + return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; - Stack.prototype.pushAll = function pushAll (iter) { - iter = IndexedCollection(iter); - if (iter.size === 0) { - return this; - } - if (this.size === 0 && isStack(iter)) { - return iter; - } - assertNotInfinite(iter.size); - var newSize = this.size; - var head = this._head; - iter.__iterate(function (value) { - newSize++; - head = { - value: value, - next: head, - }; - }, /* reverse */ true); - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; + ArraySeq.prototype.__iterate = function __iterate (fn, reverse) { + var array = this._array; + var size = array.length; + var i = 0; + while (i !== size) { + var ii = reverse ? size - ++i : i++; + if (fn(array[ii], ii, this) === false) { + break; + } } - return makeStack(newSize, head); + return i; }; - Stack.prototype.pop = function pop () { - return this.slice(1); + ArraySeq.prototype.__iterator = function __iterator (type, reverse) { + var array = this._array; + var size = array.length; + var i = 0; + return new Iterator(function () { + if (i === size) { + return iteratorDone(); + } + var ii = reverse ? size - ++i : i++; + return iteratorValue(type, ii, array[ii]); + }); }; - Stack.prototype.clear = function clear () { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._head = undefined; - this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyStack(); - }; + return ArraySeq; +}(IndexedSeq)); - Stack.prototype.slice = function slice (begin, end) { - if (wholeSlice(begin, end, this.size)) { - return this; - } - var resolvedBegin = resolveBegin(begin, this.size); - var resolvedEnd = resolveEnd(end, this.size); - if (resolvedEnd !== this.size) { - // super.slice(begin, end); - return IndexedCollection.prototype.slice.call(this, begin, end); - } - var newSize = this.size - resolvedBegin; - var head = this._head; - while (resolvedBegin--) { - head = head.next; - } - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; +var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) { + function ObjectSeq(object) { + var keys = Object.keys(object).concat( + Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [] + ); + this._object = object; + this._keys = keys; + this.size = keys.length; + } + + if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq; + ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); + ObjectSeq.prototype.constructor = ObjectSeq; + + ObjectSeq.prototype.get = function get (key, notSetValue) { + if (notSetValue !== undefined && !this.has(key)) { + return notSetValue; } - return makeStack(newSize, head); + return this._object[key]; }; - // @pragma Mutability + ObjectSeq.prototype.has = function has (key) { + return hasOwnProperty.call(this._object, key); + }; - Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyStack(); + ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) { + var object = this._object; + var keys = this._keys; + var size = keys.length; + var i = 0; + while (i !== size) { + var key = keys[reverse ? size - ++i : i++]; + if (fn(object[key], key, this) === false) { + break; } - this.__ownerID = ownerID; - this.__altered = false; - return this; } - return makeStack(this.size, this._head, ownerID, this.__hash); + return i; }; - // @pragma Iteration + ObjectSeq.prototype.__iterator = function __iterator (type, reverse) { + var object = this._object; + var keys = this._keys; + var size = keys.length; + var i = 0; + return new Iterator(function () { + if (i === size) { + return iteratorDone(); + } + var key = keys[reverse ? size - ++i : i++]; + return iteratorValue(type, key, object[key]); + }); + }; - Stack.prototype.__iterate = function __iterate (fn, reverse) { - var this$1$1 = this; + return ObjectSeq; +}(KeyedSeq)); +ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true; + +var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) { + function CollectionSeq(collection) { + this._collection = collection; + this.size = collection.length || collection.size; + } + + if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq; + CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); + CollectionSeq.prototype.constructor = CollectionSeq; + CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) { if (reverse) { - return new ArraySeq(this.toArray()).__iterate( - function (v, k) { return fn(v, k, this$1$1); }, - reverse - ); + return this.cacheResult().__iterate(fn, reverse); } + var collection = this._collection; + var iterator = getIterator(collection); var iterations = 0; - var node = this._head; - while (node) { - if (fn(node.value, iterations++, this) === false) { - break; + if (isIterator(iterator)) { + var step; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } } - node = node.next; } return iterations; }; - Stack.prototype.__iterator = function __iterator (type, reverse) { + CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) { if (reverse) { - return new ArraySeq(this.toArray()).__iterator(type, reverse); + return this.cacheResult().__iterator(type, reverse); + } + var collection = this._collection; + var iterator = getIterator(collection); + if (!isIterator(iterator)) { + return new Iterator(iteratorDone); } var iterations = 0; - var node = this._head; return new Iterator(function () { - if (node) { - var value = node.value; - node = node.next; - return iteratorValue(type, iterations++, value); - } - return iteratorDone(); + var step = iterator.next(); + return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; - return Stack; -}(IndexedCollection)); + return CollectionSeq; +}(IndexedSeq)); -Stack.isStack = isStack; +// # pragma Helper functions -var StackPrototype = Stack.prototype; -StackPrototype[IS_STACK_SYMBOL] = true; -StackPrototype.shift = StackPrototype.pop; -StackPrototype.unshift = StackPrototype.push; -StackPrototype.unshiftAll = StackPrototype.pushAll; -StackPrototype.withMutations = withMutations; -StackPrototype.wasAltered = wasAltered; -StackPrototype.asImmutable = asImmutable; -StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable; -StackPrototype['@@transducer/step'] = function (result, arr) { - return result.unshift(arr); -}; -StackPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; +var EMPTY_SEQ; -function makeStack(size, head, ownerID, hash) { - var map = Object.create(StackPrototype); - map.size = size; - map._head = head; - map.__ownerID = ownerID; - map.__hash = hash; - map.__altered = false; - return map; +function emptySequence() { + return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } -var EMPTY_STACK; -function emptyStack() { - return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); +function keyedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (seq) { + return seq.fromEntrySeq(); + } + if (typeof value === 'object') { + return new ObjectSeq(value); + } + throw new TypeError( + 'Expected Array or collection object of [k, v] entries, or keyed object: ' + + value + ); } -var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@'; +function indexedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (seq) { + return seq; + } + throw new TypeError( + 'Expected Array or collection object of values: ' + value + ); +} + +function seqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (seq) { + return isEntriesIterable(value) + ? seq.fromEntrySeq() + : isKeysIterable(value) + ? seq.toSetSeq() + : seq; + } + if (typeof value === 'object') { + return new ObjectSeq(value); + } + throw new TypeError( + 'Expected Array or collection object of values, or keyed object: ' + value + ); +} + +function maybeIndexedSeqFromValue(value) { + return isArrayLike(value) + ? new ArraySeq(value) + : hasIterator(value) + ? new CollectionSeq(value) + : undefined; +} + +var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@'; /** - * True if `maybeSet` is a Set. + * True if `maybeMap` is a Map. * - * Also true for OrderedSets. + * Also true for OrderedMaps. */ -function isSet(maybeSet) { - return Boolean(maybeSet && - // @ts-expect-error: maybeSet is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSet === 'object' && MAYBE_SET_SYMBOL in maybeSet` - maybeSet[IS_SET_SYMBOL]); +function isMap(maybeMap) { + return Boolean(maybeMap && + // @ts-expect-error: maybeMap is typed as `{}`, need to change in 6.0 to `maybeMap && typeof maybeMap === 'object' && IS_MAP_SYMBOL in maybeMap` + maybeMap[IS_MAP_SYMBOL]); } /** - * True if `maybeOrderedSet` is an OrderedSet. + * True if `maybeOrderedMap` is an OrderedMap. */ -function isOrderedSet(maybeOrderedSet) { - return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); +function isOrderedMap(maybeOrderedMap) { + return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } -function deepEqual(a, b) { - if (a === b) { +/** + * True if `maybeValue` is a JavaScript Object which has *both* `equals()` + * and `hashCode()` methods. + * + * Any two instances of *value objects* can be compared for value equality with + * `Immutable.is()` and can be used as keys in a `Map` or members in a `Set`. + */ +function isValueObject(maybeValue) { + return Boolean(maybeValue && + // @ts-expect-error: maybeValue is typed as `{}` + typeof maybeValue.equals === 'function' && + // @ts-expect-error: maybeValue is typed as `{}` + typeof maybeValue.hashCode === 'function'); +} + +/** + * An extension of the "same-value" algorithm as [described for use by ES6 Map + * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) + * + * NaN is considered the same as NaN, however -0 and 0 are considered the same + * value, which is different from the algorithm described by + * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * This is extended further to allow Objects to describe the values they + * represent, by way of `valueOf` or `equals` (and `hashCode`). + * + * Note: because of this extension, the key equality of Immutable.Map and the + * value equality of Immutable.Set will differ from ES6 Map and Set. + * + * ### Defining custom values + * + * The easiest way to describe the value an object represents is by implementing + * `valueOf`. For example, `Date` represents a value by returning a unix + * timestamp for `valueOf`: + * + * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... + * var date2 = new Date(1234567890000); + * date1.valueOf(); // 1234567890000 + * assert( date1 !== date2 ); + * assert( Immutable.is( date1, date2 ) ); + * + * Note: overriding `valueOf` may have other implications if you use this object + * where JavaScript expects a primitive, such as implicit string coercion. + * + * For more complex types, especially collections, implementing `valueOf` may + * not be performant. An alternative is to implement `equals` and `hashCode`. + * + * `equals` takes another object, presumably of similar type, and returns true + * if it is equal. Equality is symmetrical, so the same result should be + * returned if this and the argument are flipped. + * + * assert( a.equals(b) === b.equals(a) ); + * + * `hashCode` returns a 32bit integer number representing the object which will + * be used to determine how to store the value object in a Map or Set. You must + * provide both or neither methods, one must not exist without the other. + * + * Also, an important relationship between these methods must be upheld: if two + * values are equal, they *must* return the same hashCode. If the values are not + * equal, they might have the same hashCode; this is called a hash collision, + * and while undesirable for performance reasons, it is acceptable. + * + * if (a.equals(b)) { + * assert( a.hashCode() === b.hashCode() ); + * } + * + * All Immutable collections are Value Objects: they implement `equals()` + * and `hashCode()`. + */ +function is(valueA, valueB) { + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } - if (!isCollection(b) || - // @ts-expect-error size should exists on Collection - (a.size !== undefined && b.size !== undefined && a.size !== b.size) || - // @ts-expect-error __hash exists on Collection - (a.__hash !== undefined && - // @ts-expect-error __hash exists on Collection - b.__hash !== undefined && - // @ts-expect-error __hash exists on Collection - a.__hash !== b.__hash) || - isKeyed(a) !== isKeyed(b) || - isIndexed(a) !== isIndexed(b) || - // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid - isOrdered(a) !== isOrdered(b)) { + if (!valueA || !valueB) { return false; } - // @ts-expect-error size should exists on Collection - if (a.size === 0 && b.size === 0) { - return true; - } - var notAssociative = !isAssociative(a); - // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid - if (isOrdered(a)) { - var entries = a.entries(); - // @ts-expect-error need to cast as boolean - return (b.every(function (v, k) { - var entry = entries.next().value; - return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); - }) && entries.next().done); - } - var flipped = false; - if (a.size === undefined) { - // @ts-expect-error size should exists on Collection - if (b.size === undefined) { - if (typeof a.cacheResult === 'function') { - a.cacheResult(); - } - } - else { - flipped = true; - var _ = a; - a = b; - b = _; + if (typeof valueA.valueOf === 'function' && + typeof valueB.valueOf === 'function') { + valueA = valueA.valueOf(); + valueB = valueB.valueOf(); + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; } - } - var allEqual = true; - var bSize = - // @ts-expect-error b is Range | Repeat | Collection as it may have been flipped, and __iterate is valid - b.__iterate(function (v, k) { - if (notAssociative - ? // @ts-expect-error has exists on Collection - !a.has(v) - : flipped - ? // @ts-expect-error type of `get` does not "catch" the version with `notSetValue` - !is(v, a.get(k, NOT_SET)) - : // @ts-expect-error type of `get` does not "catch" the version with `notSetValue` - !is(a.get(k, NOT_SET), v)) { - allEqual = false; + if (!valueA || !valueB) { return false; } - }); - return (allEqual && - // @ts-expect-error size should exists on Collection - a.size === bSize); + } + return !!(isValueObject(valueA) && + isValueObject(valueB) && + valueA.equals(valueB)); } -/** - * Contributes additional methods to a constructor - */ -function mixin(ctor, -// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -methods) { - var keyCopier = function (key) { - // @ts-expect-error how to handle symbol ? - ctor.prototype[key] = methods[key]; - }; - Object.keys(methods).forEach(keyCopier); - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - Object.getOwnPropertySymbols && - Object.getOwnPropertySymbols(methods).forEach(keyCopier); - return ctor; +var imul = + typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 + ? Math.imul + : function imul(a, b) { + a |= 0; // int + b |= 0; // int + var c = a & 0xffff; + var d = b & 0xffff; + // Shift by 0 fixes the sign on the high part. + return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int + }; + +// v8 has an optimization for storing 31-bit signed numbers. +// Values which have either 00 or 11 as the high order bits qualify. +// This function drops the highest order bit in a signed number, maintaining +// the sign bit. +function smi(i32) { + return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff); } -function toJS(value) { - if (!value || typeof value !== 'object') { - return value; +var defaultValueOf = Object.prototype.valueOf; + +function hash(o) { + // eslint-disable-next-line eqeqeq + if (o == null) { + return hashNullish(o); } - if (!isCollection(value)) { - if (!isDataStructure(value)) { - return value; - } - value = Seq(value); + + if (typeof o.hashCode === 'function') { + // Drop any high bits from accidentally long hash codes. + return smi(o.hashCode(o)); } - if (isKeyed(value)) { - var result$1 = {}; - value.__iterate(function (v, k) { - result$1[k] = toJS(v); - }); - return result$1; + + var v = valueOf(o); + + // eslint-disable-next-line eqeqeq + if (v == null) { + return hashNullish(v); + } + + switch (typeof v) { + case 'boolean': + // The hash values for built-in constants are a 1 value for each 5-byte + // shift region expect for the first, which encodes the value. This + // reduces the odds of a hash collision for these common values. + return v ? 0x42108421 : 0x42108420; + case 'number': + return hashNumber(v); + case 'string': + return v.length > STRING_HASH_CACHE_MIN_STRLEN + ? cachedHashString(v) + : hashString(v); + case 'object': + case 'function': + return hashJSObj(v); + case 'symbol': + return hashSymbol(v); + default: + if (typeof v.toString === 'function') { + return hashString(v.toString()); + } + throw new Error('Value type ' + typeof v + ' cannot be hashed.'); } - var result = []; - value.__iterate(function (v) { - result.push(toJS(v)); - }); - return result; } -var Set = /*@__PURE__*/(function (SetCollection) { - function Set(value) { - // eslint-disable-next-line no-constructor-return - return value === undefined || value === null - ? emptySet() - : isSet(value) && !isOrdered(value) - ? value - : emptySet().withMutations(function (set) { - var iter = SetCollection(value); - assertNotInfinite(iter.size); - iter.forEach(function (v) { return set.add(v); }); - }); +function hashNullish(nullish) { + return nullish === null ? 0x42108422 : /* undefined */ 0x42108423; +} + +// Compress arbitrarily large numbers into smi hashes. +function hashNumber(n) { + if (n !== n || n === Infinity) { + return 0; + } + var hash = n | 0; + if (hash !== n) { + hash ^= n * 0xffffffff; + } + while (n > 0xffffffff) { + n /= 0xffffffff; + hash ^= n; } + return smi(hash); +} - if ( SetCollection ) Set.__proto__ = SetCollection; - Set.prototype = Object.create( SetCollection && SetCollection.prototype ); - Set.prototype.constructor = Set; +function cachedHashString(string) { + var hashed = stringHashCache[string]; + if (hashed === undefined) { + hashed = hashString(string); + if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { + STRING_HASH_CACHE_SIZE = 0; + stringHashCache = {}; + } + STRING_HASH_CACHE_SIZE++; + stringHashCache[string] = hashed; + } + return hashed; +} - Set.of = function of (/*...values*/) { - return this(arguments); - }; +// http://jsperf.com/hashing-strings +function hashString(string) { + // This is the hash from JVM + // The hash code for a string is computed as + // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], + // where s[i] is the ith character of the string and n is the length of + // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 + // (exclusive) by dropping high bits. + var hashed = 0; + for (var ii = 0; ii < string.length; ii++) { + hashed = (31 * hashed + string.charCodeAt(ii)) | 0; + } + return smi(hashed); +} - Set.fromKeys = function fromKeys (value) { - return this(KeyedCollection(value).keySeq()); - }; +function hashSymbol(sym) { + var hashed = symbolMap[sym]; + if (hashed !== undefined) { + return hashed; + } - Set.intersect = function intersect (sets) { - sets = Collection(sets).toArray(); - return sets.length - ? SetPrototype.intersect.apply(Set(sets.pop()), sets) - : emptySet(); - }; + hashed = nextHash(); - Set.union = function union (sets) { - sets = Collection(sets).toArray(); - return sets.length - ? SetPrototype.union.apply(Set(sets.pop()), sets) - : emptySet(); - }; + symbolMap[sym] = hashed; - Set.prototype.toString = function toString () { - return this.__toString('Set {', '}'); - }; + return hashed; +} - // @pragma Access +function hashJSObj(obj) { + var hashed; + if (usingWeakMap) { + hashed = weakMap.get(obj); + if (hashed !== undefined) { + return hashed; + } + } - Set.prototype.has = function has (value) { - return this._map.has(value); - }; + hashed = obj[UID_HASH_KEY]; + if (hashed !== undefined) { + return hashed; + } - // @pragma Modification + if (!canDefineProperty) { + hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; + if (hashed !== undefined) { + return hashed; + } - Set.prototype.add = function add (value) { - return updateSet(this, this._map.set(value, value)); - }; + hashed = getIENodeHash(obj); + if (hashed !== undefined) { + return hashed; + } + } - Set.prototype.remove = function remove (value) { - return updateSet(this, this._map.remove(value)); - }; + hashed = nextHash(); - Set.prototype.clear = function clear () { - return updateSet(this, this._map.clear()); - }; + if (usingWeakMap) { + weakMap.set(obj, hashed); + } else if (isExtensible !== undefined && isExtensible(obj) === false) { + throw new Error('Non-extensible objects are not allowed as keys.'); + } else if (canDefineProperty) { + Object.defineProperty(obj, UID_HASH_KEY, { + enumerable: false, + configurable: false, + writable: false, + value: hashed, + }); + } else if ( + obj.propertyIsEnumerable !== undefined && + obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable + ) { + // Since we can't define a non-enumerable property on the object + // we'll hijack one of the less-used non-enumerable properties to + // save our hash on it. Since this is a function it will not show up in + // `JSON.stringify` which is what we want. + obj.propertyIsEnumerable = function () { + return this.constructor.prototype.propertyIsEnumerable.apply( + this, + arguments + ); + }; + obj.propertyIsEnumerable[UID_HASH_KEY] = hashed; + } else if (obj.nodeType !== undefined) { + // At this point we couldn't get the IE `uniqueID` to use as a hash + // and we couldn't use a non-enumerable property to exploit the + // dontEnum bug so we simply add the `UID_HASH_KEY` on the node + // itself. + obj[UID_HASH_KEY] = hashed; + } else { + throw new Error('Unable to set a non-enumerable property on object.'); + } - // @pragma Composition + return hashed; +} - Set.prototype.map = function map (mapper, context) { - var this$1$1 = this; +// Get references to ES5 object methods. +var isExtensible = Object.isExtensible; - // keep track if the set is altered by the map function - var didChanges = false; +// True if Object.defineProperty works as expected. IE8 fails this test. +var canDefineProperty = (function () { + try { + Object.defineProperty({}, '@', {}); + return true; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } catch (e) { + return false; + } +})(); - var newMap = updateSet( - this, - this._map.mapEntries(function (ref) { - var v = ref[1]; +// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it +// and avoid memory leaks from the IE cloneNode bug. +function getIENodeHash(node) { + if (node && node.nodeType > 0) { + switch (node.nodeType) { + case 1: // Element + return node.uniqueID; + case 9: // Document + return node.documentElement && node.documentElement.uniqueID; + } + } +} - var mapped = mapper.call(context, v, v, this$1$1); +function valueOf(obj) { + return obj.valueOf !== defaultValueOf && typeof obj.valueOf === 'function' + ? obj.valueOf(obj) + : obj; +} - if (mapped !== v) { - didChanges = true; - } +function nextHash() { + var nextHash = ++_objHashUID; + if (_objHashUID & 0x40000000) { + _objHashUID = 0; + } + return nextHash; +} - return [mapped, mapped]; - }, context) - ); +// If possible, use a WeakMap. +var usingWeakMap = typeof WeakMap === 'function'; +var weakMap; +if (usingWeakMap) { + weakMap = new WeakMap(); +} - return didChanges ? newMap : this; +var symbolMap = Object.create(null); + +var _objHashUID = 0; + +var UID_HASH_KEY = '__immutablehash__'; +if (typeof Symbol === 'function') { + UID_HASH_KEY = Symbol(UID_HASH_KEY); +} + +var STRING_HASH_CACHE_MIN_STRLEN = 16; +var STRING_HASH_CACHE_MAX_SIZE = 255; +var STRING_HASH_CACHE_SIZE = 0; +var stringHashCache = {}; + +var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq) { + function ToKeyedSequence(indexed, useKeys) { + this._iter = indexed; + this._useKeys = useKeys; + this.size = indexed.size; + } + + if ( KeyedSeq ) ToKeyedSequence.__proto__ = KeyedSeq; + ToKeyedSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); + ToKeyedSequence.prototype.constructor = ToKeyedSequence; + + ToKeyedSequence.prototype.get = function get (key, notSetValue) { + return this._iter.get(key, notSetValue); }; - Set.prototype.union = function union () { - var iters = [], len = arguments.length; - while ( len-- ) iters[ len ] = arguments[ len ]; + ToKeyedSequence.prototype.has = function has (key) { + return this._iter.has(key); + }; - iters = iters.filter(function (x) { return x.size !== 0; }); - if (iters.length === 0) { - return this; - } - if (this.size === 0 && !this.__ownerID && iters.length === 1) { - return this.constructor(iters[0]); - } - return this.withMutations(function (set) { - for (var ii = 0; ii < iters.length; ii++) { - if (typeof iters[ii] === 'string') { - set.add(iters[ii]); - } else { - SetCollection(iters[ii]).forEach(function (value) { return set.add(value); }); - } - } - }); + ToKeyedSequence.prototype.valueSeq = function valueSeq () { + return this._iter.valueSeq(); }; - Set.prototype.intersect = function intersect () { - var iters = [], len = arguments.length; - while ( len-- ) iters[ len ] = arguments[ len ]; + ToKeyedSequence.prototype.reverse = function reverse () { + var this$1$1 = this; - if (iters.length === 0) { - return this; + var reversedSequence = reverseFactory(this, true); + if (!this._useKeys) { + reversedSequence.valueSeq = function () { return this$1$1._iter.toSeq().reverse(); }; } - iters = iters.map(function (iter) { return SetCollection(iter); }); - var toRemove = []; - this.forEach(function (value) { - if (!iters.every(function (iter) { return iter.includes(value); })) { - toRemove.push(value); - } - }); - return this.withMutations(function (set) { - toRemove.forEach(function (value) { - set.remove(value); - }); - }); + return reversedSequence; }; - Set.prototype.subtract = function subtract () { - var iters = [], len = arguments.length; - while ( len-- ) iters[ len ] = arguments[ len ]; + ToKeyedSequence.prototype.map = function map (mapper, context) { + var this$1$1 = this; - if (iters.length === 0) { - return this; + var mappedSequence = mapFactory(this, mapper, context); + if (!this._useKeys) { + mappedSequence.valueSeq = function () { return this$1$1._iter.toSeq().map(mapper, context); }; } - iters = iters.map(function (iter) { return SetCollection(iter); }); - var toRemove = []; - this.forEach(function (value) { - if (iters.some(function (iter) { return iter.includes(value); })) { - toRemove.push(value); - } - }); - return this.withMutations(function (set) { - toRemove.forEach(function (value) { - set.remove(value); - }); - }); + return mappedSequence; }; - Set.prototype.sort = function sort (comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator)); + ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; + + return this._iter.__iterate(function (v, k) { return fn(v, k, this$1$1); }, reverse); }; - Set.prototype.sortBy = function sortBy (mapper, comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator, mapper)); + ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) { + return this._iter.__iterator(type, reverse); }; - Set.prototype.wasAltered = function wasAltered () { - return this._map.wasAltered(); + return ToKeyedSequence; +}(KeyedSeq)); +ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true; + +var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq) { + function ToIndexedSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + if ( IndexedSeq ) ToIndexedSequence.__proto__ = IndexedSeq; + ToIndexedSequence.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); + ToIndexedSequence.prototype.constructor = ToIndexedSequence; + + ToIndexedSequence.prototype.includes = function includes (value) { + return this._iter.includes(value); }; - Set.prototype.__iterate = function __iterate (fn, reverse) { + ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) { var this$1$1 = this; - return this._map.__iterate(function (k) { return fn(k, k, this$1$1); }, reverse); + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + reverse && ensureSize(this); + return this._iter.__iterate( + function (v) { return fn(v, reverse ? this$1$1.size - ++i : i++, this$1$1); }, + reverse + ); }; - Set.prototype.__iterator = function __iterator (type, reverse) { - return this._map.__iterator(type, reverse); + ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) { + var this$1$1 = this; + + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + reverse && ensureSize(this); + return new Iterator(function () { + var step = iterator.next(); + return step.done + ? step + : iteratorValue( + type, + reverse ? this$1$1.size - ++i : i++, + step.value, + step + ); + }); }; - Set.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - var newMap = this._map.__ensureOwner(ownerID); - if (!ownerID) { - if (this.size === 0) { - return this.__empty(); - } - this.__ownerID = ownerID; - this._map = newMap; - return this; - } - return this.__make(newMap, ownerID); + return ToIndexedSequence; +}(IndexedSeq)); + +var ToSetSequence = /*@__PURE__*/(function (SetSeq) { + function ToSetSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + if ( SetSeq ) ToSetSequence.__proto__ = SetSeq; + ToSetSequence.prototype = Object.create( SetSeq && SetSeq.prototype ); + ToSetSequence.prototype.constructor = ToSetSequence; + + ToSetSequence.prototype.has = function has (key) { + return this._iter.includes(key); }; - return Set; -}(SetCollection)); + ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; -Set.isSet = isSet; + return this._iter.__iterate(function (v) { return fn(v, v, this$1$1); }, reverse); + }; -var SetPrototype = Set.prototype; -SetPrototype[IS_SET_SYMBOL] = true; -SetPrototype[DELETE] = SetPrototype.remove; -SetPrototype.merge = SetPrototype.concat = SetPrototype.union; -SetPrototype.withMutations = withMutations; -SetPrototype.asImmutable = asImmutable; -SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable; -SetPrototype['@@transducer/step'] = function (result, arr) { - return result.add(arr); -}; -SetPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; + ToSetSequence.prototype.__iterator = function __iterator (type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function () { + var step = iterator.next(); + return step.done + ? step + : iteratorValue(type, step.value, step.value, step); + }); + }; -SetPrototype.__empty = emptySet; -SetPrototype.__make = makeSet; + return ToSetSequence; +}(SetSeq)); -function updateSet(set, newMap) { - if (set.__ownerID) { - set.size = newMap.size; - set._map = newMap; - return set; +var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq) { + function FromEntriesSequence(entries) { + this._iter = entries; + this.size = entries.size; } - return newMap === set._map - ? set - : newMap.size === 0 - ? set.__empty() - : set.__make(newMap); -} - -function makeSet(map, ownerID) { - var set = Object.create(SetPrototype); - set.size = map ? map.size : 0; - set._map = map; - set.__ownerID = ownerID; - return set; -} -var EMPTY_SET; -function emptySet() { - return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); -} + if ( KeyedSeq ) FromEntriesSequence.__proto__ = KeyedSeq; + FromEntriesSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); + FromEntriesSequence.prototype.constructor = FromEntriesSequence; -/** - * Returns a lazy seq of nums from start (inclusive) to end - * (exclusive), by step, where start defaults to 0, step to 1, and end to - * infinity. When start is equal to end, returns empty list. - */ -var Range = /*@__PURE__*/(function (IndexedSeq) { - function Range(start, end, step) { - if ( step === void 0 ) step = 1; + FromEntriesSequence.prototype.entrySeq = function entrySeq () { + return this._iter.toSeq(); + }; - if (!(this instanceof Range)) { - // eslint-disable-next-line no-constructor-return - return new Range(start, end, step); - } - invariant(step !== 0, 'Cannot step a Range by 0'); - invariant( - start !== undefined, - 'You must define a start value when using Range' - ); - invariant( - end !== undefined, - 'You must define an end value when using Range' - ); + FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; - step = Math.abs(step); - if (end < start) { - step = -step; - } - this._start = start; - this._end = end; - this._step = step; - this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); - if (this.size === 0) { - if (EMPTY_RANGE) { - // eslint-disable-next-line no-constructor-return - return EMPTY_RANGE; + return this._iter.__iterate(function (entry) { + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedCollection = isCollection(entry); + return fn( + indexedCollection ? entry.get(1) : entry[1], + indexedCollection ? entry.get(0) : entry[0], + this$1$1 + ); } - // eslint-disable-next-line @typescript-eslint/no-this-alias - EMPTY_RANGE = this; - } - } - - if ( IndexedSeq ) Range.__proto__ = IndexedSeq; - Range.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); - Range.prototype.constructor = Range; - - Range.prototype.toString = function toString () { - return this.size === 0 - ? 'Range []' - : ("Range [ " + (this._start) + "..." + (this._end) + (this._step !== 1 ? ' by ' + this._step : '') + " ]"); + }, reverse); }; - Range.prototype.get = function get (index, notSetValue) { - return this.has(index) - ? this._start + wrapIndex(this, index) * this._step - : notSetValue; + FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function () { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedCollection = isCollection(entry); + return iteratorValue( + type, + indexedCollection ? entry.get(0) : entry[0], + indexedCollection ? entry.get(1) : entry[1], + step + ); + } + } + }); }; - Range.prototype.includes = function includes (searchValue) { - var possibleIndex = (searchValue - this._start) / this._step; - return ( - possibleIndex >= 0 && - possibleIndex < this.size && - possibleIndex === Math.floor(possibleIndex) - ); + return FromEntriesSequence; +}(KeyedSeq)); + +ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough; + +function flipFactory(collection) { + var flipSequence = makeSequence(collection); + flipSequence._iter = collection; + flipSequence.size = collection.size; + flipSequence.flip = function () { return collection; }; + flipSequence.reverse = function () { + var reversedSequence = collection.reverse.apply(this); // super.reverse() + reversedSequence.flip = function () { return collection.reverse(); }; + return reversedSequence; }; + flipSequence.has = function (key) { return collection.includes(key); }; + flipSequence.includes = function (key) { return collection.has(key); }; + flipSequence.cacheResult = cacheResultThrough; + flipSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - Range.prototype.slice = function slice (begin, end) { - if (wholeSlice(begin, end, this.size)) { - return this; - } - begin = resolveBegin(begin, this.size); - end = resolveEnd(end, this.size); - if (end <= begin) { - return new Range(0, 0); + return collection.__iterate(function (v, k) { return fn(k, v, this$1$1) !== false; }, reverse); + }; + flipSequence.__iteratorUncached = function (type, reverse) { + if (type === ITERATE_ENTRIES) { + var iterator = collection.__iterator(type, reverse); + return new Iterator(function () { + var step = iterator.next(); + if (!step.done) { + var k = step.value[0]; + step.value[0] = step.value[1]; + step.value[1] = k; + } + return step; + }); } - return new Range( - this.get(begin, this._end), - this.get(end, this._end), - this._step + return collection.__iterator( + type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, + reverse ); }; + return flipSequence; +} - Range.prototype.indexOf = function indexOf (searchValue) { - var offsetValue = searchValue - this._start; - if (offsetValue % this._step === 0) { - var index = offsetValue / this._step; - if (index >= 0 && index < this.size) { - return index; - } - } - return -1; +function mapFactory(collection, mapper, context) { + var mappedSequence = makeSequence(collection); + mappedSequence.size = collection.size; + mappedSequence.has = function (key) { return collection.has(key); }; + mappedSequence.get = function (key, notSetValue) { + var v = collection.get(key, NOT_SET); + return v === NOT_SET + ? notSetValue + : mapper.call(context, v, key, collection); }; + mappedSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - Range.prototype.lastIndexOf = function lastIndexOf (searchValue) { - return this.indexOf(searchValue); + return collection.__iterate( + function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1$1) !== false; }, + reverse + ); }; - - Range.prototype.__iterate = function __iterate (fn, reverse) { - var size = this.size; - var step = this._step; - var value = reverse ? this._start + (size - 1) * step : this._start; - var i = 0; - while (i !== size) { - if (fn(value, reverse ? size - ++i : i++, this) === false) { - break; + mappedSequence.__iteratorUncached = function (type, reverse) { + var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); + return new Iterator(function () { + var step = iterator.next(); + if (step.done) { + return step; } - value += reverse ? -step : step; - } - return i; + var entry = step.value; + var key = entry[0]; + return iteratorValue( + type, + key, + mapper.call(context, entry[1], key, collection), + step + ); + }); }; + return mappedSequence; +} - Range.prototype.__iterator = function __iterator (type, reverse) { - var size = this.size; - var step = this._step; - var value = reverse ? this._start + (size - 1) * step : this._start; +function reverseFactory(collection, useKeys) { + var this$1$1 = this; + + var reversedSequence = makeSequence(collection); + reversedSequence._iter = collection; + reversedSequence.size = collection.size; + reversedSequence.reverse = function () { return collection; }; + if (collection.flip) { + reversedSequence.flip = function () { + var flipSequence = flipFactory(collection); + flipSequence.reverse = function () { return collection.flip(); }; + return flipSequence; + }; + } + reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); }; + reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); }; + reversedSequence.includes = function (value) { return collection.includes(value); }; + reversedSequence.cacheResult = cacheResultThrough; + reversedSequence.__iterate = function (fn, reverse) { + var this$1$1 = this; + + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + reverse && ensureSize(collection); + return collection.__iterate( + function (v, k) { return fn(v, useKeys ? k : reverse ? this$1$1.size - ++i : i++, this$1$1); }, + !reverse + ); + }; + reversedSequence.__iterator = function (type, reverse) { var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + reverse && ensureSize(collection); + var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse); return new Iterator(function () { - if (i === size) { - return iteratorDone(); + var step = iterator.next(); + if (step.done) { + return step; } - var v = value; - value += reverse ? -step : step; - return iteratorValue(type, reverse ? size - ++i : i++, v); + var entry = step.value; + return iteratorValue( + type, + useKeys ? entry[0] : reverse ? this$1$1.size - ++i : i++, + entry[1], + step + ); }); }; + return reversedSequence; +} - Range.prototype.equals = function equals (other) { - return other instanceof Range - ? this._start === other._start && - this._end === other._end && - this._step === other._step - : deepEqual(this, other); - }; - - return Range; -}(IndexedSeq)); - -var EMPTY_RANGE; +function filterFactory(collection, predicate, context, useKeys) { + var filterSequence = makeSequence(collection); + if (useKeys) { + filterSequence.has = function (key) { + var v = collection.get(key, NOT_SET); + return v !== NOT_SET && !!predicate.call(context, v, key, collection); + }; + filterSequence.get = function (key, notSetValue) { + var v = collection.get(key, NOT_SET); + return v !== NOT_SET && predicate.call(context, v, key, collection) + ? v + : notSetValue; + }; + } + filterSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; -/** - * Returns the value at the provided key path starting at the provided - * collection, or notSetValue if the key path is not defined. - * - * A functional alternative to `collection.getIn(keypath)` which will also - * work with plain Objects and Arrays. - */ -function getIn$1(collection, searchKeyPath, notSetValue) { - var keyPath = coerceKeyPath(searchKeyPath); - var i = 0; - while (i !== keyPath.length) { - // @ts-expect-error keyPath[i++] can not be undefined by design - collection = get(collection, keyPath[i++], NOT_SET); - if (collection === NOT_SET) { - return notSetValue; + var iterations = 0; + collection.__iterate(function (v, k, c) { + if (predicate.call(context, v, k, c)) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$1$1); + } + }, reverse); + return iterations; + }; + filterSequence.__iteratorUncached = function (type, reverse) { + var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); + var iterations = 0; + return new Iterator(function () { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; } - } - return collection; -} - -function getIn(searchKeyPath, notSetValue) { - return getIn$1(this, searchKeyPath, notSetValue); + var entry = step.value; + var key = entry[0]; + var value = entry[1]; + if (predicate.call(context, value, key, collection)) { + return iteratorValue(type, useKeys ? key : iterations++, value, step); + } + } + }); + }; + return filterSequence; } -/** - * Returns true if the key path is defined in the provided collection. - * - * A functional alternative to `collection.hasIn(keypath)` which will also - * work with plain Objects and Arrays. - */ -function hasIn$1(collection, keyPath) { - return getIn$1(collection, keyPath, NOT_SET) !== NOT_SET; +function countByFactory(collection, grouper, context) { + var groups = Map().asMutable(); + collection.__iterate(function (v, k) { + groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; }); + }); + return groups.asImmutable(); } -function hasIn(searchKeyPath) { - return hasIn$1(this, searchKeyPath); +function groupByFactory(collection, grouper, context) { + var isKeyedIter = isKeyed(collection); + var groups = (isOrdered(collection) ? OrderedMap() : Map()).asMutable(); + collection.__iterate(function (v, k) { + groups.update( + grouper.call(context, v, k, collection), + function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); } + ); + }); + var coerce = collectionClass(collection); + return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable(); } -function toObject() { - assertNotInfinite(this.size); - var object = {}; - this.__iterate(function (v, k) { - object[k] = v; +function partitionFactory(collection, predicate, context) { + var isKeyedIter = isKeyed(collection); + var groups = [[], []]; + collection.__iterate(function (v, k) { + groups[predicate.call(context, v, k, collection) ? 1 : 0].push( + isKeyedIter ? [k, v] : v + ); }); - return object; + var coerce = collectionClass(collection); + return groups.map(function (arr) { return reify(collection, coerce(arr)); }); } -Collection.Iterator = Iterator; +function sliceFactory(collection, begin, end, useKeys) { + var originalSize = collection.size; -mixin(Collection, { - // ### Conversion to other types + if (wholeSlice(begin, end, originalSize)) { + return collection; + } - toArray: function toArray() { - assertNotInfinite(this.size); - var array = new Array(this.size || 0); - var useTuples = isKeyed(this); - var i = 0; - this.__iterate(function (v, k) { - // Keyed collections produce an array of tuples. - array[i++] = useTuples ? [k, v] : v; - }); - return array; - }, + // begin or end can not be resolved if they were provided as negative numbers and + // this collection's size is unknown. In that case, cache first so there is + // a known size and these do not resolve to NaN. + if (typeof originalSize === 'undefined' && (begin < 0 || end < 0)) { + return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys); + } - toIndexedSeq: function toIndexedSeq() { - return new ToIndexedSequence(this); - }, + var resolvedBegin = resolveBegin(begin, originalSize); + var resolvedEnd = resolveEnd(end, originalSize); - toJS: function toJS$1() { - return toJS(this); - }, + // Note: resolvedEnd is undefined when the original sequence's length is + // unknown and this slice did not supply an end and should contain all + // elements after resolvedBegin. + // In that case, resolvedSize will be NaN and sliceSize will remain undefined. + var resolvedSize = resolvedEnd - resolvedBegin; + var sliceSize; + if (resolvedSize === resolvedSize) { + sliceSize = resolvedSize < 0 ? 0 : resolvedSize; + } - toKeyedSeq: function toKeyedSeq() { - return new ToKeyedSequence(this, true); - }, + var sliceSeq = makeSequence(collection); - toMap: function toMap() { - // Use Late Binding here to solve the circular dependency. - return Map(this.toKeyedSeq()); - }, + // If collection.size is undefined, the size of the realized sliceSeq is + // unknown at this point unless the number of items to slice is 0 + sliceSeq.size = + sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined; - toObject: toObject, + if (!useKeys && isSeq(collection) && sliceSize >= 0) { + sliceSeq.get = function (index, notSetValue) { + index = wrapIndex(this, index); + return index >= 0 && index < sliceSize + ? collection.get(index + resolvedBegin, notSetValue) + : notSetValue; + }; + } - toOrderedMap: function toOrderedMap() { - // Use Late Binding here to solve the circular dependency. - return OrderedMap(this.toKeyedSeq()); - }, + sliceSeq.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - toOrderedSet: function toOrderedSet() { - // Use Late Binding here to solve the circular dependency. - return OrderedSet(isKeyed(this) ? this.valueSeq() : this); - }, + if (sliceSize === 0) { + return 0; + } + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var skipped = 0; + var isSkipping = true; + var iterations = 0; + collection.__iterate(function (v, k) { + if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { + iterations++; + return ( + fn(v, useKeys ? k : iterations - 1, this$1$1) !== false && + iterations !== sliceSize + ); + } + }); + return iterations; + }; - toSet: function toSet() { - // Use Late Binding here to solve the circular dependency. - return Set(isKeyed(this) ? this.valueSeq() : this); - }, + sliceSeq.__iteratorUncached = function (type, reverse) { + if (sliceSize !== 0 && reverse) { + return this.cacheResult().__iterator(type, reverse); + } + // Don't bother instantiating parent iterator if taking 0. + if (sliceSize === 0) { + return new Iterator(iteratorDone); + } + var iterator = collection.__iterator(type, reverse); + var skipped = 0; + var iterations = 0; + return new Iterator(function () { + while (skipped++ < resolvedBegin) { + iterator.next(); + } + if (++iterations > sliceSize) { + return iteratorDone(); + } + var step = iterator.next(); + if (useKeys || type === ITERATE_VALUES || step.done) { + return step; + } + if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations - 1, undefined, step); + } + return iteratorValue(type, iterations - 1, step.value[1], step); + }); + }; - toSetSeq: function toSetSeq() { - return new ToSetSequence(this); - }, + return sliceSeq; +} - toSeq: function toSeq() { - return isIndexed(this) - ? this.toIndexedSeq() - : isKeyed(this) - ? this.toKeyedSeq() - : this.toSetSeq(); - }, +function takeWhileFactory(collection, predicate, context) { + var takeSequence = makeSequence(collection); + takeSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - toStack: function toStack() { - // Use Late Binding here to solve the circular dependency. - return Stack(isKeyed(this) ? this.valueSeq() : this); - }, - - toList: function toList() { - // Use Late Binding here to solve the circular dependency. - return List(isKeyed(this) ? this.valueSeq() : this); - }, - - // ### Common JavaScript methods and properties - - toString: function toString() { - return '[Collection]'; - }, - - __toString: function __toString(head, tail) { - if (this.size === 0) { - return head + tail; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); } - return ( - head + - ' ' + - this.toSeq().map(this.__toStringMapper).join(', ') + - ' ' + - tail + var iterations = 0; + collection.__iterate( + function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1$1); } ); - }, - - // ### ES6 Collection methods (ES6 Array and Map) - - concat: function concat() { - var values = [], len = arguments.length; - while ( len-- ) values[ len ] = arguments[ len ]; - - return reify(this, concatFactory(this, values)); - }, - - includes: function includes(searchValue) { - return this.some(function (value) { return is(value, searchValue); }); - }, - - entries: function entries() { - return this.__iterator(ITERATE_ENTRIES); - }, + return iterations; + }; + takeSequence.__iteratorUncached = function (type, reverse) { + var this$1$1 = this; - every: function every(predicate, context) { - assertNotInfinite(this.size); - var returnValue = true; - this.__iterate(function (v, k, c) { - if (!predicate.call(context, v, k, c)) { - returnValue = false; - return false; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); + var iterating = true; + return new Iterator(function () { + if (!iterating) { + return iteratorDone(); + } + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var k = entry[0]; + var v = entry[1]; + if (!predicate.call(context, v, k, this$1$1)) { + iterating = false; + return iteratorDone(); } + return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); - return returnValue; - }, - - filter: function filter(predicate, context) { - return reify(this, filterFactory(this, predicate, context, true)); - }, + }; + return takeSequence; +} - partition: function partition(predicate, context) { - return partitionFactory(this, predicate, context); - }, +function skipWhileFactory(collection, predicate, context, useKeys) { + var skipSequence = makeSequence(collection); + skipSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - find: function find(predicate, context, notSetValue) { - var entry = this.findEntry(predicate, context); - return entry ? entry[1] : notSetValue; - }, + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var isSkipping = true; + var iterations = 0; + collection.__iterate(function (v, k, c) { + if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$1$1); + } + }); + return iterations; + }; + skipSequence.__iteratorUncached = function (type, reverse) { + var this$1$1 = this; - forEach: function forEach(sideEffect, context) { - assertNotInfinite(this.size); - return this.__iterate(context ? sideEffect.bind(context) : sideEffect); - }, + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); + var skipping = true; + var iterations = 0; + return new Iterator(function () { + var step; + var k; + var v; + do { + step = iterator.next(); + if (step.done) { + if (useKeys || type === ITERATE_VALUES) { + return step; + } + if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations++, undefined, step); + } + return iteratorValue(type, iterations++, step.value[1], step); + } + var entry = step.value; + k = entry[0]; + v = entry[1]; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + skipping && (skipping = predicate.call(context, v, k, this$1$1)); + } while (skipping); + return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); + }); + }; + return skipSequence; +} - join: function join(separator) { - assertNotInfinite(this.size); - separator = separator !== undefined ? '' + separator : ','; - var joined = ''; - var isFirst = true; - this.__iterate(function (v) { - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - isFirst ? (isFirst = false) : (joined += separator); - joined += v !== null && v !== undefined ? v.toString() : ''; +var ConcatSeq = /*@__PURE__*/(function (Seq) { + function ConcatSeq(iterables) { + this._wrappedIterables = iterables.flatMap(function (iterable) { + if (iterable._wrappedIterables) { + return iterable._wrappedIterables; + } + return [iterable]; }); - return joined; - }, + this.size = this._wrappedIterables.reduce(function (sum, iterable) { + if (sum !== undefined) { + var size = iterable.size; + if (size !== undefined) { + return sum + size; + } + } + }, 0); + this[IS_KEYED_SYMBOL] = this._wrappedIterables[0][IS_KEYED_SYMBOL]; + this[IS_INDEXED_SYMBOL] = this._wrappedIterables[0][IS_INDEXED_SYMBOL]; + this[IS_ORDERED_SYMBOL] = this._wrappedIterables[0][IS_ORDERED_SYMBOL]; + } - keys: function keys() { - return this.__iterator(ITERATE_KEYS); - }, + if ( Seq ) ConcatSeq.__proto__ = Seq; + ConcatSeq.prototype = Object.create( Seq && Seq.prototype ); + ConcatSeq.prototype.constructor = ConcatSeq; - map: function map(mapper, context) { - return reify(this, mapFactory(this, mapper, context)); - }, + ConcatSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) { + if (this._wrappedIterables.length === 0) { + return; + } - reduce: function reduce$1(reducer, initialReduction, context) { - return reduce( - this, - reducer, - initialReduction, - context, - arguments.length < 2, - false - ); - }, + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } - reduceRight: function reduceRight(reducer, initialReduction, context) { - return reduce( - this, - reducer, - initialReduction, - context, - arguments.length < 2, - true + var iterableIndex = 0; + var useKeys = isKeyed(this); + var iteratorType = useKeys ? ITERATE_ENTRIES : ITERATE_VALUES; + var currentIterator = this._wrappedIterables[iterableIndex].__iterator( + iteratorType, + reverse ); - }, - - reverse: function reverse() { - return reify(this, reverseFactory(this, true)); - }, - - slice: function slice(begin, end) { - return reify(this, sliceFactory(this, begin, end, true)); - }, - some: function some(predicate, context) { - assertNotInfinite(this.size); - var returnValue = false; - this.__iterate(function (v, k, c) { - if (predicate.call(context, v, k, c)) { - returnValue = true; - return false; + var keepGoing = true; + var index = 0; + while (keepGoing) { + var next = currentIterator.next(); + while (next.done) { + iterableIndex++; + if (iterableIndex === this._wrappedIterables.length) { + return index; + } + currentIterator = this._wrappedIterables[iterableIndex].__iterator( + iteratorType, + reverse + ); + next = currentIterator.next(); } - }); - return returnValue; - }, - - sort: function sort(comparator) { - return reify(this, sortFactory(this, comparator)); - }, - - values: function values() { - return this.__iterator(ITERATE_VALUES); - }, + var fnResult = useKeys + ? fn(next.value[1], next.value[0], this) + : fn(next.value, index, this); + keepGoing = fnResult !== false; + index++; + } + return index; + }; - // ### More sequential methods + ConcatSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) { + var this$1$1 = this; - butLast: function butLast() { - return this.slice(0, -1); - }, + if (this._wrappedIterables.length === 0) { + return new Iterator(iteratorDone); + } - isEmpty: function isEmpty() { - return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; }); - }, + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } - count: function count(predicate, context) { - return ensureSize( - predicate ? this.toSeq().filter(predicate, context) : this + var iterableIndex = 0; + var currentIterator = this._wrappedIterables[iterableIndex].__iterator( + type, + reverse ); - }, + return new Iterator(function () { + var next = currentIterator.next(); + while (next.done) { + iterableIndex++; + if (iterableIndex === this$1$1._wrappedIterables.length) { + return next; + } + currentIterator = this$1$1._wrappedIterables[iterableIndex].__iterator( + type, + reverse + ); + next = currentIterator.next(); + } + return next; + }); + }; - countBy: function countBy(grouper, context) { - return countByFactory(this, grouper, context); - }, + return ConcatSeq; +}(Seq)); - equals: function equals(other) { - return deepEqual(this, other); - }, +function concatFactory(collection, values) { + var isKeyedCollection = isKeyed(collection); + var iters = [collection] + .concat(values) + .map(function (v) { + if (!isCollection(v)) { + v = isKeyedCollection + ? keyedSeqFromValue(v) + : indexedSeqFromValue(Array.isArray(v) ? v : [v]); + } else if (isKeyedCollection) { + v = KeyedCollection(v); + } + return v; + }) + .filter(function (v) { return v.size !== 0; }); - entrySeq: function entrySeq() { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var collection = this; - if (collection._cache) { - // We cache as an entries array, so we can just return the cache! - return new ArraySeq(collection._cache); + if (iters.length === 0) { + return collection; + } + + if (iters.length === 1) { + var singleton = iters[0]; + if ( + singleton === collection || + (isKeyedCollection && isKeyed(singleton)) || + (isIndexed(collection) && isIndexed(singleton)) + ) { + return singleton; } - var entriesSequence = collection.toSeq().map(entryMapper).toIndexedSeq(); - entriesSequence.fromEntrySeq = function () { return collection.toSeq(); }; - return entriesSequence; - }, + } - filterNot: function filterNot(predicate, context) { - return this.filter(not(predicate), context); - }, + return new ConcatSeq(iters); +} - findEntry: function findEntry(predicate, context, notSetValue) { - var found = notSetValue; - this.__iterate(function (v, k, c) { - if (predicate.call(context, v, k, c)) { - found = [k, v]; - return false; +function flattenFactory(collection, depth, useKeys) { + var flatSequence = makeSequence(collection); + flatSequence.__iterateUncached = function (fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterations = 0; + var stopped = false; + function flatDeep(iter, currentDepth) { + iter.__iterate(function (v, k) { + if ((!depth || currentDepth < depth) && isCollection(v)) { + flatDeep(v, currentDepth + 1); + } else { + iterations++; + if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) { + stopped = true; + } + } + return !stopped; + }, reverse); + } + flatDeep(collection, 0); + return iterations; + }; + flatSequence.__iteratorUncached = function (type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = collection.__iterator(type, reverse); + var stack = []; + var iterations = 0; + return new Iterator(function () { + while (iterator) { + var step = iterator.next(); + if (step.done !== false) { + iterator = stack.pop(); + continue; + } + var v = step.value; + if (type === ITERATE_ENTRIES) { + v = v[1]; + } + if ((!depth || stack.length < depth) && isCollection(v)) { + stack.push(iterator); + iterator = v.__iterator(type, reverse); + } else { + return useKeys ? step : iteratorValue(type, iterations++, v, step); + } } + return iteratorDone(); }); - return found; - }, + }; + return flatSequence; +} - findKey: function findKey(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry && entry[0]; - }, +function flatMapFactory(collection, mapper, context) { + var coerce = collectionClass(collection); + return collection + .toSeq() + .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); }) + .flatten(true); +} - findLast: function findLast(predicate, context, notSetValue) { - return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); - }, +function interposeFactory(collection, separator) { + var interposedSequence = makeSequence(collection); + interposedSequence.size = collection.size && collection.size * 2 - 1; + interposedSequence.__iterateUncached = function (fn, reverse) { + var this$1$1 = this; - findLastEntry: function findLastEntry(predicate, context, notSetValue) { - return this.toKeyedSeq() - .reverse() - .findEntry(predicate, context, notSetValue); - }, + var iterations = 0; + collection.__iterate( + function (v) { return (!iterations || fn(separator, iterations++, this$1$1) !== false) && + fn(v, iterations++, this$1$1) !== false; }, + reverse + ); + return iterations; + }; + interposedSequence.__iteratorUncached = function (type, reverse) { + var iterator = collection.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + var step; + return new Iterator(function () { + if (!step || iterations % 2) { + step = iterator.next(); + if (step.done) { + return step; + } + } + return iterations % 2 + ? iteratorValue(type, iterations++, separator) + : iteratorValue(type, iterations++, step.value, step); + }); + }; + return interposedSequence; +} - findLastKey: function findLastKey(predicate, context) { - return this.toKeyedSeq().reverse().findKey(predicate, context); - }, +function sortFactory(collection, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + var isKeyedCollection = isKeyed(collection); + var index = 0; + var entries = collection + .toSeq() + .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; }) + .valueSeq() + .toArray(); + entries + .sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }) + .forEach( + isKeyedCollection + ? function (v, i) { + entries[i].length = 2; + } + : function (v, i) { + entries[i] = v[1]; + } + ); + return isKeyedCollection + ? KeyedSeq(entries) + : isIndexed(collection) + ? IndexedSeq(entries) + : SetSeq(entries); +} - first: function first(notSetValue) { - return this.find(returnTrue, null, notSetValue); - }, +function maxFactory(collection, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + if (mapper) { + var entry = collection + .toSeq() + .map(function (v, k) { return [v, mapper(v, k, collection)]; }) + .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); }); + return entry && entry[0]; + } + return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); }); +} - flatMap: function flatMap(mapper, context) { - return reify(this, flatMapFactory(this, mapper, context)); - }, - - flatten: function flatten(depth) { - return reify(this, flattenFactory(this, depth, true)); - }, +function maxCompare(comparator, a, b) { + var comp = comparator(b, a); + // b is considered the new max if the comparator declares them equal, but + // they are not equal and b is in fact a nullish value. + return ( + (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || + comp > 0 + ); +} - fromEntrySeq: function fromEntrySeq() { - return new FromEntriesSequence(this); - }, +function zipWithFactory(keyIter, zipper, iters, zipAll) { + var zipSequence = makeSequence(keyIter); + var sizes = new ArraySeq(iters).map(function (i) { return i.size; }); + zipSequence.size = zipAll ? sizes.max() : sizes.min(); + // Note: this a generic base implementation of __iterate in terms of + // __iterator which may be more generically useful in the future. + zipSequence.__iterate = function (fn, reverse) { + /* generic: + var iterator = this.__iterator(ITERATE_ENTRIES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + iterations++; + if (fn(step.value[1], step.value[0], this) === false) { + break; + } + } + return iterations; + */ + // indexed: + var iterator = this.__iterator(ITERATE_VALUES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + return iterations; + }; + zipSequence.__iteratorUncached = function (type, reverse) { + var iterators = iters.map( + function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); } + ); + var iterations = 0; + var isDone = false; + return new Iterator(function () { + var steps; + if (!isDone) { + steps = iterators.map(function (i) { return i.next(); }); + isDone = zipAll + ? steps.every(function (s) { return s.done; }) + : steps.some(function (s) { return s.done; }); + } + if (isDone) { + return iteratorDone(); + } + return iteratorValue( + type, + iterations++, + zipper.apply( + null, + steps.map(function (s) { return s.value; }) + ) + ); + }); + }; + return zipSequence; +} - get: function get(searchKey, notSetValue) { - return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue); - }, +// #pragma Helper Functions - getIn: getIn, +function reify(iter, seq) { + return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq); +} - groupBy: function groupBy(grouper, context) { - return groupByFactory(this, grouper, context); - }, +function validateEntry(entry) { + if (entry !== Object(entry)) { + throw new TypeError('Expected [K, V] tuple: ' + entry); + } +} - has: function has(searchKey) { - return this.get(searchKey, NOT_SET) !== NOT_SET; - }, +function collectionClass(collection) { + return isKeyed(collection) + ? KeyedCollection + : isIndexed(collection) + ? IndexedCollection + : SetCollection; +} - hasIn: hasIn, +function makeSequence(collection) { + return Object.create( + (isKeyed(collection) + ? KeyedSeq + : isIndexed(collection) + ? IndexedSeq + : SetSeq + ).prototype + ); +} - isSubset: function isSubset(iter) { - iter = typeof iter.includes === 'function' ? iter : Collection(iter); - return this.every(function (value) { return iter.includes(value); }); - }, +function cacheResultThrough() { + if (this._iter.cacheResult) { + this._iter.cacheResult(); + this.size = this._iter.size; + return this; + } + return Seq.prototype.cacheResult.call(this); +} - isSuperset: function isSuperset(iter) { - iter = typeof iter.isSubset === 'function' ? iter : Collection(iter); - return iter.isSubset(this); - }, +function defaultComparator(a, b) { + if (a === undefined && b === undefined) { + return 0; + } - keyOf: function keyOf(searchValue) { - return this.findKey(function (value) { return is(value, searchValue); }); - }, + if (a === undefined) { + return 1; + } - keySeq: function keySeq() { - return this.toSeq().map(keyMapper).toIndexedSeq(); - }, + if (b === undefined) { + return -1; + } - last: function last(notSetValue) { - return this.toSeq().reverse().first(notSetValue); - }, + return a > b ? 1 : a < b ? -1 : 0; +} - lastKeyOf: function lastKeyOf(searchValue) { - return this.toKeyedSeq().reverse().keyOf(searchValue); - }, +// http://jsperf.com/copy-array-inline +function arrCopy(arr, offset) { + offset = offset || 0; + var len = Math.max(0, arr.length - offset); + var newArr = new Array(len); + for (var ii = 0; ii < len; ii++) { + // @ts-expect-error We may want to guard for undefined values with `if (arr[ii + offset] !== undefined`, but ths should not happen by design + newArr[ii] = arr[ii + offset]; + } + return newArr; +} - max: function max(comparator) { - return maxFactory(this, comparator); - }, +function invariant(condition, error) { + if (!condition) + { throw new Error(error); } +} - maxBy: function maxBy(mapper, comparator) { - return maxFactory(this, comparator, mapper); - }, +function assertNotInfinite(size) { + invariant(size !== Infinity, 'Cannot perform this action with an infinite size.'); +} - min: function min(comparator) { - return maxFactory( - this, - comparator ? neg(comparator) : defaultNegComparator - ); - }, +function coerceKeyPath(keyPath) { + if (isArrayLike(keyPath) && typeof keyPath !== 'string') { + return keyPath; + } + if (isOrdered(keyPath)) { + return keyPath.toArray(); + } + throw new TypeError('Invalid keyPath: expected Ordered Collection or Array: ' + keyPath); +} - minBy: function minBy(mapper, comparator) { - return maxFactory( - this, - comparator ? neg(comparator) : defaultNegComparator, - mapper - ); - }, +var toString = Object.prototype.toString; +function isPlainObject(value) { + // The base prototype's toString deals with Argument objects and native namespaces like Math + if (!value || + typeof value !== 'object' || + toString.call(value) !== '[object Object]') { + return false; + } + var proto = Object.getPrototypeOf(value); + if (proto === null) { + return true; + } + // Iteratively going up the prototype chain is needed for cross-realm environments (differing contexts, iframes, etc) + var parentProto = proto; + var nextProto = Object.getPrototypeOf(proto); + while (nextProto !== null) { + parentProto = nextProto; + nextProto = Object.getPrototypeOf(parentProto); + } + return parentProto === proto; +} - rest: function rest() { - return this.slice(1); - }, +/** + * Returns true if the value is a potentially-persistent data structure, either + * provided by Immutable.js or a plain Array or Object. + */ +function isDataStructure(value) { + return (typeof value === 'object' && + (isImmutable(value) || Array.isArray(value) || isPlainObject(value))); +} - skip: function skip(amount) { - return amount === 0 ? this : this.slice(Math.max(0, amount)); - }, +/** + * Converts a value to a string, adding quotes if a string was provided. + */ +function quoteString(value) { + try { + return typeof value === 'string' ? JSON.stringify(value) : String(value); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } + catch (_ignoreError) { + return JSON.stringify(value); + } +} - skipLast: function skipLast(amount) { - return amount === 0 ? this : this.slice(0, -Math.max(0, amount)); - }, +/** + * Returns true if the key is defined in the provided collection. + * + * A functional alternative to `collection.has(key)` which will also work with + * plain Objects and Arrays as an alternative for + * `collection.hasOwnProperty(key)`. + */ +function has(collection, key) { + return isImmutable(collection) + ? // @ts-expect-error key might be a number or symbol, which is not handled be Record key type + collection.has(key) + : // @ts-expect-error key might be anything else than PropertyKey, and will return false in that case but runtime is OK + isDataStructure(collection) && hasOwnProperty.call(collection, key); +} - skipWhile: function skipWhile(predicate, context) { - return reify(this, skipWhileFactory(this, predicate, context, true)); - }, +function get(collection, key, notSetValue) { + return isImmutable(collection) + ? collection.get(key, notSetValue) + : !has(collection, key) + ? notSetValue + : // @ts-expect-error weird "get" here, + typeof collection.get === 'function' + ? // @ts-expect-error weird "get" here, + collection.get(key) + : // @ts-expect-error key is unknown here, + collection[key]; +} - skipUntil: function skipUntil(predicate, context) { - return this.skipWhile(not(predicate), context); - }, +function shallowCopy(from) { + if (Array.isArray(from)) { + return arrCopy(from); + } + var to = {}; + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + return to; +} - sortBy: function sortBy(mapper, comparator) { - return reify(this, sortFactory(this, comparator, mapper)); - }, +function remove(collection, key) { + if (!isDataStructure(collection)) { + throw new TypeError('Cannot update non-data-structure value: ' + collection); + } + if (isImmutable(collection)) { + // @ts-expect-error weird "remove" here, + if (!collection.remove) { + throw new TypeError('Cannot update immutable value without .remove() method: ' + collection); + } + // @ts-expect-error weird "remove" here, + return collection.remove(key); + } + // @ts-expect-error assert that key is a string, a number or a symbol here + if (!hasOwnProperty.call(collection, key)) { + return collection; + } + var collectionCopy = shallowCopy(collection); + if (Array.isArray(collectionCopy)) { + // @ts-expect-error assert that key is a number here + collectionCopy.splice(key, 1); + } + else { + // @ts-expect-error assert that key is a string, a number or a symbol here + delete collectionCopy[key]; + } + return collectionCopy; +} - take: function take(amount) { - return this.slice(0, Math.max(0, amount)); - }, +function set(collection, key, value) { + if (!isDataStructure(collection)) { + throw new TypeError('Cannot update non-data-structure value: ' + collection); + } + if (isImmutable(collection)) { + // @ts-expect-error weird "set" here, + if (!collection.set) { + throw new TypeError('Cannot update immutable value without .set() method: ' + collection); + } + // @ts-expect-error weird "set" here, + return collection.set(key, value); + } + // @ts-expect-error mix of key and string here. Probably need a more fine type here + if (hasOwnProperty.call(collection, key) && value === collection[key]) { + return collection; + } + var collectionCopy = shallowCopy(collection); + // @ts-expect-error mix of key and string here. Probably need a more fine type here + collectionCopy[key] = value; + return collectionCopy; +} - takeLast: function takeLast(amount) { - return this.slice(-Math.max(0, amount)); - }, +function updateIn$1(collection, keyPath, notSetValue, updater) { + if (!updater) { + // handle the fact that `notSetValue` is optional here, in that case `updater` is the updater function + // @ts-expect-error updater is a function here + updater = notSetValue; + notSetValue = undefined; + } + var updatedValue = updateInDeeply(isImmutable(collection), + // @ts-expect-error type issues with Record and mixed types + collection, coerceKeyPath(keyPath), 0, notSetValue, updater); + // @ts-expect-error mixed return type + return updatedValue === NOT_SET ? notSetValue : updatedValue; +} +function updateInDeeply(inImmutable, existing, keyPath, i, notSetValue, updater) { + var wasNotSet = existing === NOT_SET; + if (i === keyPath.length) { + var existingValue = wasNotSet ? notSetValue : existing; + // @ts-expect-error mixed type with optional value + var newValue = updater(existingValue); + // @ts-expect-error mixed type + return newValue === existingValue ? existing : newValue; + } + if (!wasNotSet && !isDataStructure(existing)) { + throw new TypeError('Cannot update within non-data-structure value in path [' + + Array.from(keyPath).slice(0, i).map(quoteString) + + ']: ' + + existing); + } + var key = keyPath[i]; + var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET); + var nextUpdated = updateInDeeply(nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting), + // @ts-expect-error mixed type + nextExisting, keyPath, i + 1, notSetValue, updater); + return nextUpdated === nextExisting + ? existing + : nextUpdated === NOT_SET + ? remove(existing, key) + : set(wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated); +} - takeWhile: function takeWhile(predicate, context) { - return reify(this, takeWhileFactory(this, predicate, context)); - }, +/** + * Returns a copy of the collection with the value at the key path set to the + * provided value. + * + * A functional alternative to `collection.setIn(keypath)` which will also + * work with plain Objects and Arrays. + */ +function setIn$1(collection, keyPath, value) { + return updateIn$1(collection, keyPath, NOT_SET, function () { return value; }); +} - takeUntil: function takeUntil(predicate, context) { - return this.takeWhile(not(predicate), context); - }, +function setIn(keyPath, v) { + return setIn$1(this, keyPath, v); +} - update: function update(fn) { - return fn(this); - }, +/** + * Returns a copy of the collection with the value at the key path removed. + * + * A functional alternative to `collection.removeIn(keypath)` which will also + * work with plain Objects and Arrays. + */ +function removeIn(collection, keyPath) { + return updateIn$1(collection, keyPath, function () { return NOT_SET; }); +} - valueSeq: function valueSeq() { - return this.toIndexedSeq(); - }, +function deleteIn(keyPath) { + return removeIn(this, keyPath); +} - // ### Hashable Object +function update$1(collection, key, notSetValue, updater) { + return updateIn$1( + // @ts-expect-error Index signature for type string is missing in type V[] + collection, [key], notSetValue, updater); +} - hashCode: function hashCode() { - return this.__hash || (this.__hash = hashCollection(this)); - }, +function update(key, notSetValue, updater) { + return arguments.length === 1 + ? key(this) + : update$1(this, key, notSetValue, updater); +} - // ### Internal +function updateIn(keyPath, notSetValue, updater) { + return updateIn$1(this, keyPath, notSetValue, updater); +} - // abstract __iterate(fn, reverse) +function merge$1() { + var iters = [], len = arguments.length; + while ( len-- ) iters[ len ] = arguments[ len ]; - // abstract __iterator(type, reverse) -}); + return mergeIntoKeyedWith(this, iters); +} -var CollectionPrototype = Collection.prototype; -CollectionPrototype[IS_COLLECTION_SYMBOL] = true; -CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values; -CollectionPrototype.toJSON = CollectionPrototype.toArray; -CollectionPrototype.__toStringMapper = quoteString; -CollectionPrototype.inspect = CollectionPrototype.toSource = function () { - return this.toString(); -}; -CollectionPrototype.chain = CollectionPrototype.flatMap; -CollectionPrototype.contains = CollectionPrototype.includes; +function mergeWith$1(merger) { + var iters = [], len = arguments.length - 1; + while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; -mixin(KeyedCollection, { - // ### More sequential methods + if (typeof merger !== 'function') { + throw new TypeError('Invalid merger function: ' + merger); + } + return mergeIntoKeyedWith(this, iters, merger); +} - flip: function flip() { - return reify(this, flipFactory(this)); - }, +function mergeIntoKeyedWith(collection, collections, merger) { + var iters = []; + for (var ii = 0; ii < collections.length; ii++) { + var collection$1 = KeyedCollection(collections[ii]); + if (collection$1.size !== 0) { + iters.push(collection$1); + } + } + if (iters.length === 0) { + return collection; + } + if ( + collection.toSeq().size === 0 && + !collection.__ownerID && + iters.length === 1 + ) { + return isRecord(collection) + ? collection // Record is empty and will not be updated: return the same instance + : collection.constructor(iters[0]); + } + return collection.withMutations(function (collection) { + var mergeIntoCollection = merger + ? function (value, key) { + update$1(collection, key, NOT_SET, function (oldVal) { return oldVal === NOT_SET ? value : merger(oldVal, value, key); } + ); + } + : function (value, key) { + collection.set(key, value); + }; + for (var ii = 0; ii < iters.length; ii++) { + iters[ii].forEach(mergeIntoCollection); + } + }); +} - mapEntries: function mapEntries(mapper, context) { - var this$1$1 = this; - - var iterations = 0; - return reify( - this, - this.toSeq() - .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1$1); }) - .fromEntrySeq() - ); - }, - - mapKeys: function mapKeys(mapper, context) { - var this$1$1 = this; - - return reify( - this, - this.toSeq() - .flip() - .map(function (k, v) { return mapper.call(context, k, v, this$1$1); }) - .flip() - ); - }, -}); - -var KeyedCollectionPrototype = KeyedCollection.prototype; -KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true; -KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries; -KeyedCollectionPrototype.toJSON = toObject; -KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); }; - -mixin(IndexedCollection, { - // ### Conversion to other types - - toKeyedSeq: function toKeyedSeq() { - return new ToKeyedSequence(this, false); - }, - - // ### ES6 Collection methods (ES6 Array and Map) - - filter: function filter(predicate, context) { - return reify(this, filterFactory(this, predicate, context, false)); - }, - - findIndex: function findIndex(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry ? entry[0] : -1; - }, - - indexOf: function indexOf(searchValue) { - var key = this.keyOf(searchValue); - return key === undefined ? -1 : key; - }, - - lastIndexOf: function lastIndexOf(searchValue) { - var key = this.lastKeyOf(searchValue); - return key === undefined ? -1 : key; - }, +function merge(collection) { + var sources = [], len = arguments.length - 1; + while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; - reverse: function reverse() { - return reify(this, reverseFactory(this, false)); - }, + return mergeWithSources(collection, sources); +} - slice: function slice(begin, end) { - return reify(this, sliceFactory(this, begin, end, false)); - }, +function mergeWith(merger, collection) { + var sources = [], len = arguments.length - 2; + while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; - splice: function splice(index, removeNum /*, ...values*/) { - var numArgs = arguments.length; - removeNum = Math.max(removeNum || 0, 0); - if (numArgs === 0 || (numArgs === 2 && !removeNum)) { - return this; - } - // If index is negative, it should resolve relative to the size of the - // collection. However size may be expensive to compute if not cached, so - // only call count() if the number is in fact negative. - index = resolveBegin(index, index < 0 ? this.count() : this.size); - var spliced = this.slice(0, index); - return reify( - this, - numArgs === 1 - ? spliced - : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) - ); - }, + return mergeWithSources(collection, sources, merger); +} - // ### More collection methods +function mergeDeep$1(collection) { + var sources = [], len = arguments.length - 1; + while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; - findLastIndex: function findLastIndex(predicate, context) { - var entry = this.findLastEntry(predicate, context); - return entry ? entry[0] : -1; - }, + return mergeDeepWithSources(collection, sources); +} - first: function first(notSetValue) { - return this.get(0, notSetValue); - }, +function mergeDeepWith$1(merger, collection) { + var sources = [], len = arguments.length - 2; + while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; - flatten: function flatten(depth) { - return reify(this, flattenFactory(this, depth, false)); - }, + return mergeDeepWithSources(collection, sources, merger); +} - get: function get(index, notSetValue) { - index = wrapIndex(this, index); - return index < 0 || - this.size === Infinity || - (this.size !== undefined && index > this.size) - ? notSetValue - : this.find(function (_, key) { return key === index; }, undefined, notSetValue); - }, +function mergeDeepWithSources(collection, sources, merger) { + return mergeWithSources(collection, sources, deepMergerWith(merger)); +} - has: function has(index) { - index = wrapIndex(this, index); - return ( - index >= 0 && - (this.size !== undefined - ? this.size === Infinity || index < this.size - : this.indexOf(index) !== -1) +function mergeWithSources(collection, sources, merger) { + if (!isDataStructure(collection)) { + throw new TypeError( + 'Cannot merge into non-data-structure value: ' + collection ); - }, - - interpose: function interpose(separator) { - return reify(this, interposeFactory(this, separator)); - }, - - interleave: function interleave(/*...collections*/) { - var collections = [this].concat(arrCopy(arguments)); - var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections); - var interleaved = zipped.flatten(true); - if (zipped.size) { - interleaved.size = zipped.size * collections.length; - } - return reify(this, interleaved); - }, - - keySeq: function keySeq() { - return Range(0, this.size); - }, - - last: function last(notSetValue) { - return this.get(-1, notSetValue); - }, - - skipWhile: function skipWhile(predicate, context) { - return reify(this, skipWhileFactory(this, predicate, context, false)); - }, - - zip: function zip(/*, ...collections */) { - var collections = [this].concat(arrCopy(arguments)); - return reify(this, zipWithFactory(this, defaultZipper, collections)); - }, - - zipAll: function zipAll(/*, ...collections */) { - var collections = [this].concat(arrCopy(arguments)); - return reify(this, zipWithFactory(this, defaultZipper, collections, true)); - }, - - zipWith: function zipWith(zipper /*, ...collections */) { - var collections = arrCopy(arguments); - collections[0] = this; - return reify(this, zipWithFactory(this, zipper, collections)); - }, -}); - -var IndexedCollectionPrototype = IndexedCollection.prototype; -IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true; -IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true; - -mixin(SetCollection, { - // ### ES6 Collection methods (ES6 Array and Map) - - get: function get(value, notSetValue) { - return this.has(value) ? value : notSetValue; - }, - - includes: function includes(value) { - return this.has(value); - }, - - // ### More sequential methods - - keySeq: function keySeq() { - return this.valueSeq(); - }, -}); - -var SetCollectionPrototype = SetCollection.prototype; -SetCollectionPrototype.has = CollectionPrototype.includes; -SetCollectionPrototype.contains = SetCollectionPrototype.includes; -SetCollectionPrototype.keys = SetCollectionPrototype.values; - -// Mixin subclasses - -mixin(KeyedSeq, KeyedCollectionPrototype); -mixin(IndexedSeq, IndexedCollectionPrototype); -mixin(SetSeq, SetCollectionPrototype); - -// #pragma Helper functions - -function reduce(collection, reducer, reduction, context, useFirst, reverse) { - assertNotInfinite(collection.size); - collection.__iterate(function (v, k, c) { - if (useFirst) { - useFirst = false; - reduction = v; - } else { - reduction = reducer.call(context, reduction, v, k, c); - } - }, reverse); - return reduction; + } + if (isImmutable(collection)) { + return typeof merger === 'function' && collection.mergeWith + ? collection.mergeWith.apply(collection, [ merger ].concat( sources )) + : collection.merge + ? collection.merge.apply(collection, sources) + : collection.concat.apply(collection, sources); + } + var isArray = Array.isArray(collection); + var merged = collection; + var Collection = isArray ? IndexedCollection : KeyedCollection; + var mergeItem = isArray + ? function (value) { + // Copy on write + if (merged === collection) { + merged = shallowCopy(merged); + } + merged.push(value); + } + : function (value, key) { + var hasVal = hasOwnProperty.call(merged, key); + var nextVal = + hasVal && merger ? merger(merged[key], value, key) : value; + if (!hasVal || nextVal !== merged[key]) { + // Copy on write + if (merged === collection) { + merged = shallowCopy(merged); + } + merged[key] = nextVal; + } + }; + for (var i = 0; i < sources.length; i++) { + Collection(sources[i]).forEach(mergeItem); + } + return merged; } -function keyMapper(v, k) { - return k; +function deepMergerWith(merger) { + function deepMerger(oldValue, newValue, key) { + return isDataStructure(oldValue) && + isDataStructure(newValue) && + areMergeable(oldValue, newValue) + ? mergeWithSources(oldValue, [newValue], deepMerger) + : merger + ? merger(oldValue, newValue, key) + : newValue; + } + return deepMerger; } -function entryMapper(v, k) { - return [k, v]; +/** + * It's unclear what the desired behavior is for merging two collections that + * fall into separate categories between keyed, indexed, or set-like, so we only + * consider them mergeable if they fall into the same category. + */ +function areMergeable(oldDataStructure, newDataStructure) { + var oldSeq = Seq(oldDataStructure); + var newSeq = Seq(newDataStructure); + // This logic assumes that a sequence can only fall into one of the three + // categories mentioned above (since there's no `isSetLike()` method). + return ( + isIndexed(oldSeq) === isIndexed(newSeq) && + isKeyed(oldSeq) === isKeyed(newSeq) + ); } -function not(predicate) { - return function () { - return !predicate.apply(this, arguments); - }; -} +function mergeDeep() { + var iters = [], len = arguments.length; + while ( len-- ) iters[ len ] = arguments[ len ]; -function neg(predicate) { - return function () { - return -predicate.apply(this, arguments); - }; + return mergeDeepWithSources(this, iters); } -function defaultZipper() { - return arrCopy(arguments); +function mergeDeepWith(merger) { + var iters = [], len = arguments.length - 1; + while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; + + return mergeDeepWithSources(this, iters, merger); } -function defaultNegComparator(a, b) { - return a < b ? 1 : a > b ? -1 : 0; +function mergeIn(keyPath) { + var iters = [], len = arguments.length - 1; + while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; + + return updateIn$1(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); }); } -function hashCollection(collection) { - if (collection.size === Infinity) { - return 0; - } - var ordered = isOrdered(collection); - var keyed = isKeyed(collection); - var h = ordered ? 1 : 0; +function mergeDeepIn(keyPath) { + var iters = [], len = arguments.length - 1; + while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; - collection.__iterate( - keyed - ? ordered - ? function (v, k) { - h = (31 * h + hashMerge(hash(v), hash(k))) | 0; - } - : function (v, k) { - h = (h + hashMerge(hash(v), hash(k))) | 0; - } - : ordered - ? function (v) { - h = (31 * h + hash(v)) | 0; - } - : function (v) { - h = (h + hash(v)) | 0; - } + return updateIn$1(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); } ); +} - return murmurHashOfSize(collection.size, h); +function withMutations(fn) { + var mutable = this.asMutable(); + fn(mutable); + return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; } -function murmurHashOfSize(size, h) { - h = imul(h, 0xcc9e2d51); - h = imul((h << 15) | (h >>> -15), 0x1b873593); - h = imul((h << 13) | (h >>> -13), 5); - h = ((h + 0xe6546b64) | 0) ^ size; - h = imul(h ^ (h >>> 16), 0x85ebca6b); - h = imul(h ^ (h >>> 13), 0xc2b2ae35); - h = smi(h ^ (h >>> 16)); - return h; +function asMutable() { + return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); } -function hashMerge(a, b) { - return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int +function asImmutable() { + return this.__ensureOwner(); } -var OrderedSet = /*@__PURE__*/(function (Set) { - function OrderedSet(value) { +function wasAltered() { + return this.__altered; +} + +var Map = /*@__PURE__*/(function (KeyedCollection) { + function Map(value) { // eslint-disable-next-line no-constructor-return return value === undefined || value === null - ? emptyOrderedSet() - : isOrderedSet(value) + ? emptyMap() + : isMap(value) && !isOrdered(value) ? value - : emptyOrderedSet().withMutations(function (set) { - var iter = SetCollection(value); + : emptyMap().withMutations(function (map) { + var iter = KeyedCollection(value); assertNotInfinite(iter.size); - iter.forEach(function (v) { return set.add(v); }); + iter.forEach(function (v, k) { return map.set(k, v); }); }); } - if ( Set ) OrderedSet.__proto__ = Set; - OrderedSet.prototype = Object.create( Set && Set.prototype ); - OrderedSet.prototype.constructor = OrderedSet; + if ( KeyedCollection ) Map.__proto__ = KeyedCollection; + Map.prototype = Object.create( KeyedCollection && KeyedCollection.prototype ); + Map.prototype.constructor = Map; - OrderedSet.of = function of (/*...values*/) { - return this(arguments); + Map.prototype.toString = function toString () { + return this.__toString('Map {', '}'); }; - OrderedSet.fromKeys = function fromKeys (value) { - return this(KeyedCollection(value).keySeq()); + // @pragma Access + + Map.prototype.get = function get (k, notSetValue) { + return this._root + ? this._root.get(0, undefined, k, notSetValue) + : notSetValue; }; - OrderedSet.prototype.toString = function toString () { - return this.__toString('OrderedSet {', '}'); + // @pragma Modification + + Map.prototype.set = function set (k, v) { + return updateMap(this, k, v); }; - return OrderedSet; -}(Set)); + Map.prototype.remove = function remove (k) { + return updateMap(this, k, NOT_SET); + }; -OrderedSet.isOrderedSet = isOrderedSet; + Map.prototype.deleteAll = function deleteAll (keys) { + var collection = Collection(keys); -var OrderedSetPrototype = OrderedSet.prototype; -OrderedSetPrototype[IS_ORDERED_SYMBOL] = true; -OrderedSetPrototype.zip = IndexedCollectionPrototype.zip; -OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith; -OrderedSetPrototype.zipAll = IndexedCollectionPrototype.zipAll; + if (collection.size === 0) { + return this; + } -OrderedSetPrototype.__empty = emptyOrderedSet; -OrderedSetPrototype.__make = makeOrderedSet; + return this.withMutations(function (map) { + collection.forEach(function (key) { return map.remove(key); }); + }); + }; -function makeOrderedSet(map, ownerID) { - var set = Object.create(OrderedSetPrototype); - set.size = map ? map.size : 0; - set._map = map; - set.__ownerID = ownerID; - return set; -} + Map.prototype.clear = function clear () { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._root = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyMap(); + }; -var EMPTY_ORDERED_SET; -function emptyOrderedSet() { - return ( - EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())) - ); -} + // @pragma Composition -var PairSorting = { - LeftThenRight: -1, - RightThenLeft: 1, -}; + Map.prototype.sort = function sort (comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator)); + }; -function throwOnInvalidDefaultValues(defaultValues) { - if (isRecord(defaultValues)) { - throw new Error( - 'Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.' - ); - } + Map.prototype.sortBy = function sortBy (mapper, comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator, mapper)); + }; - if (isImmutable(defaultValues)) { - throw new Error( - 'Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.' - ); - } + Map.prototype.map = function map (mapper, context) { + var this$1$1 = this; - if (defaultValues === null || typeof defaultValues !== 'object') { - throw new Error( - 'Can not call `Record` with a non-object as default values. Use a plain javascript object instead.' - ); - } -} + return this.withMutations(function (map) { + map.forEach(function (value, key) { + map.set(key, mapper.call(context, value, key, this$1$1)); + }); + }); + }; -var Record = function Record(defaultValues, name) { - var hasInitialized; + // @pragma Mutability - throwOnInvalidDefaultValues(defaultValues); + Map.prototype.__iterator = function __iterator (type, reverse) { + return new MapIterator(this, type, reverse); + }; - var RecordType = function Record(values) { + Map.prototype.__iterate = function __iterate (fn, reverse) { var this$1$1 = this; - if (values instanceof RecordType) { - return values; - } - if (!(this instanceof RecordType)) { - return new RecordType(values); - } - if (!hasInitialized) { - hasInitialized = true; - var keys = Object.keys(defaultValues); - var indices = (RecordTypePrototype._indices = {}); - // Deprecated: left to attempt not to break any external code which - // relies on a ._name property existing on record instances. - // Use Record.getDescriptiveName() instead - RecordTypePrototype._name = name; - RecordTypePrototype._keys = keys; - RecordTypePrototype._defaultValues = defaultValues; - for (var i = 0; i < keys.length; i++) { - var propName = keys[i]; - indices[propName] = i; - if (RecordTypePrototype[propName]) { - /* eslint-disable no-console */ - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - typeof console === 'object' && - console.warn && - console.warn( - 'Cannot define ' + - recordName(this) + - ' with property "' + - propName + - '" since that property name is part of the Record API.' - ); - /* eslint-enable no-console */ - } else { - setProp(RecordTypePrototype, propName); - } + var iterations = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + this._root && + this._root.iterate(function (entry) { + iterations++; + return fn(entry[1], entry[0], this$1$1); + }, reverse); + return iterations; + }; + + Map.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + if (this.size === 0) { + return emptyMap(); } + this.__ownerID = ownerID; + this.__altered = false; + return this; } - this.__ownerID = undefined; - this._values = List().withMutations(function (l) { - l.setSize(this$1$1._keys.length); - KeyedCollection(values).forEach(function (v, k) { - l.set(this$1$1._indices[k], v === this$1$1._defaultValues[k] ? undefined : v); - }); - }); - return this; + return makeMap(this.size, this._root, ownerID, this.__hash); }; - var RecordTypePrototype = (RecordType.prototype = - Object.create(RecordPrototype)); - RecordTypePrototype.constructor = RecordType; + return Map; +}(KeyedCollection)); - if (name) { - RecordType.displayName = name; - } +Map.isMap = isMap; - // eslint-disable-next-line no-constructor-return - return RecordType; +var MapPrototype = Map.prototype; +MapPrototype[IS_MAP_SYMBOL] = true; +MapPrototype[DELETE] = MapPrototype.remove; +MapPrototype.removeAll = MapPrototype.deleteAll; +MapPrototype.setIn = setIn; +MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn; +MapPrototype.update = update; +MapPrototype.updateIn = updateIn; +MapPrototype.merge = MapPrototype.concat = merge$1; +MapPrototype.mergeWith = mergeWith$1; +MapPrototype.mergeDeep = mergeDeep; +MapPrototype.mergeDeepWith = mergeDeepWith; +MapPrototype.mergeIn = mergeIn; +MapPrototype.mergeDeepIn = mergeDeepIn; +MapPrototype.withMutations = withMutations; +MapPrototype.wasAltered = wasAltered; +MapPrototype.asImmutable = asImmutable; +MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable; +MapPrototype['@@transducer/step'] = function (result, arr) { + return result.set(arr[0], arr[1]); }; - -Record.prototype.toString = function toString () { - var str = recordName(this) + ' { '; - var keys = this._keys; - var k; - for (var i = 0, l = keys.length; i !== l; i++) { - k = keys[i]; - str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k)); - } - return str + ' }'; +MapPrototype['@@transducer/result'] = function (obj) { + return obj.asImmutable(); }; -Record.prototype.equals = function equals (other) { - return ( - this === other || - (isRecord(other) && recordSeq(this).equals(recordSeq(other))) - ); +// #pragma Trie Nodes + +var ArrayMapNode = function ArrayMapNode(ownerID, entries) { + this.ownerID = ownerID; + this.entries = entries; }; -Record.prototype.hashCode = function hashCode () { - return recordSeq(this).hashCode(); +ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; }; -// @pragma Access +ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; -Record.prototype.has = function has (k) { - return this._indices.hasOwnProperty(k); -}; + var entries = this.entries; + var idx = 0; + var len = entries.length; + for (; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; -Record.prototype.get = function get (k, notSetValue) { - if (!this.has(k)) { - return notSetValue; + if (exists ? entries[idx][1] === value : removed) { + return this; } - var index = this._indices[k]; - var value = this._values.get(index); - return value === undefined ? this._defaultValues[k] : value; -}; -// @pragma Modification + SetRef(didAlter); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + (removed || !exists) && SetRef(didChangeSize); -Record.prototype.set = function set (k, v) { - if (this.has(k)) { - var newValues = this._values.set( - this._indices[k], - v === this._defaultValues[k] ? undefined : v - ); - if (newValues !== this._values && !this.__ownerID) { - return makeRecord(this, newValues); - } + if (removed && entries.length === 1) { + return; // undefined } - return this; -}; -Record.prototype.remove = function remove (k) { - return this.set(k); -}; + if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { + return createNodes(ownerID, entries, key, value); + } -Record.prototype.clear = function clear () { - var newValues = this._values.clear().setSize(this._keys.length); + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); - return this.__ownerID ? this : makeRecord(this, newValues); -}; + if (exists) { + if (removed) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + idx === len - 1 + ? newEntries.pop() + : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } -Record.prototype.wasAltered = function wasAltered () { - return this._values.wasAltered(); -}; + if (isEditable) { + this.entries = newEntries; + return this; + } -Record.prototype.toSeq = function toSeq () { - return recordSeq(this); + return new ArrayMapNode(ownerID, newEntries); }; -Record.prototype.toJS = function toJS$1 () { - return toJS(this); +var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) { + this.ownerID = ownerID; + this.bitmap = bitmap; + this.nodes = nodes; }; -Record.prototype.entries = function entries () { - return this.__iterator(ITERATE_ENTRIES); +BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK); + var bitmap = this.bitmap; + return (bitmap & bit) === 0 + ? notSetValue + : this.nodes[popCount(bitmap & (bit - 1))].get( + shift + SHIFT, + keyHash, + key, + notSetValue + ); }; -Record.prototype.__iterator = function __iterator (type, reverse) { - return recordSeq(this).__iterator(type, reverse); -}; +BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var bit = 1 << keyHashFrag; + var bitmap = this.bitmap; + var exists = (bitmap & bit) !== 0; -Record.prototype.__iterate = function __iterate (fn, reverse) { - return recordSeq(this).__iterate(fn, reverse); -}; + if (!exists && value === NOT_SET) { + return this; + } -Record.prototype.__ensureOwner = function __ensureOwner (ownerID) { - if (ownerID === this.__ownerID) { + var idx = popCount(bitmap & (bit - 1)); + var nodes = this.nodes; + var node = exists ? nodes[idx] : undefined; + var newNode = updateNode( + node, + ownerID, + shift + SHIFT, + keyHash, + key, + value, + didChangeSize, + didAlter + ); + + if (newNode === node) { return this; } - var newValues = this._values.__ensureOwner(ownerID); - if (!ownerID) { - this.__ownerID = ownerID; - this._values = newValues; + + if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { + return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); + } + + if ( + exists && + !newNode && + nodes.length === 2 && + isLeafNode(nodes[idx ^ 1]) + ) { + return nodes[idx ^ 1]; + } + + if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { + return newNode; + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit; + var newNodes = exists + ? newNode + ? setAt(nodes, idx, newNode, isEditable) + : spliceOut(nodes, idx, isEditable) + : spliceIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.bitmap = newBitmap; + this.nodes = newNodes; return this; } - return makeRecord(this, newValues, ownerID); + + return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; -Record.isRecord = isRecord; -Record.getDescriptiveName = recordName; -var RecordPrototype = Record.prototype; -RecordPrototype[IS_RECORD_SYMBOL] = true; -RecordPrototype[DELETE] = RecordPrototype.remove; -RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn; -RecordPrototype.getIn = getIn; -RecordPrototype.hasIn = CollectionPrototype.hasIn; -RecordPrototype.merge = merge$1; -RecordPrototype.mergeWith = mergeWith$1; -RecordPrototype.mergeIn = mergeIn; -RecordPrototype.mergeDeep = mergeDeep; -RecordPrototype.mergeDeepWith = mergeDeepWith; -RecordPrototype.mergeDeepIn = mergeDeepIn; -RecordPrototype.setIn = setIn; -RecordPrototype.update = update; -RecordPrototype.updateIn = updateIn; -RecordPrototype.withMutations = withMutations; -RecordPrototype.asMutable = asMutable; -RecordPrototype.asImmutable = asImmutable; -RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries; -RecordPrototype.toJSON = RecordPrototype.toObject = - CollectionPrototype.toObject; -RecordPrototype.inspect = RecordPrototype.toSource = function () { - return this.toString(); +var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) { + this.ownerID = ownerID; + this.count = count; + this.nodes = nodes; }; -function makeRecord(likeRecord, values, ownerID) { - var record = Object.create(Object.getPrototypeOf(likeRecord)); - record._values = values; - record.__ownerID = ownerID; - return record; -} +HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var node = this.nodes[idx]; + return node + ? node.get(shift + SHIFT, keyHash, key, notSetValue) + : notSetValue; +}; -function recordName(record) { - return record.constructor.displayName || record.constructor.name || 'Record'; -} +HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var removed = value === NOT_SET; + var nodes = this.nodes; + var node = nodes[idx]; -function recordSeq(record) { - return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; })); -} + if (removed && !node) { + return this; + } -function setProp(prototype, name) { - try { - Object.defineProperty(prototype, name, { - get: function () { - return this.get(name); - }, - set: function (value) { - invariant(this.__ownerID, 'Cannot set on an immutable record.'); - this.set(name, value); - }, - }); - // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO enable eslint here - } catch (error) { - // Object.defineProperty failed. Probably IE8. + var newNode = updateNode( + node, + ownerID, + shift + SHIFT, + keyHash, + key, + value, + didChangeSize, + didAlter + ); + if (newNode === node) { + return this; } -} -/** - * Returns a lazy Seq of `value` repeated `times` times. When `times` is - * undefined, returns an infinite sequence of `value`. - */ -var Repeat = /*@__PURE__*/(function (IndexedSeq) { - function Repeat(value, times) { - if (!(this instanceof Repeat)) { - // eslint-disable-next-line no-constructor-return - return new Repeat(value, times); - } - this._value = value; - this.size = times === undefined ? Infinity : Math.max(0, times); - if (this.size === 0) { - if (EMPTY_REPEAT) { - // eslint-disable-next-line no-constructor-return - return EMPTY_REPEAT; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - EMPTY_REPEAT = this; + var newCount = this.count; + if (!node) { + newCount++; + } else if (!newNode) { + newCount--; + if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { + return packNodes(ownerID, nodes, newCount, idx); } } - if ( IndexedSeq ) Repeat.__proto__ = IndexedSeq; - Repeat.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); - Repeat.prototype.constructor = Repeat; + var isEditable = ownerID && ownerID === this.ownerID; + var newNodes = setAt(nodes, idx, newNode, isEditable); - Repeat.prototype.toString = function toString () { - if (this.size === 0) { - return 'Repeat []'; - } - return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; - }; + if (isEditable) { + this.count = newCount; + this.nodes = newNodes; + return this; + } - Repeat.prototype.get = function get (index, notSetValue) { - return this.has(index) ? this._value : notSetValue; - }; + return new HashArrayMapNode(ownerID, newCount, newNodes); +}; - Repeat.prototype.includes = function includes (searchValue) { - return is(this._value, searchValue); - }; +var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entries = entries; +}; - Repeat.prototype.slice = function slice (begin, end) { - var size = this.size; - return wholeSlice(begin, end, size) - ? this - : new Repeat( - this._value, - resolveEnd(end, size) - resolveBegin(begin, size) - ); - }; +HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; +}; - Repeat.prototype.reverse = function reverse () { - return this; - }; +HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } - Repeat.prototype.indexOf = function indexOf (searchValue) { - if (is(this._value, searchValue)) { - return 0; - } - return -1; - }; + var removed = value === NOT_SET; - Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) { - if (is(this._value, searchValue)) { - return this.size; + if (keyHash !== this.keyHash) { + if (removed) { + return this; } - return -1; - }; + SetRef(didAlter); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); + } - Repeat.prototype.__iterate = function __iterate (fn, reverse) { - var size = this.size; - var i = 0; - while (i !== size) { - if (fn(this._value, reverse ? size - ++i : i++, this) === false) { - break; - } + var entries = this.entries; + var idx = 0; + var len = entries.length; + for (; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; } - return i; - }; + } + var exists = idx < len; - Repeat.prototype.__iterator = function __iterator (type, reverse) { - var this$1$1 = this; + if (exists ? entries[idx][1] === value : removed) { + return this; + } - var size = this.size; - var i = 0; - return new Iterator(function () { return i === size - ? iteratorDone() - : iteratorValue(type, reverse ? size - ++i : i++, this$1$1._value); } - ); - }; + SetRef(didAlter); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + (removed || !exists) && SetRef(didChangeSize); - Repeat.prototype.equals = function equals (other) { - return other instanceof Repeat - ? is(this._value, other._value) - : deepEqual(this, other); - }; + if (removed && len === 2) { + return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); + } - return Repeat; -}(IndexedSeq)); + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); -var EMPTY_REPEAT; + if (exists) { + if (removed) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + idx === len - 1 + ? newEntries.pop() + : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } -function fromJS(value, converter) { - return fromJSWith( - [], - converter || defaultConverter, + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new HashCollisionNode(ownerID, this.keyHash, newEntries); +}; + +var ValueNode = function ValueNode(ownerID, keyHash, entry) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entry = entry; +}; + +ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) { + return is(key, this.entry[0]) ? this.entry[1] : notSetValue; +}; + +ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + var keyMatch = is(key, this.entry[0]); + if (keyMatch ? value === this.entry[1] : removed) { + return this; + } + + SetRef(didAlter); + + if (removed) { + SetRef(didChangeSize); + return; // undefined + } + + if (keyMatch) { + if (ownerID && ownerID === this.ownerID) { + this.entry[1] = value; + return this; + } + return new ValueNode(ownerID, this.keyHash, [key, value]); + } + + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); +}; + +// #pragma Iterators + +ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = + function (fn, reverse) { + var entries = this.entries; + for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { + if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { + return false; + } + } + }; + +BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = + function (fn, reverse) { + var nodes = this.nodes; + for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { + var node = nodes[reverse ? maxIndex - ii : ii]; + if (node && node.iterate(fn, reverse) === false) { + return false; + } + } + }; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +ValueNode.prototype.iterate = function (fn, reverse) { + return fn(this.entry); +}; + +var MapIterator = /*@__PURE__*/(function (Iterator) { + function MapIterator(map, type, reverse) { + this._type = type; + this._reverse = reverse; + this._stack = map._root && mapIteratorFrame(map._root); + } + + if ( Iterator ) MapIterator.__proto__ = Iterator; + MapIterator.prototype = Object.create( Iterator && Iterator.prototype ); + MapIterator.prototype.constructor = MapIterator; + + MapIterator.prototype.next = function next () { + var type = this._type; + var stack = this._stack; + while (stack) { + var node = stack.node; + var index = stack.index++; + var maxIndex = (void 0); + if (node.entry) { + if (index === 0) { + return mapIteratorValue(type, node.entry); + } + } else if (node.entries) { + maxIndex = node.entries.length - 1; + if (index <= maxIndex) { + return mapIteratorValue( + type, + node.entries[this._reverse ? maxIndex - index : index] + ); + } + } else { + maxIndex = node.nodes.length - 1; + if (index <= maxIndex) { + var subNode = node.nodes[this._reverse ? maxIndex - index : index]; + if (subNode) { + if (subNode.entry) { + return mapIteratorValue(type, subNode.entry); + } + stack = this._stack = mapIteratorFrame(subNode, stack); + } + continue; + } + } + stack = this._stack = this._stack.__prev; + } + return iteratorDone(); + }; + + return MapIterator; +}(Iterator)); + +function mapIteratorValue(type, entry) { + return iteratorValue(type, entry[0], entry[1]); +} + +function mapIteratorFrame(node, prev) { + return { + node: node, + index: 0, + __prev: prev, + }; +} + +function makeMap(size, root, ownerID, hash) { + var map = Object.create(MapPrototype); + map.size = size; + map._root = root; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; +} + +var EMPTY_MAP; +function emptyMap() { + return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); +} + +function updateMap(map, k, v) { + var newRoot; + var newSize; + if (!map._root) { + if (v === NOT_SET) { + return map; + } + newSize = 1; + newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); + } else { + var didChangeSize = MakeRef(); + var didAlter = MakeRef(); + newRoot = updateNode( + map._root, + map.__ownerID, + 0, + undefined, + k, + v, + didChangeSize, + didAlter + ); + if (!didAlter.value) { + return map; + } + newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0); + } + if (map.__ownerID) { + map.size = newSize; + map._root = newRoot; + map.__hash = undefined; + map.__altered = true; + return map; + } + return newRoot ? makeMap(newSize, newRoot) : emptyMap(); +} + +function updateNode( + node, + ownerID, + shift, + keyHash, + key, + value, + didChangeSize, + didAlter +) { + if (!node) { + if (value === NOT_SET) { + return node; + } + SetRef(didAlter); + SetRef(didChangeSize); + return new ValueNode(ownerID, keyHash, [key, value]); + } + return node.update( + ownerID, + shift, + keyHash, + key, value, - '', - converter && converter.length > 2 ? [] : undefined, - { '': value } + didChangeSize, + didAlter ); } -function fromJSWith(stack, converter, value, key, keyPath, parentValue) { - if ( - typeof value !== 'string' && - !isImmutable(value) && - (isArrayLike(value) || hasIterator(value) || isPlainObject(value)) - ) { - if (~stack.indexOf(value)) { - throw new TypeError('Cannot convert circular structure to Immutable'); +function isLeafNode(node) { + return ( + node.constructor === ValueNode || node.constructor === HashCollisionNode + ); +} + +function mergeIntoNode(node, ownerID, shift, keyHash, entry) { + if (node.keyHash === keyHash) { + return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); + } + + var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; + var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + + var newNode; + var nodes = + idx1 === idx2 + ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] + : ((newNode = new ValueNode(ownerID, keyHash, entry)), + idx1 < idx2 ? [node, newNode] : [newNode, node]); + + return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); +} + +function createNodes(ownerID, entries, key, value) { + if (!ownerID) { + ownerID = new OwnerID(); + } + var node = new ValueNode(ownerID, hash(key), [key, value]); + for (var ii = 0; ii < entries.length; ii++) { + var entry = entries[ii]; + node = node.update(ownerID, 0, undefined, entry[0], entry[1]); + } + return node; +} + +function packNodes(ownerID, nodes, count, excluding) { + var bitmap = 0; + var packedII = 0; + var packedNodes = new Array(count); + for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { + var node = nodes[ii]; + if (node !== undefined && ii !== excluding) { + bitmap |= bit; + packedNodes[packedII++] = node; } - stack.push(value); - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - keyPath && key !== '' && keyPath.push(key); - var converted = converter.call( - parentValue, - key, - Seq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); } - ), - keyPath && keyPath.slice() - ); - stack.pop(); - // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here - keyPath && keyPath.pop(); - return converted; } - return value; + return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } -function defaultConverter(k, v) { - // Effectively the opposite of "Collection.toSeq()" - return isIndexed(v) ? v.toList() : isKeyed(v) ? v.toMap() : v.toSet(); +function expandNodes(ownerID, nodes, bitmap, including, node) { + var count = 0; + var expandedNodes = new Array(SIZE); + for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { + expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; + } + expandedNodes[including] = node; + return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } -var version = "5.1.3"; +function popCount(x) { + x -= (x >> 1) & 0x55555555; + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0f0f0f0f; + x += x >> 8; + x += x >> 16; + return x & 0x7f; +} -// Note: Iterable is deprecated -var Iterable = Collection; +function setAt(array, idx, val, canEdit) { + var newArray = canEdit ? array : arrCopy(array); + newArray[idx] = val; + return newArray; +} +function spliceIn(array, idx, val, canEdit) { + var newLen = array.length + 1; + if (canEdit && idx + 1 === newLen) { + array[idx] = val; + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + newArray[ii] = val; + after = -1; + } else { + newArray[ii] = array[ii + after]; + } + } + return newArray; +} +function spliceOut(array, idx, canEdit) { + var newLen = array.length - 1; + if (canEdit && idx === newLen) { + array.pop(); + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + after = 1; + } + newArray[ii] = array[ii + after]; + } + return newArray; +} +var MAX_ARRAY_MAP_SIZE = SIZE / 4; +var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; +var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { +var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@'; +/** + * True if `maybeList` is a List. + */ +function isList(maybeList) { + return Boolean(maybeList && + // @ts-expect-error: maybeList is typed as `{}`, need to change in 6.0 to `maybeList && typeof maybeList === 'object' && IS_LIST_SYMBOL in maybeList` + maybeList[IS_LIST_SYMBOL]); +} -var __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory){ +var List = /*@__PURE__*/(function (IndexedCollection) { + function List(value) { + var empty = emptyList(); + if (value === undefined || value === null) { + // eslint-disable-next-line no-constructor-return + return empty; + } + if (isList(value)) { + // eslint-disable-next-line no-constructor-return + return value; + } + var iter = IndexedCollection(value); + var size = iter.size; + if (size === 0) { + // eslint-disable-next-line no-constructor-return + return empty; + } + assertNotInfinite(size); + if (size > 0 && size < SIZE) { + // eslint-disable-next-line no-constructor-return + return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); + } + // eslint-disable-next-line no-constructor-return + return empty.withMutations(function (list) { + list.setSize(size); + iter.forEach(function (v, i) { return list.set(i, v); }); + }); + } - //UMD - if ( true ) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { - return factory(); - }.call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module === "object") { - module.exports = factory(); - } else { - root.Tone = factory(); - } + if ( IndexedCollection ) List.__proto__ = IndexedCollection; + List.prototype = Object.create( IndexedCollection && IndexedCollection.prototype ); + List.prototype.constructor = List; -}(this, function(){ + List.of = function of (/*...values*/) { + return this(arguments); + }; - "use strict"; - - var Tone; - //constructs the main Tone object - function Main(func){ - Tone = func(); - } - //invokes each of the modules with the main Tone object as the argument - function Module(func){ - func(Tone); - } /** - * Tone.js - * @author Yotam Mann - * @license http://opensource.org/licenses/MIT MIT License - * @copyright 2014-2017 Yotam Mann - */ - Main(function () { - - /////////////////////////////////////////////////////////////////////////// - // TONE - /////////////////////////////////////////////////////////////////////////// - /** - * @class Tone is the base class of all other classes. It provides - * a lot of methods and functionality to all classes that extend - * it. - * - * @constructor - * @alias Tone - * @param {number} [inputs=1] the number of input nodes - * @param {number} [outputs=1] the number of output nodes - */ - var Tone = function (inputs, outputs) { - /** - * the input node(s) - * @type {GainNode|Array} - */ - if (this.isUndef(inputs) || inputs === 1) { - this.input = this.context.createGain(); - } else if (inputs > 1) { - this.input = new Array(inputs); - } - /** - * the output node(s) - * @type {GainNode|Array} - */ - if (this.isUndef(outputs) || outputs === 1) { - this.output = this.context.createGain(); - } else if (outputs > 1) { - this.output = new Array(inputs); - } - }; - /** - * Set the parameters at once. Either pass in an - * object mapping parameters to values, or to set a - * single parameter, by passing in a string and value. - * The last argument is an optional ramp time which - * will ramp any signal values to their destination value - * over the duration of the rampTime. - * @param {Object|string} params - * @param {number=} value - * @param {Time=} rampTime - * @returns {Tone} this - * @example - * //set values using an object - * filter.set({ - * "frequency" : 300, - * "type" : highpass - * }); - * @example - * filter.set("type", "highpass"); - * @example - * //ramp to the value 220 over 3 seconds. - * oscillator.set({ - * "frequency" : 220 - * }, 3); - */ - Tone.prototype.set = function (params, value, rampTime) { - if (this.isObject(params)) { - rampTime = value; - } else if (this.isString(params)) { - var tmpObj = {}; - tmpObj[params] = value; - params = tmpObj; - } - paramLoop: - for (var attr in params) { - value = params[attr]; - var parent = this; - if (attr.indexOf('.') !== -1) { - var attrSplit = attr.split('.'); - for (var i = 0; i < attrSplit.length - 1; i++) { - parent = parent[attrSplit[i]]; - if (parent instanceof Tone) { - attrSplit.splice(0, i + 1); - var innerParam = attrSplit.join('.'); - parent.set(innerParam, value); - continue paramLoop; - } - } - attr = attrSplit[attrSplit.length - 1]; - } - var param = parent[attr]; - if (this.isUndef(param)) { - continue; - } - if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { - if (param.value !== value) { - if (this.isUndef(rampTime)) { - param.value = value; - } else { - param.rampTo(value, rampTime); - } - } - } else if (param instanceof AudioParam) { - if (param.value !== value) { - param.value = value; - } - } else if (param instanceof Tone) { - param.set(value); - } else if (param !== value) { - parent[attr] = value; - } - } - return this; - }; - /** - * Get the object's attributes. Given no arguments get - * will return all available object properties and their corresponding - * values. Pass in a single attribute to retrieve or an array - * of attributes. The attribute strings can also include a "." - * to access deeper properties. - * @example - * osc.get(); - * //returns {"type" : "sine", "frequency" : 440, ...etc} - * @example - * osc.get("type"); - * //returns { "type" : "sine"} - * @example - * //use dot notation to access deep properties - * synth.get(["envelope.attack", "envelope.release"]); - * //returns {"envelope" : {"attack" : 0.2, "release" : 0.4}} - * @param {Array=|string|undefined} params the parameters to get, otherwise will return - * all available. - * @returns {Object} - */ - Tone.prototype.get = function (params) { - if (this.isUndef(params)) { - params = this._collectDefaults(this.constructor); - } else if (this.isString(params)) { - params = [params]; - } - var ret = {}; - for (var i = 0; i < params.length; i++) { - var attr = params[i]; - var parent = this; - var subRet = ret; - if (attr.indexOf('.') !== -1) { - var attrSplit = attr.split('.'); - for (var j = 0; j < attrSplit.length - 1; j++) { - var subAttr = attrSplit[j]; - subRet[subAttr] = subRet[subAttr] || {}; - subRet = subRet[subAttr]; - parent = parent[subAttr]; - } - attr = attrSplit[attrSplit.length - 1]; - } - var param = parent[attr]; - if (this.isObject(params[attr])) { - subRet[attr] = param.get(); - } else if (Tone.Signal && param instanceof Tone.Signal) { - subRet[attr] = param.value; - } else if (Tone.Param && param instanceof Tone.Param) { - subRet[attr] = param.value; - } else if (param instanceof AudioParam) { - subRet[attr] = param.value; - } else if (param instanceof Tone) { - subRet[attr] = param.get(); - } else if (!this.isFunction(param) && !this.isUndef(param)) { - subRet[attr] = param; - } - } - return ret; - }; - /** - * collect all of the default attributes in one - * @private - * @param {function} constr the constructor to find the defaults from - * @return {Array} all of the attributes which belong to the class - */ - Tone.prototype._collectDefaults = function (constr) { - var ret = []; - if (!this.isUndef(constr.defaults)) { - ret = Object.keys(constr.defaults); - } - if (!this.isUndef(constr._super)) { - var superDefs = this._collectDefaults(constr._super); - //filter out repeats - for (var i = 0; i < superDefs.length; i++) { - if (ret.indexOf(superDefs[i]) === -1) { - ret.push(superDefs[i]); - } - } - } - return ret; - }; - /** - * @returns {string} returns the name of the class as a string - */ - Tone.prototype.toString = function () { - for (var className in Tone) { - var isLetter = className[0].match(/^[A-Z]$/); - var sameConstructor = Tone[className] === this.constructor; - if (this.isFunction(Tone[className]) && isLetter && sameConstructor) { - return className; - } - } - return 'Tone'; - }; - /////////////////////////////////////////////////////////////////////////// - // CLASS VARS - /////////////////////////////////////////////////////////////////////////// - /** - * The number of inputs feeding into the AudioNode. - * For source nodes, this will be 0. - * @memberOf Tone# - * @name numberOfInputs - * @readOnly - */ - Object.defineProperty(Tone.prototype, 'numberOfInputs', { - get: function () { - if (this.input) { - if (this.isArray(this.input)) { - return this.input.length; - } else { - return 1; - } - } else { - return 0; - } - } - }); - /** - * The number of outputs coming out of the AudioNode. - * For source nodes, this will be 0. - * @memberOf Tone# - * @name numberOfInputs - * @readOnly - */ - Object.defineProperty(Tone.prototype, 'numberOfOutputs', { - get: function () { - if (this.output) { - if (this.isArray(this.output)) { - return this.output.length; - } else { - return 1; - } - } else { - return 0; - } - } - }); - /////////////////////////////////////////////////////////////////////////// - // CONNECTIONS - /////////////////////////////////////////////////////////////////////////// - /** - * disconnect and dispose - * @returns {Tone} this - */ - Tone.prototype.dispose = function () { - if (!this.isUndef(this.input)) { - if (this.input instanceof AudioNode) { - this.input.disconnect(); - } - this.input = null; - } - if (!this.isUndef(this.output)) { - if (this.output instanceof AudioNode) { - this.output.disconnect(); - } - this.output = null; - } - return this; - }; - /** - * connect the output of a ToneNode to an AudioParam, AudioNode, or ToneNode - * @param {Tone | AudioParam | AudioNode} unit - * @param {number} [outputNum=0] optionally which output to connect from - * @param {number} [inputNum=0] optionally which input to connect to - * @returns {Tone} this - */ - Tone.prototype.connect = function (unit, outputNum, inputNum) { - if (Array.isArray(this.output)) { - outputNum = this.defaultArg(outputNum, 0); - this.output[outputNum].connect(unit, 0, inputNum); - } else { - this.output.connect(unit, outputNum, inputNum); - } - return this; - }; - /** - * disconnect the output - * @param {Number|AudioNode} output Either the output index to disconnect - * if the output is an array, or the - * node to disconnect from. - * @returns {Tone} this - */ - Tone.prototype.disconnect = function (destination, outputNum, inputNum) { - if (this.isArray(this.output)) { - if (this.isNumber(destination)) { - this.output[destination].disconnect(); - } else { - outputNum = this.defaultArg(outputNum, 0); - this.output[outputNum].disconnect(destination, 0, inputNum); - } - } else { - this.output.disconnect.apply(this.output, arguments); - } - }; - /** - * connect together all of the arguments in series - * @param {...AudioParam|Tone|AudioNode} nodes - * @returns {Tone} this - */ - Tone.prototype.connectSeries = function () { - if (arguments.length > 1) { - var currentUnit = arguments[0]; - for (var i = 1; i < arguments.length; i++) { - var toUnit = arguments[i]; - currentUnit.connect(toUnit); - currentUnit = toUnit; - } - } - return this; - }; - /** - * Connect the output of this node to the rest of the nodes in series. - * @example - * //connect a node to an effect, panVol and then to the master output - * node.chain(effect, panVol, Tone.Master); - * @param {...AudioParam|Tone|AudioNode} nodes - * @returns {Tone} this - */ - Tone.prototype.chain = function () { - if (arguments.length > 0) { - var currentUnit = this; - for (var i = 0; i < arguments.length; i++) { - var toUnit = arguments[i]; - currentUnit.connect(toUnit); - currentUnit = toUnit; - } - } - return this; - }; - /** - * connect the output of this node to the rest of the nodes in parallel. - * @param {...AudioParam|Tone|AudioNode} nodes - * @returns {Tone} this - */ - Tone.prototype.fan = function () { - if (arguments.length > 0) { - for (var i = 0; i < arguments.length; i++) { - this.connect(arguments[i]); - } - } - return this; - }; - //give native nodes chain and fan methods - AudioNode.prototype.chain = Tone.prototype.chain; - AudioNode.prototype.fan = Tone.prototype.fan; - /////////////////////////////////////////////////////////////////////////// - // UTILITIES / HELPERS / MATHS - /////////////////////////////////////////////////////////////////////////// - /** - * If the `given` parameter is undefined, use the `fallback`. - * If both `given` and `fallback` are object literals, it will - * return a deep copy which includes all of the parameters from both - * objects. If a parameter is undefined in given, it will return - * the fallback property. - *

- * WARNING: if object is self referential, it will go into an an - * infinite recursive loop. - * - * @param {*} given - * @param {*} fallback - * @return {*} - */ - Tone.prototype.defaultArg = function (given, fallback) { - if (this.isObject(given) && this.isObject(fallback)) { - var ret = {}; - //make a deep copy of the given object - for (var givenProp in given) { - ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); - } - for (var fallbackProp in fallback) { - ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); - } - return ret; - } else { - return this.isUndef(given) ? fallback : given; - } - }; - /** - * returns the args as an options object with given arguments - * mapped to the names provided. - * - * if the args given is an array containing only one object, it is assumed - * that that's already the options object and will just return it. - * - * @param {Array} values the 'arguments' object of the function - * @param {Array} keys the names of the arguments as they - * should appear in the options object - * @param {Object=} defaults optional defaults to mixin to the returned - * options object - * @return {Object} the options object with the names mapped to the arguments - */ - Tone.prototype.optionsObject = function (values, keys, defaults) { - var options = {}; - if (values.length === 1 && this.isObject(values[0])) { - options = values[0]; - } else { - for (var i = 0; i < keys.length; i++) { - options[keys[i]] = values[i]; - } - } - if (!this.isUndef(defaults)) { - return this.defaultArg(options, defaults); - } else { - return options; - } - }; - /////////////////////////////////////////////////////////////////////////// - // TYPE CHECKING - /////////////////////////////////////////////////////////////////////////// - /** - * test if the arg is undefined - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is undefined - * @function - */ - Tone.prototype.isUndef = function (val) { - return typeof val === 'undefined'; - }; - /** - * test if the arg is a function - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is a function - * @function - */ - Tone.prototype.isFunction = function (val) { - return typeof val === 'function'; - }; - /** - * Test if the argument is a number. - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is a number - */ - Tone.prototype.isNumber = function (arg) { - return typeof arg === 'number'; - }; - /** - * Test if the given argument is an object literal (i.e. `{}`); - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is an object literal. - */ - Tone.prototype.isObject = function (arg) { - return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; - }; - /** - * Test if the argument is a boolean. - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is a boolean - */ - Tone.prototype.isBoolean = function (arg) { - return typeof arg === 'boolean'; - }; - /** - * Test if the argument is an Array - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is an array - */ - Tone.prototype.isArray = function (arg) { - return Array.isArray(arg); - }; - /** - * Test if the argument is a string. - * @param {*} arg the argument to test - * @returns {boolean} true if the arg is a string - */ - Tone.prototype.isString = function (arg) { - return typeof arg === 'string'; - }; - /** - * An empty function. - * @static - */ - Tone.noOp = function () { - }; - /** - * Make the property not writable. Internal use only. - * @private - * @param {string} property the property to make not writable - */ - Tone.prototype._readOnly = function (property) { - if (Array.isArray(property)) { - for (var i = 0; i < property.length; i++) { - this._readOnly(property[i]); - } - } else { - Object.defineProperty(this, property, { - writable: false, - enumerable: true - }); - } - }; - /** - * Make an attribute writeable. Interal use only. - * @private - * @param {string} property the property to make writable - */ - Tone.prototype._writable = function (property) { - if (Array.isArray(property)) { - for (var i = 0; i < property.length; i++) { - this._writable(property[i]); - } - } else { - Object.defineProperty(this, property, { writable: true }); - } - }; - /** - * Possible play states. - * @enum {string} - */ - Tone.State = { - Started: 'started', - Stopped: 'stopped', - Paused: 'paused' - }; - /////////////////////////////////////////////////////////////////////////// - // CONVERSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Equal power gain scale. Good for cross-fading. - * @param {NormalRange} percent (0-1) - * @return {Number} output gain (0-1) - */ - Tone.prototype.equalPowerScale = function (percent) { - var piFactor = 0.5 * Math.PI; - return Math.sin(percent * piFactor); - }; - /** - * Convert decibels into gain. - * @param {Decibels} db - * @return {Number} - */ - Tone.prototype.dbToGain = function (db) { - return Math.pow(2, db / 6); - }; - /** - * Convert gain to decibels. - * @param {Number} gain (0-1) - * @return {Decibels} - */ - Tone.prototype.gainToDb = function (gain) { - return 20 * (Math.log(gain) / Math.LN10); - }; - /** - * Convert an interval (in semitones) to a frequency ratio. - * @param {Interval} interval the number of semitones above the base note - * @return {number} the frequency ratio - * @example - * tone.intervalToFrequencyRatio(0); // 1 - * tone.intervalToFrequencyRatio(12); // 2 - * tone.intervalToFrequencyRatio(-12); // 0.5 - */ - Tone.prototype.intervalToFrequencyRatio = function (interval) { - return Math.pow(2, interval / 12); - }; - /////////////////////////////////////////////////////////////////////////// - // TIMING - /////////////////////////////////////////////////////////////////////////// - /** - * Return the current time of the AudioContext clock. - * @return {Number} the currentTime from the AudioContext - */ - Tone.prototype.now = function () { - return Tone.context.now(); - }; - /** - * Return the current time of the AudioContext clock. - * @return {Number} the currentTime from the AudioContext - * @static - */ - Tone.now = function () { - return Tone.context.now(); - }; - /////////////////////////////////////////////////////////////////////////// - // INHERITANCE - /////////////////////////////////////////////////////////////////////////// - /** - * have a child inherit all of Tone's (or a parent's) prototype - * to inherit the parent's properties, make sure to call - * Parent.call(this) in the child's constructor - * - * based on closure library's inherit function - * - * @static - * @param {function} child - * @param {function=} parent (optional) parent to inherit from - * if no parent is supplied, the child - * will inherit from Tone - */ - Tone.extend = function (child, parent) { - if (Tone.prototype.isUndef(parent)) { - parent = Tone; - } - function TempConstructor() { - } - TempConstructor.prototype = parent.prototype; - child.prototype = new TempConstructor(); - /** @override */ - child.prototype.constructor = child; - child._super = parent; - }; - /////////////////////////////////////////////////////////////////////////// - // CONTEXT - /////////////////////////////////////////////////////////////////////////// - /** - * The private audio context shared by all Tone Nodes. - * @private - * @type {Tone.Context|undefined} - */ - var audioContext; - /** - * A static pointer to the audio context accessible as Tone.context. - * @type {Tone.Context} - * @name context - * @memberOf Tone - */ - Object.defineProperty(Tone, 'context', { - get: function () { - return audioContext; - }, - set: function (context) { - if (Tone.Context && context instanceof Tone.Context) { - audioContext = context; - } else { - audioContext = new Tone.Context(context); - } - //initialize the new audio context - if (Tone.Context) { - Tone.Context.emit('init', audioContext); - } - } - }); - /** - * The AudioContext - * @type {Tone.Context} - * @name context - * @memberOf Tone# - * @readOnly - */ - Object.defineProperty(Tone.prototype, 'context', { - get: function () { - return Tone.context; - } - }); - /** - * Tone automatically creates a context on init, but if you are working - * with other libraries which also create an AudioContext, it can be - * useful to set your own. If you are going to set your own context, - * be sure to do it at the start of your code, before creating any objects. - * @static - * @param {AudioContext} ctx The new audio context to set - */ - Tone.setContext = function (ctx) { - Tone.context = ctx; - }; - /** - * The number of seconds of 1 processing block (128 samples) - * @type {Number} - * @name blockTime - * @memberOf Tone# - * @readOnly - */ - Object.defineProperty(Tone.prototype, 'blockTime', { - get: function () { - return 128 / this.context.sampleRate; - } - }); - /** - * The duration in seconds of one sample. - * @type {Number} - * @name sampleTime - * @memberOf Tone# - * @readOnly - */ - Object.defineProperty(Tone.prototype, 'sampleTime', { - get: function () { - return 1 / this.context.sampleRate; - } - }); - /** - * Whether or not all the technologies that Tone.js relies on are supported by the current browser. - * @type {Boolean} - * @name supported - * @memberOf Tone - * @readOnly - */ - Object.defineProperty(Tone, 'supported', { - get: function () { - var hasAudioContext = window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext'); - var hasPromises = window.hasOwnProperty('Promise'); - var hasWorkers = window.hasOwnProperty('Worker'); - return hasAudioContext && hasPromises && hasWorkers; - } - }); - Tone.version = 'r10'; - // allow optional silencing of this log - if (!window.TONE_SILENCE_VERSION_LOGGING) { - console.log('%c * Tone.js ' + Tone.version + ' * ', 'background: #000; color: #fff'); - } - return Tone; - }); - Module(function (Tone) { - - /** - * @class Base class for all Signals. Used Internally. - * - * @constructor - * @extends {Tone} - */ - Tone.SignalBase = function () { - }; - Tone.extend(Tone.SignalBase); - /** - * When signals connect to other signals or AudioParams, - * they take over the output value of that signal or AudioParam. - * For all other nodes, the behavior is the same as a default connect. - * - * @override - * @param {AudioParam|AudioNode|Tone.Signal|Tone} node - * @param {number} [outputNumber=0] The output number to connect from. - * @param {number} [inputNumber=0] The input number to connect to. - * @returns {Tone.SignalBase} this - */ - Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { - //zero it out so that the signal can have full control - if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { - //cancel changes - node._param.cancelScheduledValues(0); - //reset the value - node._param.value = 0; - //mark the value as overridden - node.overridden = true; - } else if (node instanceof AudioParam) { - node.cancelScheduledValues(0); - node.value = 0; - } - Tone.prototype.connect.call(this, node, outputNumber, inputNumber); - return this; - }; - return Tone.SignalBase; - }); - Module(function (Tone) { - - /** - * @class Wraps the native Web Audio API - * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface). - * - * @extends {Tone.SignalBase} - * @constructor - * @param {function|Array|Number} mapping The function used to define the values. - * The mapping function should take two arguments: - * the first is the value at the current position - * and the second is the array position. - * If the argument is an array, that array will be - * set as the wave shaping function. The input - * signal is an AudioRange [-1, 1] value and the output - * signal can take on any numerical values. - * - * @param {Number} [bufferLen=1024] The length of the WaveShaperNode buffer. - * @example - * var timesTwo = new Tone.WaveShaper(function(val){ - * return val * 2; - * }, 2048); - * @example - * //a waveshaper can also be constructed with an array of values - * var invert = new Tone.WaveShaper([1, -1]); - */ - Tone.WaveShaper = function (mapping, bufferLen) { - /** - * the waveshaper - * @type {WaveShaperNode} - * @private - */ - this._shaper = this.input = this.output = this.context.createWaveShaper(); - /** - * the waveshapers curve - * @type {Float32Array} - * @private - */ - this._curve = null; - if (Array.isArray(mapping)) { - this.curve = mapping; - } else if (isFinite(mapping) || this.isUndef(mapping)) { - this._curve = new Float32Array(this.defaultArg(mapping, 1024)); - } else if (this.isFunction(mapping)) { - this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); - this.setMap(mapping); - } - }; - Tone.extend(Tone.WaveShaper, Tone.SignalBase); - /** - * Uses a mapping function to set the value of the curve. - * @param {function} mapping The function used to define the values. - * The mapping function take two arguments: - * the first is the value at the current position - * which goes from -1 to 1 over the number of elements - * in the curve array. The second argument is the array position. - * @returns {Tone.WaveShaper} this - * @example - * //map the input signal from [-1, 1] to [0, 10] - * shaper.setMap(function(val, index){ - * return (val + 1) * 5; - * }) - */ - Tone.WaveShaper.prototype.setMap = function (mapping) { - for (var i = 0, len = this._curve.length; i < len; i++) { - var normalized = i / (len - 1) * 2 - 1; - this._curve[i] = mapping(normalized, i); - } - this._shaper.curve = this._curve; - return this; - }; - /** - * The array to set as the waveshaper curve. For linear curves - * array length does not make much difference, but for complex curves - * longer arrays will provide smoother interpolation. - * @memberOf Tone.WaveShaper# - * @type {Array} - * @name curve - */ - Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { - get: function () { - return this._shaper.curve; - }, - set: function (mapping) { - this._curve = new Float32Array(mapping); - this._shaper.curve = this._curve; - } - }); - /** - * Specifies what type of oversampling (if any) should be used when - * applying the shaping curve. Can either be "none", "2x" or "4x". - * @memberOf Tone.WaveShaper# - * @type {string} - * @name oversample - */ - Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { - get: function () { - return this._shaper.oversample; - }, - set: function (oversampling) { - if ([ - 'none', - '2x', - '4x' - ].indexOf(oversampling) !== -1) { - this._shaper.oversample = oversampling; - } else { - throw new RangeError('Tone.WaveShaper: oversampling must be either \'none\', \'2x\', or \'4x\''); - } - } - }); - /** - * Clean up. - * @returns {Tone.WaveShaper} this - */ - Tone.WaveShaper.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._shaper.disconnect(); - this._shaper = null; - this._curve = null; - return this; - }; - return Tone.WaveShaper; - }); - Module(function (Tone) { - /** - * @class Tone.TimeBase is a flexible encoding of time - * which can be evaluated to and from a string. - * Parsing code modified from https://code.google.com/p/tapdigit/ - * Copyright 2011 2012 Ariya Hidayat, New BSD License - * @extends {Tone} - * @param {Time} val The time value as a number or string - * @param {String=} units Unit values - * @example - * Tone.TimeBase(4, "n") - * Tone.TimeBase(2, "t") - * Tone.TimeBase("2t").add("1m") - * Tone.TimeBase("2t + 1m"); - */ - Tone.TimeBase = function (val, units) { - //allows it to be constructed with or without 'new' - if (this instanceof Tone.TimeBase) { - /** - * Any expressions parsed from the Time - * @type {Array} - * @private - */ - this._expr = this._noOp; - if (val instanceof Tone.TimeBase) { - this.copy(val); - } else if (!this.isUndef(units) || this.isNumber(val)) { - //default units - units = this.defaultArg(units, this._defaultUnits); - var method = this._primaryExpressions[units].method; - this._expr = method.bind(this, val); - } else if (this.isString(val)) { - this.set(val); - } else if (this.isUndef(val)) { - //default expression - this._expr = this._defaultExpr(); - } - } else { - return new Tone.TimeBase(val, units); - } - }; - Tone.extend(Tone.TimeBase); - /** - * Repalce the current time value with the value - * given by the expression string. - * @param {String} exprString - * @return {Tone.TimeBase} this - */ - Tone.TimeBase.prototype.set = function (exprString) { - this._expr = this._parseExprString(exprString); - return this; - }; - /** - * Return a clone of the TimeBase object. - * @return {Tone.TimeBase} The new cloned Tone.TimeBase - */ - Tone.TimeBase.prototype.clone = function () { - var instance = new this.constructor(); - instance.copy(this); - return instance; - }; - /** - * Copies the value of time to this Time - * @param {Tone.TimeBase} time - * @return {TimeBase} - */ - Tone.TimeBase.prototype.copy = function (time) { - var val = time._expr(); - return this.set(val); - }; - /////////////////////////////////////////////////////////////////////////// - // ABSTRACT SYNTAX TREE PARSER - /////////////////////////////////////////////////////////////////////////// - /** - * All the primary expressions. - * @private - * @type {Object} - */ - Tone.TimeBase.prototype._primaryExpressions = { - 'n': { - regexp: /^(\d+)n/i, - method: function (value) { - value = parseInt(value); - if (value === 1) { - return this._beatsToUnits(this._timeSignature()); - } else { - return this._beatsToUnits(4 / value); - } - } - }, - 't': { - regexp: /^(\d+)t/i, - method: function (value) { - value = parseInt(value); - return this._beatsToUnits(8 / (parseInt(value) * 3)); - } - }, - 'm': { - regexp: /^(\d+)m/i, - method: function (value) { - return this._beatsToUnits(parseInt(value) * this._timeSignature()); - } - }, - 'i': { - regexp: /^(\d+)i/i, - method: function (value) { - return this._ticksToUnits(parseInt(value)); - } - }, - 'hz': { - regexp: /^(\d+(?:\.\d+)?)hz/i, - method: function (value) { - return this._frequencyToUnits(parseFloat(value)); - } - }, - 'tr': { - regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, - method: function (m, q, s) { - var total = 0; - if (m && m !== '0') { - total += this._beatsToUnits(this._timeSignature() * parseFloat(m)); - } - if (q && q !== '0') { - total += this._beatsToUnits(parseFloat(q)); - } - if (s && s !== '0') { - total += this._beatsToUnits(parseFloat(s) / 4); - } - return total; - } - }, - 's': { - regexp: /^(\d+(?:\.\d+)?s)/, - method: function (value) { - return this._secondsToUnits(parseFloat(value)); - } - }, - 'samples': { - regexp: /^(\d+)samples/, - method: function (value) { - return parseInt(value) / this.context.sampleRate; - } - }, - 'default': { - regexp: /^(\d+(?:\.\d+)?)/, - method: function (value) { - return this._primaryExpressions[this._defaultUnits].method.call(this, value); - } - } - }; - /** - * All the binary expressions that TimeBase can accept. - * @private - * @type {Object} - */ - Tone.TimeBase.prototype._binaryExpressions = { - '+': { - regexp: /^\+/, - precedence: 2, - method: function (lh, rh) { - return lh() + rh(); - } - }, - '-': { - regexp: /^\-/, - precedence: 2, - method: function (lh, rh) { - return lh() - rh(); - } - }, - '*': { - regexp: /^\*/, - precedence: 1, - method: function (lh, rh) { - return lh() * rh(); - } - }, - '/': { - regexp: /^\//, - precedence: 1, - method: function (lh, rh) { - return lh() / rh(); - } - } - }; - /** - * All the unary expressions. - * @private - * @type {Object} - */ - Tone.TimeBase.prototype._unaryExpressions = { - 'neg': { - regexp: /^\-/, - method: function (lh) { - return -lh(); - } - } - }; - /** - * Syntactic glue which holds expressions together - * @private - * @type {Object} - */ - Tone.TimeBase.prototype._syntaxGlue = { - '(': { regexp: /^\(/ }, - ')': { regexp: /^\)/ } - }; - /** - * tokenize the expression based on the Expressions object - * @param {string} expr - * @return {Object} returns two methods on the tokenized list, next and peek - * @private - */ - Tone.TimeBase.prototype._tokenize = function (expr) { - var position = -1; - var tokens = []; - while (expr.length > 0) { - expr = expr.trim(); - var token = getNextToken(expr, this); - tokens.push(token); - expr = expr.substr(token.value.length); - } - function getNextToken(expr, context) { - var expressions = [ - '_binaryExpressions', - '_unaryExpressions', - '_primaryExpressions', - '_syntaxGlue' - ]; - for (var i = 0; i < expressions.length; i++) { - var group = context[expressions[i]]; - for (var opName in group) { - var op = group[opName]; - var reg = op.regexp; - var match = expr.match(reg); - if (match !== null) { - return { - method: op.method, - precedence: op.precedence, - regexp: op.regexp, - value: match[0] - }; - } - } - } - throw new SyntaxError('Tone.TimeBase: Unexpected token ' + expr); - } - return { - next: function () { - return tokens[++position]; - }, - peek: function () { - return tokens[position + 1]; - } - }; - }; - /** - * Given a token, find the value within the groupName - * @param {Object} token - * @param {String} groupName - * @param {Number} precedence - * @private - */ - Tone.TimeBase.prototype._matchGroup = function (token, group, prec) { - var ret = false; - if (!this.isUndef(token)) { - for (var opName in group) { - var op = group[opName]; - if (op.regexp.test(token.value)) { - if (!this.isUndef(prec)) { - if (op.precedence === prec) { - return op; - } - } else { - return op; - } - } - } - } - return ret; - }; - /** - * Match a binary expression given the token and the precedence - * @param {Lexer} lexer - * @param {Number} precedence - * @private - */ - Tone.TimeBase.prototype._parseBinary = function (lexer, precedence) { - if (this.isUndef(precedence)) { - precedence = 2; - } - var expr; - if (precedence < 0) { - expr = this._parseUnary(lexer); - } else { - expr = this._parseBinary(lexer, precedence - 1); - } - var token = lexer.peek(); - while (token && this._matchGroup(token, this._binaryExpressions, precedence)) { - token = lexer.next(); - expr = token.method.bind(this, expr, this._parseBinary(lexer, precedence - 1)); - token = lexer.peek(); - } - return expr; - }; - /** - * Match a unary expression. - * @param {Lexer} lexer - * @private - */ - Tone.TimeBase.prototype._parseUnary = function (lexer) { - var token, expr; - token = lexer.peek(); - var op = this._matchGroup(token, this._unaryExpressions); - if (op) { - token = lexer.next(); - expr = this._parseUnary(lexer); - return op.method.bind(this, expr); - } - return this._parsePrimary(lexer); - }; - /** - * Match a primary expression (a value). - * @param {Lexer} lexer - * @private - */ - Tone.TimeBase.prototype._parsePrimary = function (lexer) { - var token, expr; - token = lexer.peek(); - if (this.isUndef(token)) { - throw new SyntaxError('Tone.TimeBase: Unexpected end of expression'); - } - if (this._matchGroup(token, this._primaryExpressions)) { - token = lexer.next(); - var matching = token.value.match(token.regexp); - return token.method.bind(this, matching[1], matching[2], matching[3]); - } - if (token && token.value === '(') { - lexer.next(); - expr = this._parseBinary(lexer); - token = lexer.next(); - if (!(token && token.value === ')')) { - throw new SyntaxError('Expected )'); - } - return expr; - } - throw new SyntaxError('Tone.TimeBase: Cannot process token ' + token.value); - }; - /** - * Recursively parse the string expression into a syntax tree. - * @param {string} expr - * @return {Function} the bound method to be evaluated later - * @private - */ - Tone.TimeBase.prototype._parseExprString = function (exprString) { - if (!this.isString(exprString)) { - exprString = exprString.toString(); - } - var lexer = this._tokenize(exprString); - var tree = this._parseBinary(lexer); - return tree; - }; - /////////////////////////////////////////////////////////////////////////// - // DEFAULTS - /////////////////////////////////////////////////////////////////////////// - /** - * The initial expression value - * @return {Number} The initial value 0 - * @private - */ - Tone.TimeBase.prototype._noOp = function () { - return 0; - }; - /** - * The default expression value if no arguments are given - * @private - */ - Tone.TimeBase.prototype._defaultExpr = function () { - return this._noOp; - }; - /** - * The default units if none are given. - * @private - */ - Tone.TimeBase.prototype._defaultUnits = 's'; - /////////////////////////////////////////////////////////////////////////// - // UNIT CONVERSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Returns the value of a frequency in the current units - * @param {Frequency} freq - * @return {Number} - * @private - */ - Tone.TimeBase.prototype._frequencyToUnits = function (freq) { - return 1 / freq; - }; - /** - * Return the value of the beats in the current units - * @param {Number} beats - * @return {Number} - * @private - */ - Tone.TimeBase.prototype._beatsToUnits = function (beats) { - return 60 / Tone.Transport.bpm.value * beats; - }; - /** - * Returns the value of a second in the current units - * @param {Seconds} seconds - * @return {Number} - * @private - */ - Tone.TimeBase.prototype._secondsToUnits = function (seconds) { - return seconds; - }; - /** - * Returns the value of a tick in the current time units - * @param {Ticks} ticks - * @return {Number} - * @private - */ - Tone.TimeBase.prototype._ticksToUnits = function (ticks) { - return ticks * (this._beatsToUnits(1) / Tone.Transport.PPQ); - }; - /** - * Return the time signature. - * @return {Number} - * @private - */ - Tone.TimeBase.prototype._timeSignature = function () { - return Tone.Transport.timeSignature; - }; - /////////////////////////////////////////////////////////////////////////// - // EXPRESSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Push an expression onto the expression list - * @param {Time} val - * @param {String} type - * @param {String} units - * @return {Tone.TimeBase} - * @private - */ - Tone.TimeBase.prototype._pushExpr = function (val, name, units) { - //create the expression - if (!(val instanceof Tone.TimeBase)) { - val = new this.constructor(val, units); - } - this._expr = this._binaryExpressions[name].method.bind(this, this._expr, val._expr); - return this; - }; - /** - * Add to the current value. - * @param {Time} val The value to add - * @param {String=} units Optional units to use with the value. - * @return {Tone.TimeBase} this - * @example - * Tone.TimeBase("2m").add("1m"); //"3m" - */ - Tone.TimeBase.prototype.add = function (val, units) { - return this._pushExpr(val, '+', units); - }; - /** - * Subtract the value from the current time. - * @param {Time} val The value to subtract - * @param {String=} units Optional units to use with the value. - * @return {Tone.TimeBase} this - * @example - * Tone.TimeBase("2m").sub("1m"); //"1m" - */ - Tone.TimeBase.prototype.sub = function (val, units) { - return this._pushExpr(val, '-', units); - }; - /** - * Multiply the current value by the given time. - * @param {Time} val The value to multiply - * @param {String=} units Optional units to use with the value. - * @return {Tone.TimeBase} this - * @example - * Tone.TimeBase("2m").mult("2"); //"4m" - */ - Tone.TimeBase.prototype.mult = function (val, units) { - return this._pushExpr(val, '*', units); - }; - /** - * Divide the current value by the given time. - * @param {Time} val The value to divide by - * @param {String=} units Optional units to use with the value. - * @return {Tone.TimeBase} this - * @example - * Tone.TimeBase("2m").div(2); //"1m" - */ - Tone.TimeBase.prototype.div = function (val, units) { - return this._pushExpr(val, '/', units); - }; - /** - * Evaluate the time value. Returns the time - * in seconds. - * @return {Seconds} - */ - Tone.TimeBase.prototype.valueOf = function () { - return this._expr(); - }; - /** - * Clean up - * @return {Tone.TimeBase} this - */ - Tone.TimeBase.prototype.dispose = function () { - this._expr = null; - }; - return Tone.TimeBase; - }); - Module(function (Tone) { - /** - * @class Tone.Time is a primitive type for encoding Time values. - * Eventually all time values are evaluated to seconds - * using the `eval` method. Tone.Time can be constructed - * with or without the `new` keyword. Tone.Time can be passed - * into the parameter of any method which takes time as an argument. - * @constructor - * @extends {Tone.TimeBase} - * @param {String|Number} val The time value. - * @param {String=} units The units of the value. - * @example - * var t = Tone.Time("4n");//encodes a quarter note - * t.mult(4); // multiply that value by 4 - * t.toNotation(); //returns "1m" - */ - Tone.Time = function (val, units) { - if (this instanceof Tone.Time) { - /** - * If the current clock time should - * be added to the output - * @type {Boolean} - * @private - */ - this._plusNow = false; - Tone.TimeBase.call(this, val, units); - } else { - return new Tone.Time(val, units); - } - }; - Tone.extend(Tone.Time, Tone.TimeBase); - //clone the expressions so that - //we can add more without modifying the original - Tone.Time.prototype._unaryExpressions = Object.create(Tone.TimeBase.prototype._unaryExpressions); - /* - * Adds an additional unary expression - * which quantizes values to the next subdivision - * @type {Object} - * @private - */ - Tone.Time.prototype._unaryExpressions.quantize = { - regexp: /^@/, - method: function (rh) { - return Tone.Transport.nextSubdivision(rh()); - } - }; - /* - * Adds an additional unary expression - * which adds the current clock time. - * @type {Object} - * @private - */ - Tone.Time.prototype._unaryExpressions.now = { - regexp: /^\+/, - method: function (lh) { - this._plusNow = true; - return lh(); - } - }; - /** - * Quantize the time by the given subdivision. Optionally add a - * percentage which will move the time value towards the ideal - * quantized value by that percentage. - * @param {Number|Time} val The subdivision to quantize to - * @param {NormalRange} [percent=1] Move the time value - * towards the quantized value by - * a percentage. - * @return {Tone.Time} this - * @example - * Tone.Time(21).quantize(2) //returns 22 - * Tone.Time(0.6).quantize("4n", 0.5) //returns 0.55 - */ - Tone.Time.prototype.quantize = function (subdiv, percent) { - percent = this.defaultArg(percent, 1); - this._expr = function (expr, subdivision, percent) { - expr = expr(); - subdivision = subdivision.toSeconds(); - var multiple = Math.round(expr / subdivision); - var ideal = multiple * subdivision; - var diff = ideal - expr; - return expr + diff * percent; - }.bind(this, this._expr, new this.constructor(subdiv), percent); - return this; - }; - /** - * Adds the clock time to the time expression at the - * moment of evaluation. - * @return {Tone.Time} this - */ - Tone.Time.prototype.addNow = function () { - this._plusNow = true; - return this; - }; - /** - * @override - * Override the default value return when no arguments are passed in. - * The default value is 'now' - * @private - */ - Tone.Time.prototype._defaultExpr = function () { - this._plusNow = true; - return this._noOp; - }; - /** - * Copies the value of time to this Time - * @param {Tone.Time} time - * @return {Time} - */ - Tone.Time.prototype.copy = function (time) { - Tone.TimeBase.prototype.copy.call(this, time); - this._plusNow = time._plusNow; - return this; - }; - //CONVERSIONS////////////////////////////////////////////////////////////// - /** - * Convert a Time to Notation. Values will be thresholded to the nearest 128th note. - * @return {Notation} - * @example - * //if the Transport is at 120bpm: - * Tone.Time(2).toNotation();//returns "1m" - */ - Tone.Time.prototype.toNotation = function () { - var time = this.toSeconds(); - var testNotations = [ - '1m', - '2n', - '4n', - '8n', - '16n', - '32n', - '64n', - '128n' - ]; - var retNotation = this._toNotationHelper(time, testNotations); - //try the same thing but with tripelets - var testTripletNotations = [ - '1m', - '2n', - '2t', - '4n', - '4t', - '8n', - '8t', - '16n', - '16t', - '32n', - '32t', - '64n', - '64t', - '128n' - ]; - var retTripletNotation = this._toNotationHelper(time, testTripletNotations); - //choose the simpler expression of the two - if (retTripletNotation.split('+').length < retNotation.split('+').length) { - return retTripletNotation; - } else { - return retNotation; - } - }; - /** - * Helper method for Tone.toNotation - * @param {Number} units - * @param {Array} testNotations - * @return {String} - * @private - */ - Tone.Time.prototype._toNotationHelper = function (units, testNotations) { - //the threshold is the last value in the array - var threshold = this._notationToUnits(testNotations[testNotations.length - 1]); - var retNotation = ''; - for (var i = 0; i < testNotations.length; i++) { - var notationTime = this._notationToUnits(testNotations[i]); - //account for floating point errors (i.e. round up if the value is 0.999999) - var multiple = units / notationTime; - var floatingPointError = 0.000001; - if (1 - multiple % 1 < floatingPointError) { - multiple += floatingPointError; - } - multiple = Math.floor(multiple); - if (multiple > 0) { - if (multiple === 1) { - retNotation += testNotations[i]; - } else { - retNotation += multiple.toString() + '*' + testNotations[i]; - } - units -= multiple * notationTime; - if (units < threshold) { - break; - } else { - retNotation += ' + '; - } - } - } - if (retNotation === '') { - retNotation = '0'; - } - return retNotation; - }; - /** - * Convert a notation value to the current units - * @param {Notation} notation - * @return {Number} - * @private - */ - Tone.Time.prototype._notationToUnits = function (notation) { - var primaryExprs = this._primaryExpressions; - var notationExprs = [ - primaryExprs.n, - primaryExprs.t, - primaryExprs.m - ]; - for (var i = 0; i < notationExprs.length; i++) { - var expr = notationExprs[i]; - var match = notation.match(expr.regexp); - if (match) { - return expr.method.call(this, match[1]); - } - } - }; - /** - * Return the time encoded as Bars:Beats:Sixteenths. - * @return {BarsBeatsSixteenths} - */ - Tone.Time.prototype.toBarsBeatsSixteenths = function () { - var quarterTime = this._beatsToUnits(1); - var quarters = this.toSeconds() / quarterTime; - var measures = Math.floor(quarters / this._timeSignature()); - var sixteenths = quarters % 1 * 4; - quarters = Math.floor(quarters) % this._timeSignature(); - sixteenths = sixteenths.toString(); - if (sixteenths.length > 3) { - sixteenths = parseFloat(sixteenths).toFixed(3); - } - var progress = [ - measures, - quarters, - sixteenths - ]; - return progress.join(':'); - }; - /** - * Return the time in ticks. - * @return {Ticks} - */ - Tone.Time.prototype.toTicks = function () { - var quarterTime = this._beatsToUnits(1); - var quarters = this.valueOf() / quarterTime; - return Math.floor(quarters * Tone.Transport.PPQ); - }; - /** - * Return the time in samples - * @return {Samples} - */ - Tone.Time.prototype.toSamples = function () { - return this.toSeconds() * this.context.sampleRate; - }; - /** - * Return the time as a frequency value - * @return {Frequency} - * @example - * Tone.Time(2).toFrequency(); //0.5 - */ - Tone.Time.prototype.toFrequency = function () { - return 1 / this.toSeconds(); - }; - /** - * Return the time in seconds. - * @return {Seconds} - */ - Tone.Time.prototype.toSeconds = function () { - return this.valueOf(); - }; - /** - * Return the time in milliseconds. - * @return {Milliseconds} - */ - Tone.Time.prototype.toMilliseconds = function () { - return this.toSeconds() * 1000; - }; - /** - * Return the time in seconds. - * @return {Seconds} - */ - Tone.Time.prototype.valueOf = function () { - var val = this._expr(); - return val + (this._plusNow ? this.now() : 0); - }; - return Tone.Time; - }); - Module(function (Tone) { - /** - * @class Tone.Frequency is a primitive type for encoding Frequency values. - * Eventually all time values are evaluated to hertz - * using the `eval` method. - * @constructor - * @extends {Tone.TimeBase} - * @param {String|Number} val The time value. - * @param {String=} units The units of the value. - * @example - * Tone.Frequency("C3") // 261 - * Tone.Frequency(38, "midi") // - * Tone.Frequency("C3").transpose(4); - */ - Tone.Frequency = function (val, units) { - if (this instanceof Tone.Frequency) { - Tone.TimeBase.call(this, val, units); - } else { - return new Tone.Frequency(val, units); - } - }; - Tone.extend(Tone.Frequency, Tone.TimeBase); - /////////////////////////////////////////////////////////////////////////// - // AUGMENT BASE EXPRESSIONS - /////////////////////////////////////////////////////////////////////////// - //clone the expressions so that - //we can add more without modifying the original - Tone.Frequency.prototype._primaryExpressions = Object.create(Tone.TimeBase.prototype._primaryExpressions); - /* - * midi type primary expression - * @type {Object} - * @private - */ - Tone.Frequency.prototype._primaryExpressions.midi = { - regexp: /^(\d+(?:\.\d+)?midi)/, - method: function (value) { - return this.midiToFrequency(value); - } - }; - /* - * note type primary expression - * @type {Object} - * @private - */ - Tone.Frequency.prototype._primaryExpressions.note = { - regexp: /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i, - method: function (pitch, octave) { - var index = noteToScaleIndex[pitch.toLowerCase()]; - var noteNumber = index + (parseInt(octave) + 1) * 12; - return this.midiToFrequency(noteNumber); - } - }; - /* - * BeatsBarsSixteenths type primary expression - * @type {Object} - * @private - */ - Tone.Frequency.prototype._primaryExpressions.tr = { - regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, - method: function (m, q, s) { - var total = 1; - if (m && m !== '0') { - total *= this._beatsToUnits(this._timeSignature() * parseFloat(m)); - } - if (q && q !== '0') { - total *= this._beatsToUnits(parseFloat(q)); - } - if (s && s !== '0') { - total *= this._beatsToUnits(parseFloat(s) / 4); - } - return total; - } - }; - /////////////////////////////////////////////////////////////////////////// - // EXPRESSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Transposes the frequency by the given number of semitones. - * @param {Interval} interval - * @return {Tone.Frequency} this - * @example - * Tone.Frequency("A4").transpose(3); //"C5" - */ - Tone.Frequency.prototype.transpose = function (interval) { - this._expr = function (expr, interval) { - var val = expr(); - return val * this.intervalToFrequencyRatio(interval); - }.bind(this, this._expr, interval); - return this; - }; - /** - * Takes an array of semitone intervals and returns - * an array of frequencies transposed by those intervals. - * @param {Array} intervals - * @return {Tone.Frequency} this - * @example - * Tone.Frequency("A4").harmonize([0, 3, 7]); //["A4", "C5", "E5"] - */ - Tone.Frequency.prototype.harmonize = function (intervals) { - this._expr = function (expr, intervals) { - var val = expr(); - var ret = []; - for (var i = 0; i < intervals.length; i++) { - ret[i] = val * this.intervalToFrequencyRatio(intervals[i]); - } - return ret; - }.bind(this, this._expr, intervals); - return this; - }; - /////////////////////////////////////////////////////////////////////////// - // UNIT CONVERSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Return the value of the frequency as a MIDI note - * @return {MIDI} - * @example - * Tone.Frequency("C4").toMidi(); //60 - */ - Tone.Frequency.prototype.toMidi = function () { - return this.frequencyToMidi(this.valueOf()); - }; - /** - * Return the value of the frequency in Scientific Pitch Notation - * @return {Note} - * @example - * Tone.Frequency(69, "midi").toNote(); //"A4" - */ - Tone.Frequency.prototype.toNote = function () { - var freq = this.valueOf(); - var log = Math.log(freq / Tone.Frequency.A4) / Math.LN2; - var noteNumber = Math.round(12 * log) + 57; - var octave = Math.floor(noteNumber / 12); - if (octave < 0) { - noteNumber += -12 * octave; - } - var noteName = scaleIndexToNote[noteNumber % 12]; - return noteName + octave.toString(); - }; - /** - * Return the duration of one cycle in seconds. - * @return {Seconds} - */ - Tone.Frequency.prototype.toSeconds = function () { - return 1 / this.valueOf(); - }; - /** - * Return the value in Hertz - * @return {Frequency} - */ - Tone.Frequency.prototype.toFrequency = function () { - return this.valueOf(); - }; - /** - * Return the duration of one cycle in ticks - * @return {Ticks} - */ - Tone.Frequency.prototype.toTicks = function () { - var quarterTime = this._beatsToUnits(1); - var quarters = this.valueOf() / quarterTime; - return Math.floor(quarters * Tone.Transport.PPQ); - }; - /////////////////////////////////////////////////////////////////////////// - // UNIT CONVERSIONS HELPERS - /////////////////////////////////////////////////////////////////////////// - /** - * Returns the value of a frequency in the current units - * @param {Frequency} freq - * @return {Number} - * @private - */ - Tone.Frequency.prototype._frequencyToUnits = function (freq) { - return freq; - }; - /** - * Returns the value of a tick in the current time units - * @param {Ticks} ticks - * @return {Number} - * @private - */ - Tone.Frequency.prototype._ticksToUnits = function (ticks) { - return 1 / (ticks * 60 / (Tone.Transport.bpm.value * Tone.Transport.PPQ)); - }; - /** - * Return the value of the beats in the current units - * @param {Number} beats - * @return {Number} - * @private - */ - Tone.Frequency.prototype._beatsToUnits = function (beats) { - return 1 / Tone.TimeBase.prototype._beatsToUnits.call(this, beats); - }; - /** - * Returns the value of a second in the current units - * @param {Seconds} seconds - * @return {Number} - * @private - */ - Tone.Frequency.prototype._secondsToUnits = function (seconds) { - return 1 / seconds; - }; - /** - * The default units if none are given. - * @private - */ - Tone.Frequency.prototype._defaultUnits = 'hz'; - /////////////////////////////////////////////////////////////////////////// - // FREQUENCY CONVERSIONS - /////////////////////////////////////////////////////////////////////////// - /** - * Note to scale index - * @type {Object} - */ - var noteToScaleIndex = { - 'cbb': -2, - 'cb': -1, - 'c': 0, - 'c#': 1, - 'cx': 2, - 'dbb': 0, - 'db': 1, - 'd': 2, - 'd#': 3, - 'dx': 4, - 'ebb': 2, - 'eb': 3, - 'e': 4, - 'e#': 5, - 'ex': 6, - 'fbb': 3, - 'fb': 4, - 'f': 5, - 'f#': 6, - 'fx': 7, - 'gbb': 5, - 'gb': 6, - 'g': 7, - 'g#': 8, - 'gx': 9, - 'abb': 7, - 'ab': 8, - 'a': 9, - 'a#': 10, - 'ax': 11, - 'bbb': 9, - 'bb': 10, - 'b': 11, - 'b#': 12, - 'bx': 13 - }; - /** - * scale index to note (sharps) - * @type {Array} - */ - var scaleIndexToNote = [ - 'C', - 'C#', - 'D', - 'D#', - 'E', - 'F', - 'F#', - 'G', - 'G#', - 'A', - 'A#', - 'B' - ]; - /** - * The [concert pitch](https://en.wikipedia.org/wiki/Concert_pitch) - * A4's values in Hertz. - * @type {Frequency} - * @static - */ - Tone.Frequency.A4 = 440; - /** - * Convert a MIDI note to frequency value. - * @param {MIDI} midi The midi number to convert. - * @return {Frequency} the corresponding frequency value - * @example - * tone.midiToFrequency(69); // returns 440 - */ - Tone.Frequency.prototype.midiToFrequency = function (midi) { - return Tone.Frequency.A4 * Math.pow(2, (midi - 69) / 12); - }; - /** - * Convert a frequency value to a MIDI note. - * @param {Frequency} frequency The value to frequency value to convert. - * @returns {MIDI} - * @example - * tone.midiToFrequency(440); // returns 69 - */ - Tone.Frequency.prototype.frequencyToMidi = function (frequency) { - return 69 + 12 * Math.log(frequency / Tone.Frequency.A4) / Math.LN2; - }; - return Tone.Frequency; - }); - Module(function (Tone) { - /** - * @class Tone.TransportTime is a the time along the Transport's - * timeline. It is similar to Tone.Time, but instead of evaluating - * against the AudioContext's clock, it is evaluated against - * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime). - * @constructor - * @param {Time} val The time value as a number or string - * @param {String=} units Unit values - * @extends {Tone.Time} - */ - Tone.TransportTime = function (val, units) { - if (this instanceof Tone.TransportTime) { - Tone.Time.call(this, val, units); - } else { - return new Tone.TransportTime(val, units); - } - }; - Tone.extend(Tone.TransportTime, Tone.Time); - //clone the expressions so that - //we can add more without modifying the original - Tone.TransportTime.prototype._unaryExpressions = Object.create(Tone.Time.prototype._unaryExpressions); - /** - * Adds an additional unary expression - * which quantizes values to the next subdivision - * @type {Object} - * @private - */ - Tone.TransportTime.prototype._unaryExpressions.quantize = { - regexp: /^@/, - method: function (rh) { - var subdivision = this._secondsToTicks(rh()); - var multiple = Math.ceil(Tone.Transport.ticks / subdivision); - return this._ticksToUnits(multiple * subdivision); - } - }; - /** - * Convert seconds into ticks - * @param {Seconds} seconds - * @return {Ticks} - * @private - */ - Tone.TransportTime.prototype._secondsToTicks = function (seconds) { - var quarterTime = this._beatsToUnits(1); - var quarters = seconds / quarterTime; - return Math.round(quarters * Tone.Transport.PPQ); - }; - /** - * Evaluate the time expression. Returns values in ticks - * @return {Ticks} - */ - Tone.TransportTime.prototype.valueOf = function () { - var val = this._secondsToTicks(this._expr()); - return val + (this._plusNow ? Tone.Transport.ticks : 0); - }; - /** - * Return the time in ticks. - * @return {Ticks} - */ - Tone.TransportTime.prototype.toTicks = function () { - return this.valueOf(); - }; - /** - * Return the time in seconds. - * @return {Seconds} - */ - Tone.TransportTime.prototype.toSeconds = function () { - var val = this._expr(); - return val + (this._plusNow ? Tone.Transport.seconds : 0); - }; - /** - * Return the time as a frequency value - * @return {Frequency} - */ - Tone.TransportTime.prototype.toFrequency = function () { - return 1 / this.toSeconds(); - }; - return Tone.TransportTime; - }); - Module(function (Tone) { - - /** - * @class Tone.Emitter gives classes which extend it - * the ability to listen for and emit events. - * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js). - * MIT (c) 2011 Jerome Etienne. - * - * @extends {Tone} - */ - Tone.Emitter = function () { - /** - * Contains all of the events. - * @private - * @type {Object} - */ - this._events = {}; - }; - Tone.extend(Tone.Emitter); - /** - * Bind a callback to a specific event. - * @param {String} event The name of the event to listen for. - * @param {Function} callback The callback to invoke when the - * event is emitted - * @return {Tone.Emitter} this - */ - Tone.Emitter.prototype.on = function (event, callback) { - //split the event - var events = event.split(/\W+/); - for (var i = 0; i < events.length; i++) { - var eventName = events[i]; - if (!this._events.hasOwnProperty(eventName)) { - this._events[eventName] = []; - } - this._events[eventName].push(callback); - } - return this; - }; - /** - * Remove the event listener. - * @param {String} event The event to stop listening to. - * @param {Function=} callback The callback which was bound to - * the event with Tone.Emitter.on. - * If no callback is given, all callbacks - * events are removed. - * @return {Tone.Emitter} this - */ - Tone.Emitter.prototype.off = function (event, callback) { - var events = event.split(/\W+/); - for (var ev = 0; ev < events.length; ev++) { - event = events[ev]; - if (this._events.hasOwnProperty(event)) { - if (Tone.prototype.isUndef(callback)) { - this._events[event] = []; - } else { - var eventList = this._events[event]; - for (var i = 0; i < eventList.length; i++) { - if (eventList[i] === callback) { - eventList.splice(i, 1); - } - } - } - } - } - return this; - }; - /** - * Invoke all of the callbacks bound to the event - * with any arguments passed in. - * @param {String} event The name of the event. - * @param {*...} args The arguments to pass to the functions listening. - * @return {Tone.Emitter} this - */ - Tone.Emitter.prototype.emit = function (event) { - if (this._events) { - var args = Array.apply(null, arguments).slice(1); - if (this._events.hasOwnProperty(event)) { - var eventList = this._events[event]; - for (var i = 0, len = eventList.length; i < len; i++) { - eventList[i].apply(this, args); - } - } - } - return this; - }; - /** - * Add Emitter functions (on/off/emit) to the object - * @param {Object|Function} object The object or class to extend. - */ - Tone.Emitter.mixin = function (object) { - var functions = [ - 'on', - 'off', - 'emit' - ]; - object._events = {}; - for (var i = 0; i < functions.length; i++) { - var func = functions[i]; - var emitterFunc = Tone.Emitter.prototype[func]; - object[func] = emitterFunc; - } - }; - /** - * Clean up - * @return {Tone.Emitter} this - */ - Tone.Emitter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._events = null; - return this; - }; - return Tone.Emitter; - }); - Module(function (Tone) { - /** - * shim - * @private - */ - if (!window.hasOwnProperty('AudioContext') && window.hasOwnProperty('webkitAudioContext')) { - window.AudioContext = window.webkitAudioContext; - } - /** - * @class Wrapper around the native AudioContext. - * @extends {Tone.Emitter} - * @param {AudioContext=} context optionally pass in a context - */ - Tone.Context = function (context) { - Tone.Emitter.call(this); - if (!context) { - context = new window.AudioContext(); - } - this._context = context; - // extend all of the methods - for (var prop in this._context) { - this._defineProperty(this._context, prop); - } - /////////////////////////////////////////////////////////////////////// - // WORKER - /////////////////////////////////////////////////////////////////////// - /** - * The default latency hint - * @type {String} - * @private - */ - this._latencyHint = 'interactive'; - /** - * The amount of time events are scheduled - * into the future - * @type {Number} - * @private - */ - this._lookAhead = 0.1; - /** - * How often the update look runs - * @type {Number} - * @private - */ - this._updateInterval = this._lookAhead / 3; - /** - * A reference to the actual computed update interval - * @type {Number} - * @private - */ - this._computedUpdateInterval = 0; - /** - * The web worker which is used to update Tone.Clock - * @private - * @type {WebWorker} - */ - this._worker = this._createWorker(); - /** - * An object containing all of the constants AudioBufferSourceNodes - * @type {Object} - * @private - */ - this._constants = {}; - }; - Tone.extend(Tone.Context, Tone.Emitter); - Tone.Emitter.mixin(Tone.Context); - /** - * Define a property on this Tone.Context. - * This is used to extend the native AudioContext - * @param {AudioContext} context - * @param {String} prop - * @private - */ - Tone.Context.prototype._defineProperty = function (context, prop) { - if (this.isUndef(this[prop])) { - Object.defineProperty(this, prop, { - get: function () { - if (typeof context[prop] === 'function') { - return context[prop].bind(context); - } else { - return context[prop]; - } - }, - set: function (val) { - context[prop] = val; - } - }); - } - }; - /** - * The current audio context time - * @return {Number} - */ - Tone.Context.prototype.now = function () { - return this._context.currentTime; - }; - /** - * Generate a web worker - * @return {WebWorker} - * @private - */ - Tone.Context.prototype._createWorker = function () { - //URL Shim - window.URL = window.URL || window.webkitURL; - var blob = new Blob([//the initial timeout time - 'var timeoutTime = ' + (this._updateInterval * 1000).toFixed(1) + ';' + //onmessage callback - 'self.onmessage = function(msg){' + '\ttimeoutTime = parseInt(msg.data);' + '};' + //the tick function which posts a message - //and schedules a new tick - 'function tick(){' + '\tsetTimeout(tick, timeoutTime);' + '\tself.postMessage(\'tick\');' + '}' + //call tick initially - 'tick();']); - var blobUrl = URL.createObjectURL(blob); - var worker = new Worker(blobUrl); - worker.addEventListener('message', function () { - // tick the clock - this.emit('tick'); - }.bind(this)); - //lag compensation - worker.addEventListener('message', function () { - var now = this.now(); - if (this.isNumber(this._lastUpdate)) { - var diff = now - this._lastUpdate; - this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97); - } - this._lastUpdate = now; - }.bind(this)); - return worker; - }; - /** - * Generate a looped buffer at some constant value. - * @param {Number} val - * @return {BufferSourceNode} - */ - Tone.Context.prototype.getConstant = function (val) { - if (this._constants[val]) { - return this._constants[val]; - } else { - var buffer = this._context.createBuffer(1, 128, this._context.sampleRate); - var arr = buffer.getChannelData(0); - for (var i = 0; i < arr.length; i++) { - arr[i] = val; - } - var constant = this._context.createBufferSource(); - constant.channelCount = 1; - constant.channelCountMode = 'explicit'; - constant.buffer = buffer; - constant.loop = true; - constant.start(0); - this._constants[val] = constant; - return constant; - } - }; - /** - * This is the time that the clock is falling behind - * the scheduled update interval. The Context automatically - * adjusts for the lag and schedules further in advance. - * @type {Number} - * @memberOf Tone.Context - * @name lag - * @static - * @readOnly - */ - Object.defineProperty(Tone.Context.prototype, 'lag', { - get: function () { - var diff = this._computedUpdateInterval - this._updateInterval; - diff = Math.max(diff, 0); - return diff; - } - }); - /** - * The amount of time in advance that events are scheduled. - * The lookAhead will adjust slightly in response to the - * measured update time to try to avoid clicks. - * @type {Number} - * @memberOf Tone.Context - * @name lookAhead - * @static - */ - Object.defineProperty(Tone.Context.prototype, 'lookAhead', { - get: function () { - return this._lookAhead; - }, - set: function (lA) { - this._lookAhead = lA; - } - }); - /** - * How often the Web Worker callback is invoked. - * This number corresponds to how responsive the scheduling - * can be. Context.updateInterval + Context.lookAhead gives you the - * total latency between scheduling an event and hearing it. - * @type {Number} - * @memberOf Tone.Context - * @name updateInterval - * @static - */ - Object.defineProperty(Tone.Context.prototype, 'updateInterval', { - get: function () { - return this._updateInterval; - }, - set: function (interval) { - this._updateInterval = Math.max(interval, Tone.prototype.blockTime); - this._worker.postMessage(Math.max(interval * 1000, 1)); - } - }); - /** - * The type of playback, which affects tradeoffs between audio - * output latency and responsiveness. - * - * In addition to setting the value in seconds, the latencyHint also - * accepts the strings "interactive" (prioritizes low latency), - * "playback" (prioritizes sustained playback), "balanced" (balances - * latency and performance), and "fastest" (lowest latency, might glitch more often). - * @type {String|Seconds} - * @memberOf Tone.Context# - * @name latencyHint - * @static - * @example - * //set the lookAhead to 0.3 seconds - * Tone.context.latencyHint = 0.3; - */ - Object.defineProperty(Tone.Context.prototype, 'latencyHint', { - get: function () { - return this._latencyHint; - }, - set: function (hint) { - var lookAhead = hint; - this._latencyHint = hint; - if (this.isString(hint)) { - switch (hint) { - case 'interactive': - lookAhead = 0.1; - this._context.latencyHint = hint; - break; - case 'playback': - lookAhead = 0.8; - this._context.latencyHint = hint; - break; - case 'balanced': - lookAhead = 0.25; - this._context.latencyHint = hint; - break; - case 'fastest': - lookAhead = 0.01; - break; - } - } - this.lookAhead = lookAhead; - this.updateInterval = lookAhead / 3; - } - }); - /** - * Shim all connect/disconnect and some deprecated methods which are still in - * some older implementations. - * @private - */ - function shimConnect() { - var nativeConnect = AudioNode.prototype.connect; - var nativeDisconnect = AudioNode.prototype.disconnect; - //replace the old connect method - function toneConnect(B, outNum, inNum) { - if (B.input) { - if (Array.isArray(B.input)) { - if (Tone.prototype.isUndef(inNum)) { - inNum = 0; - } - this.connect(B.input[inNum]); - } else { - this.connect(B.input, outNum, inNum); - } - } else { - try { - if (B instanceof AudioNode) { - nativeConnect.call(this, B, outNum, inNum); - } else { - nativeConnect.call(this, B, outNum); - } - } catch (e) { - throw new Error('error connecting to node: ' + B + '\n' + e); - } - } - } - //replace the old disconnect method - function toneDisconnect(B, outNum, inNum) { - if (B && B.input && Array.isArray(B.input)) { - if (Tone.prototype.isUndef(inNum)) { - inNum = 0; - } - this.disconnect(B.input[inNum], outNum, inNum); - } else if (B && B.input) { - this.disconnect(B.input, outNum, inNum); - } else { - try { - nativeDisconnect.apply(this, arguments); - } catch (e) { - throw new Error('error disconnecting node: ' + B + '\n' + e); - } - } - } - if (AudioNode.prototype.connect !== toneConnect) { - AudioNode.prototype.connect = toneConnect; - AudioNode.prototype.disconnect = toneDisconnect; - } - } - // set the audio context initially - if (Tone.supported) { - shimConnect(); - Tone.context = new Tone.Context(); - } else { - console.warn('This browser does not support Tone.js'); - } - return Tone.Context; - }); - Module(function (Tone) { - /////////////////////////////////////////////////////////////////////////// - // TYPES - /////////////////////////////////////////////////////////////////////////// - /** - * Units which a value can take on. - * @enum {String} - */ - Tone.Type = { - /** - * Default units - * @typedef {Default} - */ - Default: 'number', - /** - * Time can be described in a number of ways. Read more [Time](https://github.com/Tonejs/Tone.js/wiki/Time). - * - * - * - * @typedef {Time} - */ - Time: 'time', - /** - * Frequency can be described similar to time, except ultimately the - * values are converted to frequency instead of seconds. A number - * is taken literally as the value in hertz. Additionally any of the - * Time encodings can be used. Note names in the form - * of NOTE OCTAVE (i.e. C4) are also accepted and converted to their - * frequency value. - * @typedef {Frequency} - */ - Frequency: 'frequency', - /** - * TransportTime describes a position along the Transport's timeline. It is - * similar to Time in that it uses all the same encodings, but TransportTime specifically - * pertains to the Transport's timeline, which is startable, stoppable, loopable, and seekable. - * [Read more](https://github.com/Tonejs/Tone.js/wiki/TransportTime) - * @typedef {TransportTime} - */ - TransportTime: 'transportTime', - /** - * Ticks are the basic subunit of the Transport. They are - * the smallest unit of time that the Transport supports. - * @typedef {Ticks} - */ - Ticks: 'ticks', - /** - * Normal values are within the range [0, 1]. - * @typedef {NormalRange} - */ - NormalRange: 'normalRange', - /** - * AudioRange values are between [-1, 1]. - * @typedef {AudioRange} - */ - AudioRange: 'audioRange', - /** - * Decibels are a logarithmic unit of measurement which is useful for volume - * because of the logarithmic way that we perceive loudness. 0 decibels - * means no change in volume. -10db is approximately half as loud and 10db - * is twice is loud. - * @typedef {Decibels} - */ - Decibels: 'db', - /** - * Half-step note increments, i.e. 12 is an octave above the root. and 1 is a half-step up. - * @typedef {Interval} - */ - Interval: 'interval', - /** - * Beats per minute. - * @typedef {BPM} - */ - BPM: 'bpm', - /** - * The value must be greater than or equal to 0. - * @typedef {Positive} - */ - Positive: 'positive', - /** - * A cent is a hundredth of a semitone. - * @typedef {Cents} - */ - Cents: 'cents', - /** - * Angle between 0 and 360. - * @typedef {Degrees} - */ - Degrees: 'degrees', - /** - * A number representing a midi note. - * @typedef {MIDI} - */ - MIDI: 'midi', - /** - * A colon-separated representation of time in the form of - * Bars:Beats:Sixteenths. - * @typedef {BarsBeatsSixteenths} - */ - BarsBeatsSixteenths: 'barsBeatsSixteenths', - /** - * Sampling is the reduction of a continuous signal to a discrete signal. - * Audio is typically sampled 44100 times per second. - * @typedef {Samples} - */ - Samples: 'samples', - /** - * Hertz are a frequency representation defined as one cycle per second. - * @typedef {Hertz} - */ - Hertz: 'hertz', - /** - * A frequency represented by a letter name, - * accidental and octave. This system is known as - * [Scientific Pitch Notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation). - * @typedef {Note} - */ - Note: 'note', - /** - * One millisecond is a thousandth of a second. - * @typedef {Milliseconds} - */ - Milliseconds: 'milliseconds', - /** - * Seconds are the time unit of the AudioContext. In the end, - * all values need to be evaluated to seconds. - * @typedef {Seconds} - */ - Seconds: 'seconds', - /** - * A string representing a duration relative to a measure. - * - * @typedef {Notation} - */ - Notation: 'notation' - }; - /////////////////////////////////////////////////////////////////////////// - // AUGMENT TONE's PROTOTYPE - /////////////////////////////////////////////////////////////////////////// - /** - * Convert Time into seconds. - * - * Unlike the method which it overrides, this takes into account - * transporttime and musical notation. - * - * Time : 1.40 - * Notation: 4n|1m|2t - * Now Relative: +3n - * Math: 3n+16n or even complicated expressions ((3n*2)/6 + 1) - * - * @param {Time} time - * @return {Seconds} - */ - Tone.prototype.toSeconds = function (time) { - if (this.isNumber(time)) { - return time; - } else if (this.isUndef(time)) { - return this.now(); - } else if (this.isString(time)) { - return new Tone.Time(time).toSeconds(); - } else if (time instanceof Tone.TimeBase) { - return time.toSeconds(); - } - }; - /** - * Convert a frequency representation into a number. - * @param {Frequency} freq - * @return {Hertz} the frequency in hertz - */ - Tone.prototype.toFrequency = function (freq) { - if (this.isNumber(freq)) { - return freq; - } else if (this.isString(freq) || this.isUndef(freq)) { - return new Tone.Frequency(freq).valueOf(); - } else if (freq instanceof Tone.TimeBase) { - return freq.toFrequency(); - } - }; - /** - * Convert a time representation into ticks. - * @param {Time} time - * @return {Ticks} the time in ticks - */ - Tone.prototype.toTicks = function (time) { - if (this.isNumber(time) || this.isString(time)) { - return new Tone.TransportTime(time).toTicks(); - } else if (this.isUndef(time)) { - return Tone.Transport.ticks; - } else if (time instanceof Tone.TimeBase) { - return time.toTicks(); - } - }; - return Tone; - }); - Module(function (Tone) { - - /** - * @class Tone.Param wraps the native Web Audio's AudioParam to provide - * additional unit conversion functionality. It also - * serves as a base-class for classes which have a single, - * automatable parameter. - * @extends {Tone} - * @param {AudioParam} param The parameter to wrap. - * @param {Tone.Type} units The units of the audio param. - * @param {Boolean} convert If the param should be converted. - */ - Tone.Param = function () { - var options = this.optionsObject(arguments, [ - 'param', - 'units', - 'convert' - ], Tone.Param.defaults); - /** - * The native parameter to control - * @type {AudioParam} - * @private - */ - this._param = this.input = options.param; - /** - * The units of the parameter - * @type {Tone.Type} - */ - this.units = options.units; - /** - * If the value should be converted or not - * @type {Boolean} - */ - this.convert = options.convert; - /** - * True if the signal value is being overridden by - * a connected signal. - * @readOnly - * @type {boolean} - * @private - */ - this.overridden = false; - /** - * If there is an LFO, this is where it is held. - * @type {Tone.LFO} - * @private - */ - this._lfo = null; - if (this.isObject(options.lfo)) { - this.value = options.lfo; - } else if (!this.isUndef(options.value)) { - this.value = options.value; - } - }; - Tone.extend(Tone.Param); - /** - * Defaults - * @type {Object} - * @const - */ - Tone.Param.defaults = { - 'units': Tone.Type.Default, - 'convert': true, - 'param': undefined - }; - /** - * The current value of the parameter. - * @memberOf Tone.Param# - * @type {Number} - * @name value - */ - Object.defineProperty(Tone.Param.prototype, 'value', { - get: function () { - return this._toUnits(this._param.value); - }, - set: function (value) { - if (this.isObject(value)) { - //throw an error if the LFO needs to be included - if (this.isUndef(Tone.LFO)) { - throw new Error('Include \'Tone.LFO\' to use an LFO as a Param value.'); - } - //remove the old one - if (this._lfo) { - this._lfo.dispose(); - } - this._lfo = new Tone.LFO(value).start(); - this._lfo.connect(this.input); - } else { - var convertedVal = this._fromUnits(value); - this._param.cancelScheduledValues(0); - this._param.value = convertedVal; - } - } - }); - /** - * Convert the given value from the type specified by Tone.Param.units - * into the destination value (such as Gain or Frequency). - * @private - * @param {*} val the value to convert - * @return {number} the number which the value should be set to - */ - Tone.Param.prototype._fromUnits = function (val) { - if (this.convert || this.isUndef(this.convert)) { - switch (this.units) { - case Tone.Type.Time: - return this.toSeconds(val); - case Tone.Type.Frequency: - return this.toFrequency(val); - case Tone.Type.Decibels: - return this.dbToGain(val); - case Tone.Type.NormalRange: - return Math.min(Math.max(val, 0), 1); - case Tone.Type.AudioRange: - return Math.min(Math.max(val, -1), 1); - case Tone.Type.Positive: - return Math.max(val, 0); - default: - return val; - } - } else { - return val; - } - }; - /** - * Convert the parameters value into the units specified by Tone.Param.units. - * @private - * @param {number} val the value to convert - * @return {number} - */ - Tone.Param.prototype._toUnits = function (val) { - if (this.convert || this.isUndef(this.convert)) { - switch (this.units) { - case Tone.Type.Decibels: - return this.gainToDb(val); - default: - return val; - } - } else { - return val; - } - }; - /** - * the minimum output value - * @type {Number} - * @private - */ - Tone.Param.prototype._minOutput = 0.00001; - /** - * Schedules a parameter value change at the given time. - * @param {*} value The value to set the signal. - * @param {Time} time The time when the change should occur. - * @returns {Tone.Param} this - * @example - * //set the frequency to "G4" in exactly 1 second from now. - * freq.setValueAtTime("G4", "+1"); - */ - Tone.Param.prototype.setValueAtTime = function (value, time) { - value = this._fromUnits(value); - time = this.toSeconds(time); - if (time <= this.now() + this.blockTime) { - this._param.value = value; - } else { - this._param.setValueAtTime(value, time); - } - return this; - }; - /** - * Creates a schedule point with the current value at the current time. - * This is useful for creating an automation anchor point in order to - * schedule changes from the current value. - * - * @param {number=} now (Optionally) pass the now value in. - * @returns {Tone.Param} this - */ - Tone.Param.prototype.setRampPoint = function (now) { - now = this.defaultArg(now, this.now()); - var currentVal = this._param.value; - // exponentialRampToValueAt cannot ever ramp from or to 0 - // More info: https://bugzilla.mozilla.org/show_bug.cgi?id=1125600#c2 - if (currentVal === 0) { - currentVal = this._minOutput; - } - this._param.setValueAtTime(currentVal, now); - return this; - }; - /** - * Schedules a linear continuous change in parameter value from the - * previous scheduled parameter value to the given value. - * - * @param {number} value - * @param {Time} endTime - * @returns {Tone.Param} this - */ - Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { - value = this._fromUnits(value); - this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); - return this; - }; - /** - * Schedules an exponential continuous change in parameter value from - * the previous scheduled parameter value to the given value. - * - * @param {number} value - * @param {Time} endTime - * @returns {Tone.Param} this - */ - Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { - value = this._fromUnits(value); - value = Math.max(this._minOutput, value); - this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); - return this; - }; - /** - * Schedules an exponential continuous change in parameter value from - * the current time and current value to the given value over the - * duration of the rampTime. - * - * @param {number} value The value to ramp to. - * @param {Time} rampTime the time that it takes the - * value to ramp from it's current value - * @param {Time} [startTime=now] When the ramp should start. - * @returns {Tone.Param} this - * @example - * //exponentially ramp to the value 2 over 4 seconds. - * signal.exponentialRampToValue(2, 4); - */ - Tone.Param.prototype.exponentialRampToValue = function (value, rampTime, startTime) { - startTime = this.toSeconds(startTime); - this.setRampPoint(startTime); - this.exponentialRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); - return this; - }; - /** - * Schedules an linear continuous change in parameter value from - * the current time and current value to the given value over the - * duration of the rampTime. - * - * @param {number} value The value to ramp to. - * @param {Time} rampTime the time that it takes the - * value to ramp from it's current value - * @param {Time} [startTime=now] When the ramp should start. - * @returns {Tone.Param} this - * @example - * //linearly ramp to the value 4 over 3 seconds. - * signal.linearRampToValue(4, 3); - */ - Tone.Param.prototype.linearRampToValue = function (value, rampTime, startTime) { - startTime = this.toSeconds(startTime); - this.setRampPoint(startTime); - this.linearRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); - return this; - }; - /** - * Start exponentially approaching the target value at the given time with - * a rate having the given time constant. - * @param {number} value - * @param {Time} startTime - * @param {number} timeConstant - * @returns {Tone.Param} this - */ - Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { - value = this._fromUnits(value); - // The value will never be able to approach without timeConstant > 0. - // http://www.w3.org/TR/webaudio/#dfn-setTargetAtTime, where the equation - // is described. 0 results in a division by 0. - value = Math.max(this._minOutput, value); - timeConstant = Math.max(this._minOutput, timeConstant); - this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); - return this; - }; - /** - * Sets an array of arbitrary parameter values starting at the given time - * for the given duration. - * - * @param {Array} values - * @param {Time} startTime - * @param {Time} duration - * @returns {Tone.Param} this - */ - Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { - for (var i = 0; i < values.length; i++) { - values[i] = this._fromUnits(values[i]); - } - this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); - return this; - }; - /** - * Cancels all scheduled parameter changes with times greater than or - * equal to startTime. - * - * @param {Time} startTime - * @returns {Tone.Param} this - */ - Tone.Param.prototype.cancelScheduledValues = function (startTime) { - this._param.cancelScheduledValues(this.toSeconds(startTime)); - return this; - }; - /** - * Ramps to the given value over the duration of the rampTime. - * Automatically selects the best ramp type (exponential or linear) - * depending on the `units` of the signal - * - * @param {number} value - * @param {Time} rampTime The time that it takes the - * value to ramp from it's current value - * @param {Time} [startTime=now] When the ramp should start. - * @returns {Tone.Param} this - * @example - * //ramp to the value either linearly or exponentially - * //depending on the "units" value of the signal - * signal.rampTo(0, 10); - * @example - * //schedule it to ramp starting at a specific time - * signal.rampTo(0, 10, 5) - */ - Tone.Param.prototype.rampTo = function (value, rampTime, startTime) { - rampTime = this.defaultArg(rampTime, 0); - if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM || this.units === Tone.Type.Decibels) { - this.exponentialRampToValue(value, rampTime, startTime); - } else { - this.linearRampToValue(value, rampTime, startTime); - } - return this; - }; - /** - * The LFO created by the signal instance. If none - * was created, this is null. - * @type {Tone.LFO} - * @readOnly - * @memberOf Tone.Param# - * @name lfo - */ - Object.defineProperty(Tone.Param.prototype, 'lfo', { - get: function () { - return this._lfo; - } - }); - /** - * Clean up - * @returns {Tone.Param} this - */ - Tone.Param.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._param = null; - if (this._lfo) { - this._lfo.dispose(); - this._lfo = null; - } - return this; - }; - return Tone.Param; - }); - Module(function (Tone) { - - /** - * createGain shim - * @private - */ - if (window.GainNode && !AudioContext.prototype.createGain) { - AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; - } - /** - * @class A thin wrapper around the Native Web Audio GainNode. - * The GainNode is a basic building block of the Web Audio - * API and is useful for routing audio and adjusting gains. - * @extends {Tone} - * @param {Number=} gain The initial gain of the GainNode - * @param {Tone.Type=} units The units of the gain parameter. - */ - Tone.Gain = function () { - var options = this.optionsObject(arguments, [ - 'gain', - 'units' - ], Tone.Gain.defaults); - /** - * The GainNode - * @type {GainNode} - * @private - */ - this.input = this.output = this._gainNode = this.context.createGain(); - /** - * The gain parameter of the gain node. - * @type {Tone.Param} - * @signal - */ - this.gain = new Tone.Param({ - 'param': this._gainNode.gain, - 'units': options.units, - 'value': options.gain, - 'convert': options.convert - }); - this._readOnly('gain'); - }; - Tone.extend(Tone.Gain); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.Gain.defaults = { - 'gain': 1, - 'convert': true - }; - /** - * Clean up. - * @return {Tone.Gain} this - */ - Tone.Gain.prototype.dispose = function () { - Tone.Param.prototype.dispose.call(this); - this._gainNode.disconnect(); - this._gainNode = null; - this._writable('gain'); - this.gain.dispose(); - this.gain = null; - }; - //STATIC/////////////////////////////////////////////////////////////////// - /** - * Create input and outputs for this object. - * @param {Number} input The number of inputs - * @param {Number=} outputs The number of outputs - * @return {Tone} this - * @internal - */ - Tone.prototype.createInsOuts = function (inputs, outputs) { - if (inputs === 1) { - this.input = new Tone.Gain(); - } else if (inputs > 1) { - this.input = new Array(inputs); - } - if (outputs === 1) { - this.output = new Tone.Gain(); - } else if (outputs > 1) { - this.output = new Array(inputs); - } - }; - /////////////////////////////////////////////////////////////////////////// - return Tone.Gain; - }); - Module(function (Tone) { - - /** - * @class A signal is an audio-rate value. Tone.Signal is a core component of the library. - * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal - * has all of the methods available to native Web Audio - * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface) - * as well as additional conveniences. Read more about working with signals - * [here](https://github.com/Tonejs/Tone.js/wiki/Signals). - * - * @constructor - * @extends {Tone.Param} - * @param {Number|AudioParam} [value] Initial value of the signal. If an AudioParam - * is passed in, that parameter will be wrapped - * and controlled by the Signal. - * @param {string} [units=Number] unit The units the signal is in. - * @example - * var signal = new Tone.Signal(10); - */ - Tone.Signal = function () { - var options = this.optionsObject(arguments, [ - 'value', - 'units' - ], Tone.Signal.defaults); - /** - * The node where the constant signal value is scaled. - * @type {GainNode} - * @private - */ - this.output = this._gain = this.context.createGain(); - options.param = this._gain.gain; - Tone.Param.call(this, options); - /** - * The node where the value is set. - * @type {Tone.Param} - * @private - */ - this.input = this._param = this._gain.gain; - //connect the const output to the node output - this.context.getConstant(1).chain(this._gain); - }; - Tone.extend(Tone.Signal, Tone.Param); - /** - * The default values - * @type {Object} - * @static - * @const - */ - Tone.Signal.defaults = { - 'value': 0, - 'units': Tone.Type.Default, - 'convert': true - }; - /** - * When signals connect to other signals or AudioParams, - * they take over the output value of that signal or AudioParam. - * For all other nodes, the behavior is the same as a default connect. - * - * @override - * @param {AudioParam|AudioNode|Tone.Signal|Tone} node - * @param {number} [outputNumber=0] The output number to connect from. - * @param {number} [inputNumber=0] The input number to connect to. - * @returns {Tone.SignalBase} this - * @method - */ - Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; - /** - * dispose and disconnect - * @returns {Tone.Signal} this - */ - Tone.Signal.prototype.dispose = function () { - Tone.Param.prototype.dispose.call(this); - this._param = null; - this._gain.disconnect(); - this._gain = null; - return this; - }; - return Tone.Signal; - }); - Module(function (Tone) { - - /** - * @class A Timeline class for scheduling and maintaining state - * along a timeline. All events must have a "time" property. - * Internally, events are stored in time order for fast - * retrieval. - * @extends {Tone} - * @param {Positive} [memory=Infinity] The number of previous events that are retained. - */ - Tone.Timeline = function () { - var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); - /** - * The array of scheduled timeline events - * @type {Array} - * @private - */ - this._timeline = []; - /** - * An array of items to remove from the list. - * @type {Array} - * @private - */ - this._toRemove = []; - /** - * Flag if the tieline is mid iteration - * @private - * @type {Boolean} - */ - this._iterating = false; - /** - * The memory of the timeline, i.e. - * how many events in the past it will retain - * @type {Positive} - */ - this.memory = options.memory; - }; - Tone.extend(Tone.Timeline); - /** - * the default parameters - * @static - * @const - */ - Tone.Timeline.defaults = { 'memory': Infinity }; - /** - * The number of items in the timeline. - * @type {Number} - * @memberOf Tone.Timeline# - * @name length - * @readOnly - */ - Object.defineProperty(Tone.Timeline.prototype, 'length', { - get: function () { - return this._timeline.length; - } - }); - /** - * Insert an event object onto the timeline. Events must have a "time" attribute. - * @param {Object} event The event object to insert into the - * timeline. - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.add = function (event) { - //the event needs to have a time attribute - if (this.isUndef(event.time)) { - throw new Error('Tone.Timeline: events must have a time attribute'); - } - if (this._timeline.length) { - var index = this._search(event.time); - this._timeline.splice(index + 1, 0, event); - } else { - this._timeline.push(event); - } - //if the length is more than the memory, remove the previous ones - if (this.length > this.memory) { - var diff = this.length - this.memory; - this._timeline.splice(0, diff); - } - return this; - }; - /** - * Remove an event from the timeline. - * @param {Object} event The event object to remove from the list. - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.remove = function (event) { - if (this._iterating) { - this._toRemove.push(event); - } else { - var index = this._timeline.indexOf(event); - if (index !== -1) { - this._timeline.splice(index, 1); - } - } - return this; - }; - /** - * Get the nearest event whose time is less than or equal to the given time. - * @param {Number} time The time to query. - * @returns {Object} The event object set after that time. - */ - Tone.Timeline.prototype.get = function (time) { - var index = this._search(time); - if (index !== -1) { - return this._timeline[index]; - } else { - return null; - } - }; - /** - * Return the first event in the timeline without removing it - * @returns {Object} The first event object - */ - Tone.Timeline.prototype.peek = function () { - return this._timeline[0]; - }; - /** - * Return the first event in the timeline and remove it - * @returns {Object} The first event object - */ - Tone.Timeline.prototype.shift = function () { - return this._timeline.shift(); - }; - /** - * Get the event which is scheduled after the given time. - * @param {Number} time The time to query. - * @returns {Object} The event object after the given time - */ - Tone.Timeline.prototype.getAfter = function (time) { - var index = this._search(time); - if (index + 1 < this._timeline.length) { - return this._timeline[index + 1]; - } else { - return null; - } - }; - /** - * Get the event before the event at the given time. - * @param {Number} time The time to query. - * @returns {Object} The event object before the given time - */ - Tone.Timeline.prototype.getBefore = function (time) { - var len = this._timeline.length; - //if it's after the last item, return the last item - if (len > 0 && this._timeline[len - 1].time < time) { - return this._timeline[len - 1]; - } - var index = this._search(time); - if (index - 1 >= 0) { - return this._timeline[index - 1]; - } else { - return null; - } - }; - /** - * Cancel events after the given time - * @param {Number} time The time to query. - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.cancel = function (after) { - if (this._timeline.length > 1) { - var index = this._search(after); - if (index >= 0) { - if (this._timeline[index].time === after) { - //get the first item with that time - for (var i = index; i >= 0; i--) { - if (this._timeline[i].time === after) { - index = i; - } else { - break; - } - } - this._timeline = this._timeline.slice(0, index); - } else { - this._timeline = this._timeline.slice(0, index + 1); - } - } else { - this._timeline = []; - } - } else if (this._timeline.length === 1) { - //the first item's time - if (this._timeline[0].time >= after) { - this._timeline = []; - } - } - return this; - }; - /** - * Cancel events before or equal to the given time. - * @param {Number} time The time to cancel before. - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.cancelBefore = function (time) { - if (this._timeline.length) { - var index = this._search(time); - if (index >= 0) { - this._timeline = this._timeline.slice(index + 1); - } - } - return this; - }; - /** - * Does a binary serach on the timeline array and returns the - * nearest event index whose time is after or equal to the given time. - * If a time is searched before the first index in the timeline, -1 is returned. - * If the time is after the end, the index of the last item is returned. - * @param {Number} time - * @return {Number} the index in the timeline array - * @private - */ - Tone.Timeline.prototype._search = function (time) { - var beginning = 0; - var len = this._timeline.length; - var end = len; - if (len > 0 && this._timeline[len - 1].time <= time) { - return len - 1; - } - while (beginning < end) { - // calculate the midpoint for roughly equal partition - var midPoint = Math.floor(beginning + (end - beginning) / 2); - var event = this._timeline[midPoint]; - var nextEvent = this._timeline[midPoint + 1]; - if (event.time === time) { - //choose the last one that has the same time - for (var i = midPoint; i < this._timeline.length; i++) { - var testEvent = this._timeline[i]; - if (testEvent.time === time) { - midPoint = i; - } - } - return midPoint; - } else if (event.time < time && nextEvent.time > time) { - return midPoint; - } else if (event.time > time) { - //search lower - end = midPoint; - } else if (event.time < time) { - //search upper - beginning = midPoint + 1; - } - } - return -1; - }; - /** - * Internal iterator. Applies extra safety checks for - * removing items from the array. - * @param {Function} callback - * @param {Number=} lowerBound - * @param {Number=} upperBound - * @private - */ - Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { - this._iterating = true; - lowerBound = this.defaultArg(lowerBound, 0); - upperBound = this.defaultArg(upperBound, this._timeline.length - 1); - for (var i = lowerBound; i <= upperBound; i++) { - callback(this._timeline[i]); - } - this._iterating = false; - if (this._toRemove.length > 0) { - for (var j = 0; j < this._toRemove.length; j++) { - var index = this._timeline.indexOf(this._toRemove[j]); - if (index !== -1) { - this._timeline.splice(index, 1); - } - } - this._toRemove = []; - } - }; - /** - * Iterate over everything in the array - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.forEach = function (callback) { - this._iterate(callback); - return this; - }; - /** - * Iterate over everything in the array at or before the given time. - * @param {Number} time The time to check if items are before - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.forEachBefore = function (time, callback) { - //iterate over the items in reverse so that removing an item doesn't break things - var upperBound = this._search(time); - if (upperBound !== -1) { - this._iterate(callback, 0, upperBound); - } - return this; - }; - /** - * Iterate over everything in the array after the given time. - * @param {Number} time The time to check if items are before - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.forEachAfter = function (time, callback) { - //iterate over the items in reverse so that removing an item doesn't break things - var lowerBound = this._search(time); - this._iterate(callback, lowerBound + 1); - return this; - }; - /** - * Iterate over everything in the array at or after the given time. Similar to - * forEachAfter, but includes the item(s) at the given time. - * @param {Number} time The time to check if items are before - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.forEachFrom = function (time, callback) { - //iterate over the items in reverse so that removing an item doesn't break things - var lowerBound = this._search(time); - //work backwards until the event time is less than time - while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { - lowerBound--; - } - this._iterate(callback, lowerBound + 1); - return this; - }; - /** - * Iterate over everything in the array at the given time - * @param {Number} time The time to check if items are before - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.Timeline} this - */ - Tone.Timeline.prototype.forEachAtTime = function (time, callback) { - //iterate over the items in reverse so that removing an item doesn't break things - var upperBound = this._search(time); - if (upperBound !== -1) { - this._iterate(function (event) { - if (event.time === time) { - callback(event); - } - }, 0, upperBound); - } - return this; - }; - /** - * Clean up. - * @return {Tone.Timeline} this - */ - Tone.Timeline.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._timeline = null; - this._toRemove = null; - }; - return Tone.Timeline; - }); - Module(function (Tone) { - - /** - * @class A signal which adds the method getValueAtTime. - * Code and inspiration from https://github.com/jsantell/web-audio-automation-timeline - * @extends {Tone.Param} - * @param {Number=} value The initial value of the signal - * @param {String=} units The conversion units of the signal. - */ - Tone.TimelineSignal = function () { - var options = this.optionsObject(arguments, [ - 'value', - 'units' - ], Tone.Signal.defaults); - /** - * The scheduled events - * @type {Tone.Timeline} - * @private - */ - this._events = new Tone.Timeline(10); - //constructors - Tone.Signal.apply(this, options); - options.param = this._param; - Tone.Param.call(this, options); - /** - * The initial scheduled value - * @type {Number} - * @private - */ - this._initial = this._fromUnits(this._param.value); - }; - Tone.extend(Tone.TimelineSignal, Tone.Param); - /** - * The event types of a schedulable signal. - * @enum {String} - * @private - */ - Tone.TimelineSignal.Type = { - Linear: 'linear', - Exponential: 'exponential', - Target: 'target', - Curve: 'curve', - Set: 'set' - }; - /** - * The current value of the signal. - * @memberOf Tone.TimelineSignal# - * @type {Number} - * @name value - */ - Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { - get: function () { - var now = this.now(); - var val = this.getValueAtTime(now); - return this._toUnits(val); - }, - set: function (value) { - var convertedVal = this._fromUnits(value); - this._initial = convertedVal; - this.cancelScheduledValues(); - this._param.value = convertedVal; - } - }); - /////////////////////////////////////////////////////////////////////////// - // SCHEDULING - /////////////////////////////////////////////////////////////////////////// - /** - * Schedules a parameter value change at the given time. - * @param {*} value The value to set the signal. - * @param {Time} time The time when the change should occur. - * @returns {Tone.TimelineSignal} this - * @example - * //set the frequency to "G4" in exactly 1 second from now. - * freq.setValueAtTime("G4", "+1"); - */ - Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { - value = this._fromUnits(value); - startTime = this.toSeconds(startTime); - this._events.add({ - 'type': Tone.TimelineSignal.Type.Set, - 'value': value, - 'time': startTime - }); - //invoke the original event - this._param.setValueAtTime(value, startTime); - return this; - }; - /** - * Schedules a linear continuous change in parameter value from the - * previous scheduled parameter value to the given value. - * - * @param {number} value - * @param {Time} endTime - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { - value = this._fromUnits(value); - endTime = this.toSeconds(endTime); - this._events.add({ - 'type': Tone.TimelineSignal.Type.Linear, - 'value': value, - 'time': endTime - }); - this._param.linearRampToValueAtTime(value, endTime); - return this; - }; - /** - * Schedules an exponential continuous change in parameter value from - * the previous scheduled parameter value to the given value. - * - * @param {number} value - * @param {Time} endTime - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { - //get the previous event and make sure it's not starting from 0 - endTime = this.toSeconds(endTime); - var beforeEvent = this._searchBefore(endTime); - if (beforeEvent && beforeEvent.value === 0) { - //reschedule that event - this.setValueAtTime(this._minOutput, beforeEvent.time); - } - value = this._fromUnits(value); - var setValue = Math.max(value, this._minOutput); - this._events.add({ - 'type': Tone.TimelineSignal.Type.Exponential, - 'value': setValue, - 'time': endTime - }); - //if the ramped to value is 0, make it go to the min output, and then set to 0. - if (value < this._minOutput) { - this._param.exponentialRampToValueAtTime(this._minOutput, endTime - this.sampleTime); - this.setValueAtTime(0, endTime); - } else { - this._param.exponentialRampToValueAtTime(value, endTime); - } - return this; - }; - /** - * Start exponentially approaching the target value at the given time with - * a rate having the given time constant. - * @param {number} value - * @param {Time} startTime - * @param {number} timeConstant - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { - value = this._fromUnits(value); - value = Math.max(this._minOutput, value); - timeConstant = Math.max(this._minOutput, timeConstant); - startTime = this.toSeconds(startTime); - this._events.add({ - 'type': Tone.TimelineSignal.Type.Target, - 'value': value, - 'time': startTime, - 'constant': timeConstant - }); - this._param.setTargetAtTime(value, startTime, timeConstant); - return this; - }; - /** - * Set an array of arbitrary values starting at the given time for the given duration. - * @param {Float32Array} values - * @param {Time} startTime - * @param {Time} duration - * @param {NormalRange} [scaling=1] If the values in the curve should be scaled by some value - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.setValueCurveAtTime = function (values, startTime, duration, scaling) { - scaling = this.defaultArg(scaling, 1); - //copy the array - var floats = new Array(values.length); - for (var i = 0; i < floats.length; i++) { - floats[i] = this._fromUnits(values[i]) * scaling; - } - startTime = this.toSeconds(startTime); - duration = this.toSeconds(duration); - this._events.add({ - 'type': Tone.TimelineSignal.Type.Curve, - 'value': floats, - 'time': startTime, - 'duration': duration - }); - //set the first value - this._param.setValueAtTime(floats[0], startTime); - //schedule a lienar ramp for each of the segments - for (var j = 1; j < floats.length; j++) { - var segmentTime = startTime + j / (floats.length - 1) * duration; - this._param.linearRampToValueAtTime(floats[j], segmentTime); - } - return this; - }; - /** - * Cancels all scheduled parameter changes with times greater than or - * equal to startTime. - * - * @param {Time} startTime - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { - after = this.toSeconds(after); - this._events.cancel(after); - this._param.cancelScheduledValues(after); - return this; - }; - /** - * Sets the computed value at the given time. This provides - * a point from which a linear or exponential curve - * can be scheduled after. Will cancel events after - * the given time and shorten the currently scheduled - * linear or exponential ramp so that it ends at `time` . - * This is to avoid discontinuities and clicks in envelopes. - * @param {Time} time When to set the ramp point - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.setRampPoint = function (time) { - time = this.toSeconds(time); - //get the value at the given time - var val = this._toUnits(this.getValueAtTime(time)); - //if there is an event at the given time - //and that even is not a "set" - var before = this._searchBefore(time); - if (before && before.time === time) { - //remove everything after - this.cancelScheduledValues(time + this.sampleTime); - } else if (before && before.type === Tone.TimelineSignal.Type.Curve && before.time + before.duration > time) { - //if the curve is still playing - //cancel the curve - this.cancelScheduledValues(time); - this.linearRampToValueAtTime(val, time); - } else { - //reschedule the next event to end at the given time - var after = this._searchAfter(time); - if (after) { - //cancel the next event(s) - this.cancelScheduledValues(time); - if (after.type === Tone.TimelineSignal.Type.Linear) { - this.linearRampToValueAtTime(val, time); - } else if (after.type === Tone.TimelineSignal.Type.Exponential) { - this.exponentialRampToValueAtTime(val, time); - } - } - this.setValueAtTime(val, time); - } - return this; - }; - /** - * Do a linear ramp to the given value between the start and finish times. - * @param {Number} value The value to ramp to. - * @param {Time} start The beginning anchor point to do the linear ramp - * @param {Time} finish The ending anchor point by which the value of - * the signal will equal the given value. - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { - this.setRampPoint(start); - this.linearRampToValueAtTime(value, finish); - return this; - }; - /** - * Do a exponential ramp to the given value between the start and finish times. - * @param {Number} value The value to ramp to. - * @param {Time} start The beginning anchor point to do the exponential ramp - * @param {Time} finish The ending anchor point by which the value of - * the signal will equal the given value. - * @returns {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { - this.setRampPoint(start); - this.exponentialRampToValueAtTime(value, finish); - return this; - }; - /////////////////////////////////////////////////////////////////////////// - // GETTING SCHEDULED VALUES - /////////////////////////////////////////////////////////////////////////// - /** - * Returns the value before or equal to the given time - * @param {Number} time The time to query - * @return {Object} The event at or before the given time. - * @private - */ - Tone.TimelineSignal.prototype._searchBefore = function (time) { - return this._events.get(time); - }; - /** - * The event after the given time - * @param {Number} time The time to query. - * @return {Object} The next event after the given time - * @private - */ - Tone.TimelineSignal.prototype._searchAfter = function (time) { - return this._events.getAfter(time); - }; - /** - * Get the scheduled value at the given time. This will - * return the unconverted (raw) value. - * @param {Number} time The time in seconds. - * @return {Number} The scheduled value at the given time. - */ - Tone.TimelineSignal.prototype.getValueAtTime = function (time) { - time = this.toSeconds(time); - var after = this._searchAfter(time); - var before = this._searchBefore(time); - var value = this._initial; - //if it was set by - if (before === null) { - value = this._initial; - } else if (before.type === Tone.TimelineSignal.Type.Target) { - var previous = this._events.getBefore(before.time); - var previouVal; - if (previous === null) { - previouVal = this._initial; - } else { - previouVal = previous.value; - } - value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); - } else if (before.type === Tone.TimelineSignal.Type.Curve) { - value = this._curveInterpolate(before.time, before.value, before.duration, time); - } else if (after === null) { - value = before.value; - } else if (after.type === Tone.TimelineSignal.Type.Linear) { - value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); - } else if (after.type === Tone.TimelineSignal.Type.Exponential) { - value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); - } else { - value = before.value; - } - return value; - }; - /** - * When signals connect to other signals or AudioParams, - * they take over the output value of that signal or AudioParam. - * For all other nodes, the behavior is the same as a default connect. - * - * @override - * @param {AudioParam|AudioNode|Tone.Signal|Tone} node - * @param {number} [outputNumber=0] The output number to connect from. - * @param {number} [inputNumber=0] The input number to connect to. - * @returns {Tone.TimelineSignal} this - * @method - */ - Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; - /////////////////////////////////////////////////////////////////////////// - // AUTOMATION CURVE CALCULATIONS - // MIT License, copyright (c) 2014 Jordan Santell - /////////////////////////////////////////////////////////////////////////// - /** - * Calculates the the value along the curve produced by setTargetAtTime - * @private - */ - Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { - return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); - }; - /** - * Calculates the the value along the curve produced by linearRampToValueAtTime - * @private - */ - Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { - return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); - }; - /** - * Calculates the the value along the curve produced by exponentialRampToValueAtTime - * @private - */ - Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { - v0 = Math.max(this._minOutput, v0); - return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); - }; - /** - * Calculates the the value along the curve produced by setValueCurveAtTime - * @private - */ - Tone.TimelineSignal.prototype._curveInterpolate = function (start, curve, duration, time) { - var len = curve.length; - // If time is after duration, return the last curve value - if (time >= start + duration) { - return curve[len - 1]; - } else if (time <= start) { - return curve[0]; - } else { - var progress = (time - start) / duration; - var lowerIndex = Math.floor((len - 1) * progress); - var upperIndex = Math.ceil((len - 1) * progress); - var lowerVal = curve[lowerIndex]; - var upperVal = curve[upperIndex]; - if (upperIndex === lowerIndex) { - return lowerVal; - } else { - return this._linearInterpolate(lowerIndex, lowerVal, upperIndex, upperVal, progress * (len - 1)); - } - } - }; - /** - * Clean up. - * @return {Tone.TimelineSignal} this - */ - Tone.TimelineSignal.prototype.dispose = function () { - Tone.Signal.prototype.dispose.call(this); - Tone.Param.prototype.dispose.call(this); - this._events.dispose(); - this._events = null; - }; - return Tone.TimelineSignal; - }); - Module(function (Tone) { - - /** - * @class Pow applies an exponent to the incoming signal. The incoming signal - * must be AudioRange. - * - * @extends {Tone.SignalBase} - * @constructor - * @param {Positive} exp The exponent to apply to the incoming signal, must be at least 2. - * @example - * var pow = new Tone.Pow(2); - * var sig = new Tone.Signal(0.5).connect(pow); - * //output of pow is 0.25. - */ - Tone.Pow = function (exp) { - /** - * the exponent - * @private - * @type {number} - */ - this._exp = this.defaultArg(exp, 1); - /** - * @type {WaveShaperNode} - * @private - */ - this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192); - }; - Tone.extend(Tone.Pow, Tone.SignalBase); - /** - * The value of the exponent. - * @memberOf Tone.Pow# - * @type {number} - * @name value - */ - Object.defineProperty(Tone.Pow.prototype, 'value', { - get: function () { - return this._exp; - }, - set: function (exp) { - this._exp = exp; - this._expScaler.setMap(this._expFunc(this._exp)); - } - }); - /** - * the function which maps the waveshaper - * @param {number} exp - * @return {function} - * @private - */ - Tone.Pow.prototype._expFunc = function (exp) { - return function (val) { - return Math.pow(Math.abs(val), exp); - }; - }; - /** - * Clean up. - * @returns {Tone.Pow} this - */ - Tone.Pow.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._expScaler.dispose(); - this._expScaler = null; - return this; - }; - return Tone.Pow; - }); - Module(function (Tone) { - - /** - * @class Tone.Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope) - * envelope generator. Tone.Envelope outputs a signal which - * can be connected to an AudioParam or Tone.Signal. - * - * - * @constructor - * @extends {Tone} - * @param {Time} [attack] The amount of time it takes for the envelope to go from - * 0 to it's maximum value. - * @param {Time} [decay] The period of time after the attack that it takes for the envelope - * to fall to the sustain value. - * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until - * the release is triggered. - * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. - * @example - * //an amplitude envelope - * var gainNode = Tone.context.createGain(); - * var env = new Tone.Envelope({ - * "attack" : 0.1, - * "decay" : 0.2, - * "sustain" : 1, - * "release" : 0.8, - * }); - * env.connect(gainNode.gain); - */ - Tone.Envelope = function () { - //get all of the defaults - var options = this.optionsObject(arguments, [ - 'attack', - 'decay', - 'sustain', - 'release' - ], Tone.Envelope.defaults); - /** - * When triggerAttack is called, the attack time is the amount of - * time it takes for the envelope to reach it's maximum value. - * @type {Time} - */ - this.attack = options.attack; - /** - * After the attack portion of the envelope, the value will fall - * over the duration of the decay time to it's sustain value. - * @type {Time} - */ - this.decay = options.decay; - /** - * The sustain value is the value - * which the envelope rests at after triggerAttack is - * called, but before triggerRelease is invoked. - * @type {NormalRange} - */ - this.sustain = options.sustain; - /** - * After triggerRelease is called, the envelope's - * value will fall to it's miminum value over the - * duration of the release time. - * @type {Time} - */ - this.release = options.release; - /** - * the next time the envelope is at standby - * @type {number} - * @private - */ - this._attackCurve = 'linear'; - /** - * the next time the envelope is at standby - * @type {number} - * @private - */ - this._releaseCurve = 'exponential'; - /** - * the signal - * @type {Tone.TimelineSignal} - * @private - */ - this._sig = this.output = new Tone.TimelineSignal(); - this._sig.setValueAtTime(0, 0); - //set the attackCurve initially - this.attackCurve = options.attackCurve; - this.releaseCurve = options.releaseCurve; - }; - Tone.extend(Tone.Envelope); - /** - * the default parameters - * @static - * @const - */ - Tone.Envelope.defaults = { - 'attack': 0.01, - 'decay': 0.1, - 'sustain': 0.5, - 'release': 1, - 'attackCurve': 'linear', - 'releaseCurve': 'exponential' - }; - /** - * Read the current value of the envelope. Useful for - * syncronizing visual output to the envelope. - * @memberOf Tone.Envelope# - * @type {Number} - * @name value - * @readOnly - */ - Object.defineProperty(Tone.Envelope.prototype, 'value', { - get: function () { - return this.getValueAtTime(this.now()); - } - }); - /** - * The shape of the attack. - * Can be any of these strings: - * - * Can also be an array which describes the curve. Values - * in the array are evenly subdivided and linearly - * interpolated over the duration of the attack. - * @memberOf Tone.Envelope# - * @type {String|Array} - * @name attackCurve - * @example - * env.attackCurve = "linear"; - * @example - * //can also be an array - * env.attackCurve = [0, 0.2, 0.3, 0.4, 1] - */ - Object.defineProperty(Tone.Envelope.prototype, 'attackCurve', { - get: function () { - if (this.isString(this._attackCurve)) { - return this._attackCurve; - } else if (this.isArray(this._attackCurve)) { - //look up the name in the curves array - for (var type in Tone.Envelope.Type) { - if (Tone.Envelope.Type[type].In === this._attackCurve) { - return type; - } - } - //otherwise just return the array - return this._attackCurve; - } - }, - set: function (curve) { - //check if it's a valid type - if (Tone.Envelope.Type.hasOwnProperty(curve)) { - var curveDef = Tone.Envelope.Type[curve]; - if (this.isObject(curveDef)) { - this._attackCurve = curveDef.In; - } else { - this._attackCurve = curveDef; - } - } else if (this.isArray(curve)) { - this._attackCurve = curve; - } else { - throw new Error('Tone.Envelope: invalid curve: ' + curve); - } - } - }); - /** - * The shape of the release. See the attack curve types. - * @memberOf Tone.Envelope# - * @type {String|Array} - * @name releaseCurve - * @example - * env.releaseCurve = "linear"; - */ - Object.defineProperty(Tone.Envelope.prototype, 'releaseCurve', { - get: function () { - if (this.isString(this._releaseCurve)) { - return this._releaseCurve; - } else if (this.isArray(this._releaseCurve)) { - //look up the name in the curves array - for (var type in Tone.Envelope.Type) { - if (Tone.Envelope.Type[type].Out === this._releaseCurve) { - return type; - } - } - //otherwise just return the array - return this._releaseCurve; - } - }, - set: function (curve) { - //check if it's a valid type - if (Tone.Envelope.Type.hasOwnProperty(curve)) { - var curveDef = Tone.Envelope.Type[curve]; - if (this.isObject(curveDef)) { - this._releaseCurve = curveDef.Out; - } else { - this._releaseCurve = curveDef; - } - } else if (this.isArray(curve)) { - this._releaseCurve = curve; - } else { - throw new Error('Tone.Envelope: invalid curve: ' + curve); - } - } - }); - /** - * Trigger the attack/decay portion of the ADSR envelope. - * @param {Time} [time=now] When the attack should start. - * @param {NormalRange} [velocity=1] The velocity of the envelope scales the vales. - * number between 0-1 - * @returns {Tone.Envelope} this - * @example - * //trigger the attack 0.5 seconds from now with a velocity of 0.2 - * env.triggerAttack("+0.5", 0.2); - */ - Tone.Envelope.prototype.triggerAttack = function (time, velocity) { - time = this.toSeconds(time); - var originalAttack = this.toSeconds(this.attack); - var attack = originalAttack; - var decay = this.toSeconds(this.decay); - velocity = this.defaultArg(velocity, 1); - //check if it's not a complete attack - var currentValue = this.getValueAtTime(time); - if (currentValue > 0) { - //subtract the current value from the attack time - var attackRate = 1 / attack; - var remainingDistance = 1 - currentValue; - //the attack is now the remaining time - attack = remainingDistance / attackRate; - } - //attack - if (this._attackCurve === 'linear') { - this._sig.linearRampToValue(velocity, attack, time); - } else if (this._attackCurve === 'exponential') { - this._sig.exponentialRampToValue(velocity, attack, time); - } else if (attack > 0) { - this._sig.setRampPoint(time); - var curve = this._attackCurve; - //take only a portion of the curve - if (attack < originalAttack) { - var percentComplete = 1 - attack / originalAttack; - var sliceIndex = Math.floor(percentComplete * this._attackCurve.length); - curve = this._attackCurve.slice(sliceIndex); - //the first index is the current value - curve[0] = currentValue; - } - this._sig.setValueCurveAtTime(curve, time, attack, velocity); - } - //decay - this._sig.exponentialRampToValue(velocity * this.sustain, decay, attack + time); - return this; - }; - /** - * Triggers the release of the envelope. - * @param {Time} [time=now] When the release portion of the envelope should start. - * @returns {Tone.Envelope} this - * @example - * //trigger release immediately - * env.triggerRelease(); - */ - Tone.Envelope.prototype.triggerRelease = function (time) { - time = this.toSeconds(time); - var currentValue = this.getValueAtTime(time); - if (currentValue > 0) { - var release = this.toSeconds(this.release); - if (this._releaseCurve === 'linear') { - this._sig.linearRampToValue(0, release, time); - } else if (this._releaseCurve === 'exponential') { - this._sig.exponentialRampToValue(0, release, time); - } else { - var curve = this._releaseCurve; - if (this.isArray(curve)) { - this._sig.setRampPoint(time); - this._sig.setValueCurveAtTime(curve, time, release, currentValue); - } - } - } - return this; - }; - /** - * Get the scheduled value at the given time. This will - * return the unconverted (raw) value. - * @param {Number} time The time in seconds. - * @return {Number} The scheduled value at the given time. - */ - Tone.Envelope.prototype.getValueAtTime = function (time) { - return this._sig.getValueAtTime(time); - }; - /** - * triggerAttackRelease is shorthand for triggerAttack, then waiting - * some duration, then triggerRelease. - * @param {Time} duration The duration of the sustain. - * @param {Time} [time=now] When the attack should be triggered. - * @param {number} [velocity=1] The velocity of the envelope. - * @returns {Tone.Envelope} this - * @example - * //trigger the attack and then the release after 0.6 seconds. - * env.triggerAttackRelease(0.6); - */ - Tone.Envelope.prototype.triggerAttackRelease = function (duration, time, velocity) { - time = this.toSeconds(time); - this.triggerAttack(time, velocity); - this.triggerRelease(time + this.toSeconds(duration)); - return this; - }; - /** - * Cancels all scheduled envelope changes after the given time. - * @param {Time} after - * @returns {Tone.Envelope} this - */ - Tone.Envelope.prototype.cancel = function (after) { - this._sig.cancelScheduledValues(after); - return this; - }; - /** - * Borrows the connect method from Tone.Signal. - * @function - * @private - */ - Tone.Envelope.prototype.connect = Tone.Signal.prototype.connect; - /** - * Generate some complex envelope curves. - */ - (function _createCurves() { - var curveLen = 128; - var i, k; - //cosine curve - var cosineCurve = []; - for (i = 0; i < curveLen; i++) { - cosineCurve[i] = Math.sin(i / (curveLen - 1) * (Math.PI / 2)); - } - //ripple curve - var rippleCurve = []; - var rippleCurveFreq = 6.4; - for (i = 0; i < curveLen - 1; i++) { - k = i / (curveLen - 1); - var sineWave = Math.sin(k * (Math.PI * 2) * rippleCurveFreq - Math.PI / 2) + 1; - rippleCurve[i] = sineWave / 10 + k * 0.83; - } - rippleCurve[curveLen - 1] = 1; - //stairs curve - var stairsCurve = []; - var steps = 5; - for (i = 0; i < curveLen; i++) { - stairsCurve[i] = Math.ceil(i / (curveLen - 1) * steps) / steps; - } - //in-out easing curve - var sineCurve = []; - for (i = 0; i < curveLen; i++) { - k = i / (curveLen - 1); - sineCurve[i] = 0.5 * (1 - Math.cos(Math.PI * k)); - } - //a bounce curve - var bounceCurve = []; - for (i = 0; i < curveLen; i++) { - k = i / (curveLen - 1); - var freq = Math.pow(k, 3) * 4 + 0.2; - var val = Math.cos(freq * Math.PI * 2 * k); - bounceCurve[i] = Math.abs(val * (1 - k)); - } - /** - * Invert a value curve to make it work for the release - * @private - */ - function invertCurve(curve) { - var out = new Array(curve.length); - for (var j = 0; j < curve.length; j++) { - out[j] = 1 - curve[j]; - } - return out; - } - /** - * reverse the curve - * @private - */ - function reverseCurve(curve) { - return curve.slice(0).reverse(); - } - /** - * attack and release curve arrays - * @type {Object} - * @private - */ - Tone.Envelope.Type = { - 'linear': 'linear', - 'exponential': 'exponential', - 'bounce': { - In: invertCurve(bounceCurve), - Out: bounceCurve - }, - 'cosine': { - In: cosineCurve, - Out: reverseCurve(cosineCurve) - }, - 'step': { - In: stairsCurve, - Out: invertCurve(stairsCurve) - }, - 'ripple': { - In: rippleCurve, - Out: invertCurve(rippleCurve) - }, - 'sine': { - In: sineCurve, - Out: invertCurve(sineCurve) - } - }; - }()); - /** - * Disconnect and dispose. - * @returns {Tone.Envelope} this - */ - Tone.Envelope.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._sig.dispose(); - this._sig = null; - this._attackCurve = null; - this._releaseCurve = null; - return this; - }; - return Tone.Envelope; - }); - Module(function (Tone) { - - /** - * @class Tone.AmplitudeEnvelope is a Tone.Envelope connected to a gain node. - * Unlike Tone.Envelope, which outputs the envelope's value, Tone.AmplitudeEnvelope accepts - * an audio signal as the input and will apply the envelope to the amplitude - * of the signal. Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope). - * - * @constructor - * @extends {Tone.Envelope} - * @param {Time|Object} [attack] The amount of time it takes for the envelope to go from - * 0 to it's maximum value. - * @param {Time} [decay] The period of time after the attack that it takes for the envelope - * to fall to the sustain value. - * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until - * the release is triggered. - * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. - * @example - * var ampEnv = new Tone.AmplitudeEnvelope({ - * "attack": 0.1, - * "decay": 0.2, - * "sustain": 1.0, - * "release": 0.8 - * }).toMaster(); - * //create an oscillator and connect it - * var osc = new Tone.Oscillator().connect(ampEnv).start(); - * //trigger the envelopes attack and release "8t" apart - * ampEnv.triggerAttackRelease("8t"); - */ - Tone.AmplitudeEnvelope = function () { - Tone.Envelope.apply(this, arguments); - /** - * the input node - * @type {GainNode} - * @private - */ - this.input = this.output = new Tone.Gain(); - this._sig.connect(this.output.gain); - }; - Tone.extend(Tone.AmplitudeEnvelope, Tone.Envelope); - /** - * Clean up - * @return {Tone.AmplitudeEnvelope} this - */ - Tone.AmplitudeEnvelope.prototype.dispose = function () { - this.input.dispose(); - this.input = null; - Tone.Envelope.prototype.dispose.call(this); - return this; - }; - return Tone.AmplitudeEnvelope; - }); - Module(function (Tone) { - - /** - * AnalyserNode.getFloatTimeDomainData polyfill - * @private - */ - if (window.AnalyserNode && !AnalyserNode.prototype.getFloatTimeDomainData) { - //referenced https://github.com/mohayonao/get-float-time-domain-data - AnalyserNode.prototype.getFloatTimeDomainData = function (array) { - var uint8 = new Uint8Array(array.length); - this.getByteTimeDomainData(uint8); - for (var i = 0; i < uint8.length; i++) { - array[i] = (uint8[i] - 128) / 128; - } - }; - } - /** - * @class Wrapper around the native Web Audio's - * [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode). - * Extracts FFT or Waveform data from the incoming signal. - * @extends {Tone} - * @param {String=} type The return type of the analysis, either "fft", or "waveform". - * @param {Number=} size The size of the FFT. Value must be a power of - * two in the range 32 to 32768. - */ - Tone.Analyser = function () { - var options = this.optionsObject(arguments, [ - 'type', - 'size' - ], Tone.Analyser.defaults); - /** - * The analyser node. - * @private - * @type {AnalyserNode} - */ - this._analyser = this.input = this.output = this.context.createAnalyser(); - /** - * The analysis type - * @type {String} - * @private - */ - this._type = options.type; - /** - * The return type of the analysis - * @type {String} - * @private - */ - this._returnType = options.returnType; - /** - * The buffer that the FFT data is written to - * @type {TypedArray} - * @private - */ - this._buffer = null; - //set the values initially - this.size = options.size; - this.type = options.type; - this.returnType = options.returnType; - this.minDecibels = options.minDecibels; - this.maxDecibels = options.maxDecibels; - }; - Tone.extend(Tone.Analyser); - /** - * The default values. - * @type {Object} - * @const - */ - Tone.Analyser.defaults = { - 'size': 1024, - 'returnType': 'byte', - 'type': 'fft', - 'smoothing': 0.8, - 'maxDecibels': -30, - 'minDecibels': -100 - }; - /** - * Possible return types of Tone.Analyser.analyse() - * @enum {String} - */ - Tone.Analyser.Type = { - Waveform: 'waveform', - FFT: 'fft' - }; - /** - * Possible return types of Tone.Analyser.analyse(). - * byte values are between [0,255]. float values are between - * [-1, 1] when the type is set to "waveform" and between - * [minDecibels,maxDecibels] when the type is "fft". - * @enum {String} - */ - Tone.Analyser.ReturnType = { - Byte: 'byte', - Float: 'float' - }; - /** - * Run the analysis given the current settings and return the - * result as a TypedArray. - * @returns {TypedArray} - */ - Tone.Analyser.prototype.analyse = function () { - if (this._type === Tone.Analyser.Type.FFT) { - if (this._returnType === Tone.Analyser.ReturnType.Byte) { - this._analyser.getByteFrequencyData(this._buffer); - } else { - this._analyser.getFloatFrequencyData(this._buffer); - } - } else if (this._type === Tone.Analyser.Type.Waveform) { - if (this._returnType === Tone.Analyser.ReturnType.Byte) { - this._analyser.getByteTimeDomainData(this._buffer); - } else { - this._analyser.getFloatTimeDomainData(this._buffer); - } - } - return this._buffer; - }; - /** - * The size of analysis. This must be a power of two in the range 32 to 32768. - * @memberOf Tone.Analyser# - * @type {Number} - * @name size - */ - Object.defineProperty(Tone.Analyser.prototype, 'size', { - get: function () { - return this._analyser.frequencyBinCount; - }, - set: function (size) { - this._analyser.fftSize = size * 2; - this.type = this._type; - } - }); - /** - * The return type of Tone.Analyser.analyse(), either "byte" or "float". - * When the type is set to "byte" the range of values returned in the array - * are between 0-255. "float" values are between - * [-1, 1] when the type is set to "waveform" and between - * [minDecibels,maxDecibels] when the type is "fft". - * @memberOf Tone.Analyser# - * @type {String} - * @name type - */ - Object.defineProperty(Tone.Analyser.prototype, 'returnType', { - get: function () { - return this._returnType; - }, - set: function (type) { - if (type === Tone.Analyser.ReturnType.Byte) { - this._buffer = new Uint8Array(this._analyser.frequencyBinCount); - } else if (type === Tone.Analyser.ReturnType.Float) { - this._buffer = new Float32Array(this._analyser.frequencyBinCount); - } else { - throw new TypeError('Tone.Analayser: invalid return type: ' + type); - } - this._returnType = type; - } - }); - /** - * The analysis function returned by Tone.Analyser.analyse(), either "fft" or "waveform". - * @memberOf Tone.Analyser# - * @type {String} - * @name type - */ - Object.defineProperty(Tone.Analyser.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT) { - throw new TypeError('Tone.Analyser: invalid type: ' + type); - } - this._type = type; - } - }); - /** - * 0 represents no time averaging with the last analysis frame. - * @memberOf Tone.Analyser# - * @type {NormalRange} - * @name smoothing - */ - Object.defineProperty(Tone.Analyser.prototype, 'smoothing', { - get: function () { - return this._analyser.smoothingTimeConstant; - }, - set: function (val) { - this._analyser.smoothingTimeConstant = val; - } - }); - /** - * The smallest decibel value which is analysed by the FFT. - * @memberOf Tone.Analyser# - * @type {Decibels} - * @name minDecibels - */ - Object.defineProperty(Tone.Analyser.prototype, 'minDecibels', { - get: function () { - return this._analyser.minDecibels; - }, - set: function (val) { - this._analyser.minDecibels = val; - } - }); - /** - * The largest decibel value which is analysed by the FFT. - * @memberOf Tone.Analyser# - * @type {Decibels} - * @name maxDecibels - */ - Object.defineProperty(Tone.Analyser.prototype, 'maxDecibels', { - get: function () { - return this._analyser.maxDecibels; - }, - set: function (val) { - this._analyser.maxDecibels = val; - } - }); - /** - * Clean up. - * @return {Tone.Analyser} this - */ - Tone.Analyser.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._analyser.disconnect(); - this._analyser = null; - this._buffer = null; - }; - return Tone.Analyser; - }); - Module(function (Tone) { - - /** - * @class Tone.Compressor is a thin wrapper around the Web Audio - * [DynamicsCompressorNode](http://webaudio.github.io/web-audio-api/#the-dynamicscompressornode-interface). - * Compression reduces the volume of loud sounds or amplifies quiet sounds - * by narrowing or "compressing" an audio signal's dynamic range. - * Read more on [Wikipedia](https://en.wikipedia.org/wiki/Dynamic_range_compression). - * - * @extends {Tone} - * @constructor - * @param {Decibels|Object} [threshold] The value above which the compression starts to be applied. - * @param {Positive} [ratio] The gain reduction ratio. - * @example - * var comp = new Tone.Compressor(-30, 3); - */ - Tone.Compressor = function () { - var options = this.optionsObject(arguments, [ - 'threshold', - 'ratio' - ], Tone.Compressor.defaults); - /** - * the compressor node - * @type {DynamicsCompressorNode} - * @private - */ - this._compressor = this.input = this.output = this.context.createDynamicsCompressor(); - /** - * the threshold vaue - * @type {Decibels} - * @signal - */ - this.threshold = new Tone.Param({ - 'param': this._compressor.threshold, - 'units': Tone.Type.Decibels, - 'convert': false - }); - /** - * The attack parameter - * @type {Time} - * @signal - */ - this.attack = new Tone.Param(this._compressor.attack, Tone.Type.Time); - /** - * The release parameter - * @type {Time} - * @signal - */ - this.release = new Tone.Param(this._compressor.release, Tone.Type.Time); - /** - * The knee parameter - * @type {Decibels} - * @signal - */ - this.knee = new Tone.Param({ - 'param': this._compressor.knee, - 'units': Tone.Type.Decibels, - 'convert': false - }); - /** - * The ratio value - * @type {Number} - * @signal - */ - this.ratio = new Tone.Param({ - 'param': this._compressor.ratio, - 'convert': false - }); - //set the defaults - this._readOnly([ - 'knee', - 'release', - 'attack', - 'ratio', - 'threshold' - ]); - this.set(options); - }; - Tone.extend(Tone.Compressor); - /** - * @static - * @const - * @type {Object} - */ - Tone.Compressor.defaults = { - 'ratio': 12, - 'threshold': -24, - 'release': 0.25, - 'attack': 0.003, - 'knee': 30 - }; - /** - * clean up - * @returns {Tone.Compressor} this - */ - Tone.Compressor.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'knee', - 'release', - 'attack', - 'ratio', - 'threshold' - ]); - this._compressor.disconnect(); - this._compressor = null; - this.attack.dispose(); - this.attack = null; - this.release.dispose(); - this.release = null; - this.threshold.dispose(); - this.threshold = null; - this.ratio.dispose(); - this.ratio = null; - this.knee.dispose(); - this.knee = null; - return this; - }; - return Tone.Compressor; - }); - Module(function (Tone) { - - /** - * @class Add a signal and a number or two signals. When no value is - * passed into the constructor, Tone.Add will sum input[0] - * and input[1]. If a value is passed into the constructor, - * the it will be added to the input. - * - * @constructor - * @extends {Tone.Signal} - * @param {number=} value If no value is provided, Tone.Add will sum the first - * and second inputs. - * @example - * var signal = new Tone.Signal(2); - * var add = new Tone.Add(2); - * signal.connect(add); - * //the output of add equals 4 - * @example - * //if constructed with no arguments - * //it will add the first and second inputs - * var add = new Tone.Add(); - * var sig0 = new Tone.Signal(3).connect(add, 0, 0); - * var sig1 = new Tone.Signal(4).connect(add, 0, 1); - * //the output of add equals 7. - */ - Tone.Add = function (value) { - this.createInsOuts(2, 0); - /** - * the summing node - * @type {GainNode} - * @private - */ - this._sum = this.input[0] = this.input[1] = this.output = new Tone.Gain(); - /** - * @private - * @type {Tone.Signal} - */ - this._param = this.input[1] = new Tone.Signal(value); - this._param.connect(this._sum); - }; - Tone.extend(Tone.Add, Tone.Signal); - /** - * Clean up. - * @returns {Tone.Add} this - */ - Tone.Add.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._sum.dispose(); - this._sum = null; - this._param.dispose(); - this._param = null; - return this; - }; - return Tone.Add; - }); - Module(function (Tone) { - - /** - * @class Multiply two incoming signals. Or, if a number is given in the constructor, - * multiplies the incoming signal by that value. - * - * @constructor - * @extends {Tone.Signal} - * @param {number=} value Constant value to multiple. If no value is provided, - * it will return the product of the first and second inputs - * @example - * var mult = new Tone.Multiply(); - * var sigA = new Tone.Signal(3); - * var sigB = new Tone.Signal(4); - * sigA.connect(mult, 0, 0); - * sigB.connect(mult, 0, 1); - * //output of mult is 12. - * @example - * var mult = new Tone.Multiply(10); - * var sig = new Tone.Signal(2).connect(mult); - * //the output of mult is 20. - */ - Tone.Multiply = function (value) { - this.createInsOuts(2, 0); - /** - * the input node is the same as the output node - * it is also the GainNode which handles the scaling of incoming signal - * - * @type {GainNode} - * @private - */ - this._mult = this.input[0] = this.output = new Tone.Gain(); - /** - * the scaling parameter - * @type {AudioParam} - * @private - */ - this._param = this.input[1] = this.output.gain; - this._param.value = this.defaultArg(value, 0); - }; - Tone.extend(Tone.Multiply, Tone.Signal); - /** - * clean up - * @returns {Tone.Multiply} this - */ - Tone.Multiply.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._mult.dispose(); - this._mult = null; - this._param = null; - return this; - }; - return Tone.Multiply; - }); - Module(function (Tone) { - - /** - * @class Negate the incoming signal. i.e. an input signal of 10 will output -10 - * - * @constructor - * @extends {Tone.SignalBase} - * @example - * var neg = new Tone.Negate(); - * var sig = new Tone.Signal(-2).connect(neg); - * //output of neg is positive 2. - */ - Tone.Negate = function () { - /** - * negation is done by multiplying by -1 - * @type {Tone.Multiply} - * @private - */ - this._multiply = this.input = this.output = new Tone.Multiply(-1); - }; - Tone.extend(Tone.Negate, Tone.SignalBase); - /** - * clean up - * @returns {Tone.Negate} this - */ - Tone.Negate.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._multiply.dispose(); - this._multiply = null; - return this; - }; - return Tone.Negate; - }); - Module(function (Tone) { - - /** - * @class Subtract the signal connected to input[1] from the signal connected - * to input[0]. If an argument is provided in the constructor, the - * signals .value will be subtracted from the incoming signal. - * - * @extends {Tone.Signal} - * @constructor - * @param {number=} value The value to subtract from the incoming signal. If the value - * is omitted, it will subtract the second signal from the first. - * @example - * var sub = new Tone.Subtract(1); - * var sig = new Tone.Signal(4).connect(sub); - * //the output of sub is 3. - * @example - * var sub = new Tone.Subtract(); - * var sigA = new Tone.Signal(10); - * var sigB = new Tone.Signal(2.5); - * sigA.connect(sub, 0, 0); - * sigB.connect(sub, 0, 1); - * //output of sub is 7.5 - */ - Tone.Subtract = function (value) { - this.createInsOuts(2, 0); - /** - * the summing node - * @type {GainNode} - * @private - */ - this._sum = this.input[0] = this.output = new Tone.Gain(); - /** - * negate the input of the second input before connecting it - * to the summing node. - * @type {Tone.Negate} - * @private - */ - this._neg = new Tone.Negate(); - /** - * the node where the value is set - * @private - * @type {Tone.Signal} - */ - this._param = this.input[1] = new Tone.Signal(value); - this._param.chain(this._neg, this._sum); - }; - Tone.extend(Tone.Subtract, Tone.Signal); - /** - * Clean up. - * @returns {Tone.SignalBase} this - */ - Tone.Subtract.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._neg.dispose(); - this._neg = null; - this._sum.disconnect(); - this._sum = null; - this._param.dispose(); - this._param = null; - return this; - }; - return Tone.Subtract; - }); - Module(function (Tone) { - - /** - * @class GreaterThanZero outputs 1 when the input is strictly greater than zero - * - * @constructor - * @extends {Tone.SignalBase} - * @example - * var gt0 = new Tone.GreaterThanZero(); - * var sig = new Tone.Signal(0.01).connect(gt0); - * //the output of gt0 is 1. - * sig.value = 0; - * //the output of gt0 is 0. - */ - Tone.GreaterThanZero = function () { - /** - * @type {Tone.WaveShaper} - * @private - */ - this._thresh = this.output = new Tone.WaveShaper(function (val) { - if (val <= 0) { - return 0; - } else { - return 1; - } - }, 127); - /** - * scale the first thresholded signal by a large value. - * this will help with values which are very close to 0 - * @type {Tone.Multiply} - * @private - */ - this._scale = this.input = new Tone.Multiply(10000); - //connections - this._scale.connect(this._thresh); - }; - Tone.extend(Tone.GreaterThanZero, Tone.SignalBase); - /** - * dispose method - * @returns {Tone.GreaterThanZero} this - */ - Tone.GreaterThanZero.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._scale.dispose(); - this._scale = null; - this._thresh.dispose(); - this._thresh = null; - return this; - }; - return Tone.GreaterThanZero; - }); - Module(function (Tone) { - - /** - * @class Output 1 if the signal is greater than the value, otherwise outputs 0. - * can compare two signals or a signal and a number. - * - * @constructor - * @extends {Tone.Signal} - * @param {number} [value=0] the value to compare to the incoming signal - * @example - * var gt = new Tone.GreaterThan(2); - * var sig = new Tone.Signal(4).connect(gt); - * //output of gt is equal 1. - */ - Tone.GreaterThan = function (value) { - this.createInsOuts(2, 0); - /** - * subtract the amount from the incoming signal - * @type {Tone.Subtract} - * @private - */ - this._param = this.input[0] = new Tone.Subtract(value); - this.input[1] = this._param.input[1]; - /** - * compare that amount to zero - * @type {Tone.GreaterThanZero} - * @private - */ - this._gtz = this.output = new Tone.GreaterThanZero(); - //connect - this._param.connect(this._gtz); - }; - Tone.extend(Tone.GreaterThan, Tone.Signal); - /** - * dispose method - * @returns {Tone.GreaterThan} this - */ - Tone.GreaterThan.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._param.dispose(); - this._param = null; - this._gtz.dispose(); - this._gtz = null; - return this; - }; - return Tone.GreaterThan; - }); - Module(function (Tone) { - - /** - * @class Return the absolute value of an incoming signal. - * - * @constructor - * @extends {Tone.SignalBase} - * @example - * var signal = new Tone.Signal(-1); - * var abs = new Tone.Abs(); - * signal.connect(abs); - * //the output of abs is 1. - */ - Tone.Abs = function () { - /** - * @type {Tone.LessThan} - * @private - */ - this._abs = this.input = this.output = new Tone.WaveShaper(function (val) { - if (val === 0) { - return 0; - } else { - return Math.abs(val); - } - }, 127); - }; - Tone.extend(Tone.Abs, Tone.SignalBase); - /** - * dispose method - * @returns {Tone.Abs} this - */ - Tone.Abs.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._abs.dispose(); - this._abs = null; - return this; - }; - return Tone.Abs; - }); - Module(function (Tone) { - - /** - * @class Signal-rate modulo operator. Only works in AudioRange [-1, 1] and for modulus - * values in the NormalRange. - * - * @constructor - * @extends {Tone.SignalBase} - * @param {NormalRange} modulus The modulus to apply. - * @example - * var mod = new Tone.Modulo(0.2) - * var sig = new Tone.Signal(0.5).connect(mod); - * //mod outputs 0.1 - */ - Tone.Modulo = function (modulus) { - this.createInsOuts(1, 0); - /** - * A waveshaper gets the integer multiple of - * the input signal and the modulus. - * @private - * @type {Tone.WaveShaper} - */ - this._shaper = new Tone.WaveShaper(Math.pow(2, 16)); - /** - * the integer multiple is multiplied by the modulus - * @type {Tone.Multiply} - * @private - */ - this._multiply = new Tone.Multiply(); - /** - * and subtracted from the input signal - * @type {Tone.Subtract} - * @private - */ - this._subtract = this.output = new Tone.Subtract(); - /** - * the modulus signal - * @type {Tone.Signal} - * @private - */ - this._modSignal = new Tone.Signal(modulus); - //connections - this.input.fan(this._shaper, this._subtract); - this._modSignal.connect(this._multiply, 0, 0); - this._shaper.connect(this._multiply, 0, 1); - this._multiply.connect(this._subtract, 0, 1); - this._setWaveShaper(modulus); - }; - Tone.extend(Tone.Modulo, Tone.SignalBase); - /** - * @param {number} mod the modulus to apply - * @private - */ - Tone.Modulo.prototype._setWaveShaper = function (mod) { - this._shaper.setMap(function (val) { - var multiple = Math.floor((val + 0.0001) / mod); - return multiple; - }); - }; - /** - * The modulus value. - * @memberOf Tone.Modulo# - * @type {NormalRange} - * @name value - */ - Object.defineProperty(Tone.Modulo.prototype, 'value', { - get: function () { - return this._modSignal.value; - }, - set: function (mod) { - this._modSignal.value = mod; - this._setWaveShaper(mod); - } - }); - /** - * clean up - * @returns {Tone.Modulo} this - */ - Tone.Modulo.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._shaper.dispose(); - this._shaper = null; - this._multiply.dispose(); - this._multiply = null; - this._subtract.dispose(); - this._subtract = null; - this._modSignal.dispose(); - this._modSignal = null; - return this; - }; - return Tone.Modulo; - }); - Module(function (Tone) { - - /** - * @class AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1]. - * See Tone.GainToAudio. - * - * @extends {Tone.SignalBase} - * @constructor - * @example - * var a2g = new Tone.AudioToGain(); - */ - Tone.AudioToGain = function () { - /** - * @type {WaveShaperNode} - * @private - */ - this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { - return (x + 1) / 2; - }); - }; - Tone.extend(Tone.AudioToGain, Tone.SignalBase); - /** - * clean up - * @returns {Tone.AudioToGain} this - */ - Tone.AudioToGain.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._norm.dispose(); - this._norm = null; - return this; - }; - return Tone.AudioToGain; - }); - Module(function (Tone) { - - /** - * @class Evaluate an expression at audio rate.

- * Parsing code modified from https://code.google.com/p/tapdigit/ - * Copyright 2011 2012 Ariya Hidayat, New BSD License - * - * @extends {Tone.SignalBase} - * @constructor - * @param {string} expr the expression to generate - * @example - * //adds the signals from input[0] and input[1]. - * var expr = new Tone.Expr("$0 + $1"); - */ - Tone.Expr = function () { - var expr = this._replacements(Array.prototype.slice.call(arguments)); - var inputCount = this._parseInputs(expr); - /** - * hold onto all of the nodes for disposal - * @type {Array} - * @private - */ - this._nodes = []; - /** - * The inputs. The length is determined by the expression. - * @type {Array} - */ - this.input = new Array(inputCount); - //create a gain for each input - for (var i = 0; i < inputCount; i++) { - this.input[i] = this.context.createGain(); - } - //parse the syntax tree - var tree = this._parseTree(expr); - //evaluate the results - var result; - try { - result = this._eval(tree); - } catch (e) { - this._disposeNodes(); - throw new Error('Tone.Expr: Could evaluate expression: ' + expr); - } - /** - * The output node is the result of the expression - * @type {Tone} - */ - this.output = result; - }; - Tone.extend(Tone.Expr, Tone.SignalBase); - //some helpers to cut down the amount of code - function applyBinary(Constructor, args, self) { - var op = new Constructor(); - self._eval(args[0]).connect(op, 0, 0); - self._eval(args[1]).connect(op, 0, 1); - return op; - } - function applyUnary(Constructor, args, self) { - var op = new Constructor(); - self._eval(args[0]).connect(op, 0, 0); - return op; - } - function getNumber(arg) { - return arg ? parseFloat(arg) : undefined; - } - function literalNumber(arg) { - return arg && arg.args ? parseFloat(arg.args) : undefined; - } - /* - * the Expressions that Tone.Expr can parse. - * - * each expression belongs to a group and contains a regexp - * for selecting the operator as well as that operators method - * - * @type {Object} - * @private - */ - Tone.Expr._Expressions = { - //values - 'value': { - 'signal': { - regexp: /^\d+\.\d+|^\d+/, - method: function (arg) { - var sig = new Tone.Signal(getNumber(arg)); - return sig; - } - }, - 'input': { - regexp: /^\$\d/, - method: function (arg, self) { - return self.input[getNumber(arg.substr(1))]; - } - } - }, - //syntactic glue - 'glue': { - '(': { regexp: /^\(/ }, - ')': { regexp: /^\)/ }, - ',': { regexp: /^,/ } - }, - //functions - 'func': { - 'abs': { - regexp: /^abs/, - method: applyUnary.bind(this, Tone.Abs) - }, - 'mod': { - regexp: /^mod/, - method: function (args, self) { - var modulus = literalNumber(args[1]); - var op = new Tone.Modulo(modulus); - self._eval(args[0]).connect(op); - return op; - } - }, - 'pow': { - regexp: /^pow/, - method: function (args, self) { - var exp = literalNumber(args[1]); - var op = new Tone.Pow(exp); - self._eval(args[0]).connect(op); - return op; - } - }, - 'a2g': { - regexp: /^a2g/, - method: function (args, self) { - var op = new Tone.AudioToGain(); - self._eval(args[0]).connect(op); - return op; - } - } - }, - //binary expressions - 'binary': { - '+': { - regexp: /^\+/, - precedence: 1, - method: applyBinary.bind(this, Tone.Add) - }, - '-': { - regexp: /^\-/, - precedence: 1, - method: function (args, self) { - //both unary and binary op - if (args.length === 1) { - return applyUnary(Tone.Negate, args, self); - } else { - return applyBinary(Tone.Subtract, args, self); - } - } - }, - '*': { - regexp: /^\*/, - precedence: 0, - method: applyBinary.bind(this, Tone.Multiply) - } - }, - //unary expressions - 'unary': { - '-': { - regexp: /^\-/, - method: applyUnary.bind(this, Tone.Negate) - }, - '!': { - regexp: /^\!/, - method: applyUnary.bind(this, Tone.NOT) - } - } - }; - /** - * @param {string} expr the expression string - * @return {number} the input count - * @private - */ - Tone.Expr.prototype._parseInputs = function (expr) { - var inputArray = expr.match(/\$\d/g); - var inputMax = 0; - if (inputArray !== null) { - for (var i = 0; i < inputArray.length; i++) { - var inputNum = parseInt(inputArray[i].substr(1)) + 1; - inputMax = Math.max(inputMax, inputNum); - } - } - return inputMax; - }; - /** - * @param {Array} args an array of arguments - * @return {string} the results of the replacements being replaced - * @private - */ - Tone.Expr.prototype._replacements = function (args) { - var expr = args.shift(); - for (var i = 0; i < args.length; i++) { - expr = expr.replace(/\%/i, args[i]); - } - return expr; - }; - /** - * tokenize the expression based on the Expressions object - * @param {string} expr - * @return {Object} returns two methods on the tokenized list, next and peek - * @private - */ - Tone.Expr.prototype._tokenize = function (expr) { - var position = -1; - var tokens = []; - while (expr.length > 0) { - expr = expr.trim(); - var token = getNextToken(expr); - tokens.push(token); - expr = expr.substr(token.value.length); - } - function getNextToken(expr) { - for (var type in Tone.Expr._Expressions) { - var group = Tone.Expr._Expressions[type]; - for (var opName in group) { - var op = group[opName]; - var reg = op.regexp; - var match = expr.match(reg); - if (match !== null) { - return { - type: type, - value: match[0], - method: op.method - }; - } - } - } - throw new SyntaxError('Tone.Expr: Unexpected token ' + expr); - } - return { - next: function () { - return tokens[++position]; - }, - peek: function () { - return tokens[position + 1]; - } - }; - }; - /** - * recursively parse the string expression into a syntax tree - * - * @param {string} expr - * @return {Object} - * @private - */ - Tone.Expr.prototype._parseTree = function (expr) { - var lexer = this._tokenize(expr); - var isUndef = this.isUndef.bind(this); - function matchSyntax(token, syn) { - return !isUndef(token) && token.type === 'glue' && token.value === syn; - } - function matchGroup(token, groupName, prec) { - var ret = false; - var group = Tone.Expr._Expressions[groupName]; - if (!isUndef(token)) { - for (var opName in group) { - var op = group[opName]; - if (op.regexp.test(token.value)) { - if (!isUndef(prec)) { - if (op.precedence === prec) { - return true; - } - } else { - return true; - } - } - } - } - return ret; - } - function parseExpression(precedence) { - if (isUndef(precedence)) { - precedence = 5; - } - var expr; - if (precedence < 0) { - expr = parseUnary(); - } else { - expr = parseExpression(precedence - 1); - } - var token = lexer.peek(); - while (matchGroup(token, 'binary', precedence)) { - token = lexer.next(); - expr = { - operator: token.value, - method: token.method, - args: [ - expr, - parseExpression(precedence - 1) - ] - }; - token = lexer.peek(); - } - return expr; - } - function parseUnary() { - var token, expr; - token = lexer.peek(); - if (matchGroup(token, 'unary')) { - token = lexer.next(); - expr = parseUnary(); - return { - operator: token.value, - method: token.method, - args: [expr] - }; - } - return parsePrimary(); - } - function parsePrimary() { - var token, expr; - token = lexer.peek(); - if (isUndef(token)) { - throw new SyntaxError('Tone.Expr: Unexpected termination of expression'); - } - if (token.type === 'func') { - token = lexer.next(); - return parseFunctionCall(token); - } - if (token.type === 'value') { - token = lexer.next(); - return { - method: token.method, - args: token.value - }; - } - if (matchSyntax(token, '(')) { - lexer.next(); - expr = parseExpression(); - token = lexer.next(); - if (!matchSyntax(token, ')')) { - throw new SyntaxError('Expected )'); - } - return expr; - } - throw new SyntaxError('Tone.Expr: Parse error, cannot process token ' + token.value); - } - function parseFunctionCall(func) { - var token, args = []; - token = lexer.next(); - if (!matchSyntax(token, '(')) { - throw new SyntaxError('Tone.Expr: Expected ( in a function call "' + func.value + '"'); - } - token = lexer.peek(); - if (!matchSyntax(token, ')')) { - args = parseArgumentList(); - } - token = lexer.next(); - if (!matchSyntax(token, ')')) { - throw new SyntaxError('Tone.Expr: Expected ) in a function call "' + func.value + '"'); - } - return { - method: func.method, - args: args, - name: name - }; - } - function parseArgumentList() { - var token, expr, args = []; - while (true) { - expr = parseExpression(); - if (isUndef(expr)) { - // TODO maybe throw exception? - break; - } - args.push(expr); - token = lexer.peek(); - if (!matchSyntax(token, ',')) { - break; - } - lexer.next(); - } - return args; - } - return parseExpression(); - }; - /** - * recursively evaluate the expression tree - * @param {Object} tree - * @return {AudioNode} the resulting audio node from the expression - * @private - */ - Tone.Expr.prototype._eval = function (tree) { - if (!this.isUndef(tree)) { - var node = tree.method(tree.args, this); - this._nodes.push(node); - return node; - } - }; - /** - * dispose all the nodes - * @private - */ - Tone.Expr.prototype._disposeNodes = function () { - for (var i = 0; i < this._nodes.length; i++) { - var node = this._nodes[i]; - if (this.isFunction(node.dispose)) { - node.dispose(); - } else if (this.isFunction(node.disconnect)) { - node.disconnect(); - } - node = null; - this._nodes[i] = null; - } - this._nodes = null; - }; - /** - * clean up - */ - Tone.Expr.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._disposeNodes(); - }; - return Tone.Expr; - }); - Module(function (Tone) { - - /** - * @class Convert an incoming signal between 0, 1 to an equal power gain scale. - * - * @extends {Tone.SignalBase} - * @constructor - * @example - * var eqPowGain = new Tone.EqualPowerGain(); - */ - Tone.EqualPowerGain = function () { - /** - * @type {Tone.WaveShaper} - * @private - */ - this._eqPower = this.input = this.output = new Tone.WaveShaper(function (val) { - if (Math.abs(val) < 0.001) { - //should output 0 when input is 0 - return 0; - } else { - return this.equalPowerScale(val); - } - }.bind(this), 4096); - }; - Tone.extend(Tone.EqualPowerGain, Tone.SignalBase); - /** - * clean up - * @returns {Tone.EqualPowerGain} this - */ - Tone.EqualPowerGain.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._eqPower.dispose(); - this._eqPower = null; - return this; - }; - return Tone.EqualPowerGain; - }); - Module(function (Tone) { - - /** - * @class Tone.Crossfade provides equal power fading between two inputs. - * More on crossfading technique [here](https://en.wikipedia.org/wiki/Fade_(audio_engineering)#Crossfading). - * - * @constructor - * @extends {Tone} - * @param {NormalRange} [initialFade=0.5] - * @example - * var crossFade = new Tone.CrossFade(0.5); - * //connect effect A to crossfade from - * //effect output 0 to crossfade input 0 - * effectA.connect(crossFade, 0, 0); - * //connect effect B to crossfade from - * //effect output 0 to crossfade input 1 - * effectB.connect(crossFade, 0, 1); - * crossFade.fade.value = 0; - * // ^ only effectA is output - * crossFade.fade.value = 1; - * // ^ only effectB is output - * crossFade.fade.value = 0.5; - * // ^ the two signals are mixed equally. - */ - Tone.CrossFade = function (initialFade) { - this.createInsOuts(2, 1); - /** - * Alias for input[0]. - * @type {Tone.Gain} - */ - this.a = this.input[0] = new Tone.Gain(); - /** - * Alias for input[1]. - * @type {Tone.Gain} - */ - this.b = this.input[1] = new Tone.Gain(); - /** - * The mix between the two inputs. A fade value of 0 - * will output 100% input[0] and - * a value of 1 will output 100% input[1]. - * @type {NormalRange} - * @signal - */ - this.fade = new Tone.Signal(this.defaultArg(initialFade, 0.5), Tone.Type.NormalRange); - /** - * equal power gain cross fade - * @private - * @type {Tone.EqualPowerGain} - */ - this._equalPowerA = new Tone.EqualPowerGain(); - /** - * equal power gain cross fade - * @private - * @type {Tone.EqualPowerGain} - */ - this._equalPowerB = new Tone.EqualPowerGain(); - /** - * invert the incoming signal - * @private - * @type {Tone} - */ - this._invert = new Tone.Expr('1 - $0'); - //connections - this.a.connect(this.output); - this.b.connect(this.output); - this.fade.chain(this._equalPowerB, this.b.gain); - this.fade.chain(this._invert, this._equalPowerA, this.a.gain); - this._readOnly('fade'); - }; - Tone.extend(Tone.CrossFade); - /** - * clean up - * @returns {Tone.CrossFade} this - */ - Tone.CrossFade.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable('fade'); - this._equalPowerA.dispose(); - this._equalPowerA = null; - this._equalPowerB.dispose(); - this._equalPowerB = null; - this.fade.dispose(); - this.fade = null; - this._invert.dispose(); - this._invert = null; - this.a.dispose(); - this.a = null; - this.b.dispose(); - this.b = null; - return this; - }; - return Tone.CrossFade; - }); - Module(function (Tone) { - - /** - * @class Tone.Filter is a filter which allows for all of the same native methods - * as the [BiquadFilterNode](http://webaudio.github.io/web-audio-api/#the-biquadfilternode-interface). - * Tone.Filter has the added ability to set the filter rolloff at -12 - * (default), -24 and -48. - * - * @constructor - * @extends {Tone} - * @param {Frequency|Object} [frequency] The cutoff frequency of the filter. - * @param {string=} type The type of filter. - * @param {number=} rolloff The drop in decibels per octave after the cutoff frequency. - * 3 choices: -12, -24, and -48 - * @example - * var filter = new Tone.Filter(200, "highpass"); - */ - Tone.Filter = function () { - this.createInsOuts(1, 1); - var options = this.optionsObject(arguments, [ - 'frequency', - 'type', - 'rolloff' - ], Tone.Filter.defaults); - /** - * the filter(s) - * @type {Array} - * @private - */ - this._filters = []; - /** - * The cutoff frequency of the filter. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The detune parameter - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(0, Tone.Type.Cents); - /** - * The gain of the filter, only used in certain filter types - * @type {Number} - * @signal - */ - this.gain = new Tone.Signal({ - 'value': options.gain, - 'convert': false - }); - /** - * The Q or Quality of the filter - * @type {Positive} - * @signal - */ - this.Q = new Tone.Signal(options.Q); - /** - * the type of the filter - * @type {string} - * @private - */ - this._type = options.type; - /** - * the rolloff value of the filter - * @type {number} - * @private - */ - this._rolloff = options.rolloff; - //set the rolloff; - this.rolloff = options.rolloff; - this._readOnly([ - 'detune', - 'frequency', - 'gain', - 'Q' - ]); - }; - Tone.extend(Tone.Filter); - /** - * the default parameters - * - * @static - * @type {Object} - */ - Tone.Filter.defaults = { - 'type': 'lowpass', - 'frequency': 350, - 'rolloff': -12, - 'Q': 1, - 'gain': 0 - }; - /** - * The type of the filter. Types: "lowpass", "highpass", - * "bandpass", "lowshelf", "highshelf", "notch", "allpass", or "peaking". - * @memberOf Tone.Filter# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.Filter.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - var types = [ - 'lowpass', - 'highpass', - 'bandpass', - 'lowshelf', - 'highshelf', - 'notch', - 'allpass', - 'peaking' - ]; - if (types.indexOf(type) === -1) { - throw new TypeError('Tone.Filter: invalid type ' + type); - } - this._type = type; - for (var i = 0; i < this._filters.length; i++) { - this._filters[i].type = type; - } - } - }); - /** - * The rolloff of the filter which is the drop in db - * per octave. Implemented internally by cascading filters. - * Only accepts the values -12, -24, -48 and -96. - * @memberOf Tone.Filter# - * @type {number} - * @name rolloff - */ - Object.defineProperty(Tone.Filter.prototype, 'rolloff', { - get: function () { - return this._rolloff; - }, - set: function (rolloff) { - rolloff = parseInt(rolloff, 10); - var possibilities = [ - -12, - -24, - -48, - -96 - ]; - var cascadingCount = possibilities.indexOf(rolloff); - //check the rolloff is valid - if (cascadingCount === -1) { - throw new RangeError('Tone.Filter: rolloff can only be -12, -24, -48 or -96'); - } - cascadingCount += 1; - this._rolloff = rolloff; - //first disconnect the filters and throw them away - this.input.disconnect(); - for (var i = 0; i < this._filters.length; i++) { - this._filters[i].disconnect(); - this._filters[i] = null; - } - this._filters = new Array(cascadingCount); - for (var count = 0; count < cascadingCount; count++) { - var filter = this.context.createBiquadFilter(); - filter.type = this._type; - this.frequency.connect(filter.frequency); - this.detune.connect(filter.detune); - this.Q.connect(filter.Q); - this.gain.connect(filter.gain); - this._filters[count] = filter; - } - //connect them up - var connectionChain = [this.input].concat(this._filters).concat([this.output]); - this.connectSeries.apply(this, connectionChain); - } - }); - /** - * Clean up. - * @return {Tone.Filter} this - */ - Tone.Filter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - for (var i = 0; i < this._filters.length; i++) { - this._filters[i].disconnect(); - this._filters[i] = null; - } - this._filters = null; - this._writable([ - 'detune', - 'frequency', - 'gain', - 'Q' - ]); - this.frequency.dispose(); - this.Q.dispose(); - this.frequency = null; - this.Q = null; - this.detune.dispose(); - this.detune = null; - this.gain.dispose(); - this.gain = null; - return this; - }; - return Tone.Filter; - }); - Module(function (Tone) { - - /** - * @class Split the incoming signal into three bands (low, mid, high) - * with two crossover frequency controls. - * - * @extends {Tone} - * @constructor - * @param {Frequency|Object} [lowFrequency] the low/mid crossover frequency - * @param {Frequency} [highFrequency] the mid/high crossover frequency - */ - Tone.MultibandSplit = function () { - var options = this.optionsObject(arguments, [ - 'lowFrequency', - 'highFrequency' - ], Tone.MultibandSplit.defaults); - /** - * the input - * @type {Tone.Gain} - * @private - */ - this.input = new Tone.Gain(); - /** - * the outputs - * @type {Array} - * @private - */ - this.output = new Array(3); - /** - * The low band. Alias for output[0] - * @type {Tone.Filter} - */ - this.low = this.output[0] = new Tone.Filter(0, 'lowpass'); - /** - * the lower filter of the mid band - * @type {Tone.Filter} - * @private - */ - this._lowMidFilter = new Tone.Filter(0, 'highpass'); - /** - * The mid band output. Alias for output[1] - * @type {Tone.Filter} - */ - this.mid = this.output[1] = new Tone.Filter(0, 'lowpass'); - /** - * The high band output. Alias for output[2] - * @type {Tone.Filter} - */ - this.high = this.output[2] = new Tone.Filter(0, 'highpass'); - /** - * The low/mid crossover frequency. - * @type {Frequency} - * @signal - */ - this.lowFrequency = new Tone.Signal(options.lowFrequency, Tone.Type.Frequency); - /** - * The mid/high crossover frequency. - * @type {Frequency} - * @signal - */ - this.highFrequency = new Tone.Signal(options.highFrequency, Tone.Type.Frequency); - /** - * The quality of all the filters - * @type {Number} - * @signal - */ - this.Q = new Tone.Signal(options.Q); - this.input.fan(this.low, this.high); - this.input.chain(this._lowMidFilter, this.mid); - //the frequency control signal - this.lowFrequency.connect(this.low.frequency); - this.lowFrequency.connect(this._lowMidFilter.frequency); - this.highFrequency.connect(this.mid.frequency); - this.highFrequency.connect(this.high.frequency); - //the Q value - this.Q.connect(this.low.Q); - this.Q.connect(this._lowMidFilter.Q); - this.Q.connect(this.mid.Q); - this.Q.connect(this.high.Q); - this._readOnly([ - 'high', - 'mid', - 'low', - 'highFrequency', - 'lowFrequency' - ]); - }; - Tone.extend(Tone.MultibandSplit); - /** - * @private - * @static - * @type {Object} - */ - Tone.MultibandSplit.defaults = { - 'lowFrequency': 400, - 'highFrequency': 2500, - 'Q': 1 - }; - /** - * Clean up. - * @returns {Tone.MultibandSplit} this - */ - Tone.MultibandSplit.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'high', - 'mid', - 'low', - 'highFrequency', - 'lowFrequency' - ]); - this.low.dispose(); - this.low = null; - this._lowMidFilter.dispose(); - this._lowMidFilter = null; - this.mid.dispose(); - this.mid = null; - this.high.dispose(); - this.high = null; - this.lowFrequency.dispose(); - this.lowFrequency = null; - this.highFrequency.dispose(); - this.highFrequency = null; - this.Q.dispose(); - this.Q = null; - return this; - }; - return Tone.MultibandSplit; - }); - Module(function (Tone) { - - /** - * @class Tone.EQ3 is a three band EQ with control over low, mid, and high gain as - * well as the low and high crossover frequencies. - * - * @constructor - * @extends {Tone} - * - * @param {Decibels|Object} [lowLevel] The gain applied to the lows. - * @param {Decibels} [midLevel] The gain applied to the mid. - * @param {Decibels} [highLevel] The gain applied to the high. - * @example - * var eq = new Tone.EQ3(-10, 3, -20); - */ - Tone.EQ3 = function () { - var options = this.optionsObject(arguments, [ - 'low', - 'mid', - 'high' - ], Tone.EQ3.defaults); - /** - * the output node - * @type {GainNode} - * @private - */ - this.output = new Tone.Gain(); - /** - * the multiband split - * @type {Tone.MultibandSplit} - * @private - */ - this._multibandSplit = this.input = new Tone.MultibandSplit({ - 'lowFrequency': options.lowFrequency, - 'highFrequency': options.highFrequency - }); - /** - * The gain for the lower signals - * @type {Tone.Gain} - * @private - */ - this._lowGain = new Tone.Gain(options.low, Tone.Type.Decibels); - /** - * The gain for the mid signals - * @type {Tone.Gain} - * @private - */ - this._midGain = new Tone.Gain(options.mid, Tone.Type.Decibels); - /** - * The gain in decibels of the high part - * @type {Tone.Gain} - * @private - */ - this._highGain = new Tone.Gain(options.high, Tone.Type.Decibels); - /** - * The gain in decibels of the low part - * @type {Decibels} - * @signal - */ - this.low = this._lowGain.gain; - /** - * The gain in decibels of the mid part - * @type {Decibels} - * @signal - */ - this.mid = this._midGain.gain; - /** - * The gain in decibels of the high part - * @type {Decibels} - * @signal - */ - this.high = this._highGain.gain; - /** - * The Q value for all of the filters. - * @type {Positive} - * @signal - */ - this.Q = this._multibandSplit.Q; - /** - * The low/mid crossover frequency. - * @type {Frequency} - * @signal - */ - this.lowFrequency = this._multibandSplit.lowFrequency; - /** - * The mid/high crossover frequency. - * @type {Frequency} - * @signal - */ - this.highFrequency = this._multibandSplit.highFrequency; - //the frequency bands - this._multibandSplit.low.chain(this._lowGain, this.output); - this._multibandSplit.mid.chain(this._midGain, this.output); - this._multibandSplit.high.chain(this._highGain, this.output); - this._readOnly([ - 'low', - 'mid', - 'high', - 'lowFrequency', - 'highFrequency' - ]); - }; - Tone.extend(Tone.EQ3); - /** - * the default values - */ - Tone.EQ3.defaults = { - 'low': 0, - 'mid': 0, - 'high': 0, - 'lowFrequency': 400, - 'highFrequency': 2500 - }; - /** - * clean up - * @returns {Tone.EQ3} this - */ - Tone.EQ3.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'low', - 'mid', - 'high', - 'lowFrequency', - 'highFrequency' - ]); - this._multibandSplit.dispose(); - this._multibandSplit = null; - this.lowFrequency = null; - this.highFrequency = null; - this._lowGain.dispose(); - this._lowGain = null; - this._midGain.dispose(); - this._midGain = null; - this._highGain.dispose(); - this._highGain = null; - this.low = null; - this.mid = null; - this.high = null; - this.Q = null; - return this; - }; - return Tone.EQ3; - }); - Module(function (Tone) { - - /** - * @class Performs a linear scaling on an input signal. - * Scales a NormalRange input to between - * outputMin and outputMax. - * - * @constructor - * @extends {Tone.SignalBase} - * @param {number} [outputMin=0] The output value when the input is 0. - * @param {number} [outputMax=1] The output value when the input is 1. - * @example - * var scale = new Tone.Scale(50, 100); - * var signal = new Tone.Signal(0.5).connect(scale); - * //the output of scale equals 75 - */ - Tone.Scale = function (outputMin, outputMax) { - /** - * @private - * @type {number} - */ - this._outputMin = this.defaultArg(outputMin, 0); - /** - * @private - * @type {number} - */ - this._outputMax = this.defaultArg(outputMax, 1); - /** - * @private - * @type {Tone.Multiply} - * @private - */ - this._scale = this.input = new Tone.Multiply(1); - /** - * @private - * @type {Tone.Add} - * @private - */ - this._add = this.output = new Tone.Add(0); - this._scale.connect(this._add); - this._setRange(); - }; - Tone.extend(Tone.Scale, Tone.SignalBase); - /** - * The minimum output value. This number is output when - * the value input value is 0. - * @memberOf Tone.Scale# - * @type {number} - * @name min - */ - Object.defineProperty(Tone.Scale.prototype, 'min', { - get: function () { - return this._outputMin; - }, - set: function (min) { - this._outputMin = min; - this._setRange(); - } - }); - /** - * The maximum output value. This number is output when - * the value input value is 1. - * @memberOf Tone.Scale# - * @type {number} - * @name max - */ - Object.defineProperty(Tone.Scale.prototype, 'max', { - get: function () { - return this._outputMax; - }, - set: function (max) { - this._outputMax = max; - this._setRange(); - } - }); - /** - * set the values - * @private - */ - Tone.Scale.prototype._setRange = function () { - this._add.value = this._outputMin; - this._scale.value = this._outputMax - this._outputMin; - }; - /** - * Clean up. - * @returns {Tone.Scale} this - */ - Tone.Scale.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._add.dispose(); - this._add = null; - this._scale.dispose(); - this._scale = null; - return this; - }; - return Tone.Scale; - }); - Module(function (Tone) { - /** - * @class Performs an exponential scaling on an input signal. - * Scales a NormalRange value [0,1] exponentially - * to the output range of outputMin to outputMax. - * - * @constructor - * @extends {Tone.SignalBase} - * @param {number} [outputMin=0] The output value when the input is 0. - * @param {number} [outputMax=1] The output value when the input is 1. - * @param {number} [exponent=2] The exponent which scales the incoming signal. - * @example - * var scaleExp = new Tone.ScaleExp(0, 100, 2); - * var signal = new Tone.Signal(0.5).connect(scaleExp); - */ - Tone.ScaleExp = function (outputMin, outputMax, exponent) { - /** - * scale the input to the output range - * @type {Tone.Scale} - * @private - */ - this._scale = this.output = new Tone.Scale(outputMin, outputMax); - /** - * @private - * @type {Tone.Pow} - * @private - */ - this._exp = this.input = new Tone.Pow(this.defaultArg(exponent, 2)); - this._exp.connect(this._scale); - }; - Tone.extend(Tone.ScaleExp, Tone.SignalBase); - /** - * Instead of interpolating linearly between the min and - * max values, setting the exponent will interpolate between - * the two values with an exponential curve. - * @memberOf Tone.ScaleExp# - * @type {number} - * @name exponent - */ - Object.defineProperty(Tone.ScaleExp.prototype, 'exponent', { - get: function () { - return this._exp.value; - }, - set: function (exp) { - this._exp.value = exp; - } - }); - /** - * The minimum output value. This number is output when - * the value input value is 0. - * @memberOf Tone.ScaleExp# - * @type {number} - * @name min - */ - Object.defineProperty(Tone.ScaleExp.prototype, 'min', { - get: function () { - return this._scale.min; - }, - set: function (min) { - this._scale.min = min; - } - }); - /** - * The maximum output value. This number is output when - * the value input value is 1. - * @memberOf Tone.ScaleExp# - * @type {number} - * @name max - */ - Object.defineProperty(Tone.ScaleExp.prototype, 'max', { - get: function () { - return this._scale.max; - }, - set: function (max) { - this._scale.max = max; - } - }); - /** - * Clean up. - * @returns {Tone.ScaleExp} this - */ - Tone.ScaleExp.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._scale.dispose(); - this._scale = null; - this._exp.dispose(); - this._exp = null; - return this; - }; - return Tone.ScaleExp; - }); - Module(function (Tone) { - - /** - * createDelay shim - * @private - */ - if (window.DelayNode && !AudioContext.prototype.createDelay) { - AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; - } - /** - * @class Wrapper around Web Audio's native [DelayNode](http://webaudio.github.io/web-audio-api/#the-delaynode-interface). - * @extends {Tone} - * @param {Time=} delayTime The delay applied to the incoming signal. - * @param {Time=} maxDelay The maximum delay time. - */ - Tone.Delay = function () { - var options = this.optionsObject(arguments, [ - 'delayTime', - 'maxDelay' - ], Tone.Delay.defaults); - /** - * The native delay node - * @type {DelayNode} - * @private - */ - this._delayNode = this.input = this.output = this.context.createDelay(this.toSeconds(options.maxDelay)); - /** - * The amount of time the incoming signal is - * delayed. - * @type {Tone.Param} - * @signal - */ - this.delayTime = new Tone.Param({ - 'param': this._delayNode.delayTime, - 'units': Tone.Type.Time, - 'value': options.delayTime - }); - this._readOnly('delayTime'); - }; - Tone.extend(Tone.Delay); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.Delay.defaults = { - 'maxDelay': 1, - 'delayTime': 0 - }; - /** - * Clean up. - * @return {Tone.Delay} this - */ - Tone.Delay.prototype.dispose = function () { - Tone.Param.prototype.dispose.call(this); - this._delayNode.disconnect(); - this._delayNode = null; - this._writable('delayTime'); - this.delayTime = null; - return this; - }; - return Tone.Delay; - }); - Module(function (Tone) { - - /** - * @class Comb filters are basic building blocks for physical modeling. Read more - * about comb filters on [CCRMA's website](https://ccrma.stanford.edu/~jos/pasp/Feedback_Comb_Filters.html). - * - * @extends {Tone} - * @constructor - * @param {Time|Object} [delayTime] The delay time of the filter. - * @param {NormalRange=} resonance The amount of feedback the filter has. - */ - Tone.FeedbackCombFilter = function () { - var options = this.optionsObject(arguments, [ - 'delayTime', - 'resonance' - ], Tone.FeedbackCombFilter.defaults); - /** - * the delay node - * @type {DelayNode} - * @private - */ - this._delay = this.input = this.output = new Tone.Delay(options.delayTime); - /** - * The amount of delay of the comb filter. - * @type {Time} - * @signal - */ - this.delayTime = this._delay.delayTime; - /** - * the feedback node - * @type {GainNode} - * @private - */ - this._feedback = new Tone.Gain(options.resonance, Tone.Type.NormalRange); - /** - * The amount of feedback of the delayed signal. - * @type {NormalRange} - * @signal - */ - this.resonance = this._feedback.gain; - this._delay.chain(this._feedback, this._delay); - this._readOnly([ - 'resonance', - 'delayTime' - ]); - }; - Tone.extend(Tone.FeedbackCombFilter); - /** - * the default parameters - * @static - * @const - * @type {Object} - */ - Tone.FeedbackCombFilter.defaults = { - 'delayTime': 0.1, - 'resonance': 0.5 - }; - /** - * clean up - * @returns {Tone.FeedbackCombFilter} this - */ - Tone.FeedbackCombFilter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'resonance', - 'delayTime' - ]); - this._delay.dispose(); - this._delay = null; - this.delayTime = null; - this._feedback.dispose(); - this._feedback = null; - this.resonance = null; - return this; - }; - return Tone.FeedbackCombFilter; - }); - Module(function (Tone) { - - /** - * @class Tone.Follower is a crude envelope follower which will follow - * the amplitude of an incoming signal. - * Take care with small (< 0.02) attack or decay values - * as follower has some ripple which is exaggerated - * at these values. Read more about envelope followers (also known - * as envelope detectors) on [Wikipedia](https://en.wikipedia.org/wiki/Envelope_detector). - * - * @constructor - * @extends {Tone} - * @param {Time|Object} [attack] The rate at which the follower rises. - * @param {Time=} release The rate at which the folower falls. - * @example - * var follower = new Tone.Follower(0.2, 0.4); - */ - Tone.Follower = function () { - this.createInsOuts(1, 1); - var options = this.optionsObject(arguments, [ - 'attack', - 'release' - ], Tone.Follower.defaults); - /** - * @type {Tone.Abs} - * @private - */ - this._abs = new Tone.Abs(); - /** - * the lowpass filter which smooths the input - * @type {BiquadFilterNode} - * @private - */ - this._filter = this.context.createBiquadFilter(); - this._filter.type = 'lowpass'; - this._filter.frequency.value = 0; - this._filter.Q.value = -100; - /** - * @type {WaveShaperNode} - * @private - */ - this._frequencyValues = new Tone.WaveShaper(); - /** - * @type {Tone.Subtract} - * @private - */ - this._sub = new Tone.Subtract(); - /** - * @type {Tone.Delay} - * @private - */ - this._delay = new Tone.Delay(this.blockTime); - /** - * this keeps it far from 0, even for very small differences - * @type {Tone.Multiply} - * @private - */ - this._mult = new Tone.Multiply(10000); - /** - * @private - * @type {number} - */ - this._attack = options.attack; - /** - * @private - * @type {number} - */ - this._release = options.release; - //the smoothed signal to get the values - this.input.chain(this._abs, this._filter, this.output); - //the difference path - this._abs.connect(this._sub, 0, 1); - this._filter.chain(this._delay, this._sub); - //threshold the difference and use the thresh to set the frequency - this._sub.chain(this._mult, this._frequencyValues, this._filter.frequency); - //set the attack and release values in the table - this._setAttackRelease(this._attack, this._release); - }; - Tone.extend(Tone.Follower); - /** - * @static - * @type {Object} - */ - Tone.Follower.defaults = { - 'attack': 0.05, - 'release': 0.5 - }; - /** - * sets the attack and release times in the wave shaper - * @param {Time} attack - * @param {Time} release - * @private - */ - Tone.Follower.prototype._setAttackRelease = function (attack, release) { - var minTime = this.blockTime; - attack = Tone.Time(attack).toFrequency(); - release = Tone.Time(release).toFrequency(); - attack = Math.max(attack, minTime); - release = Math.max(release, minTime); - this._frequencyValues.setMap(function (val) { - if (val <= 0) { - return attack; - } else { - return release; - } - }); - }; - /** - * The attack time. - * @memberOf Tone.Follower# - * @type {Time} - * @name attack - */ - Object.defineProperty(Tone.Follower.prototype, 'attack', { - get: function () { - return this._attack; - }, - set: function (attack) { - this._attack = attack; - this._setAttackRelease(this._attack, this._release); - } - }); - /** - * The release time. - * @memberOf Tone.Follower# - * @type {Time} - * @name release - */ - Object.defineProperty(Tone.Follower.prototype, 'release', { - get: function () { - return this._release; - }, - set: function (release) { - this._release = release; - this._setAttackRelease(this._attack, this._release); - } - }); - /** - * Borrows the connect method from Signal so that the output can be used - * as a Tone.Signal control signal. - * @function - */ - Tone.Follower.prototype.connect = Tone.Signal.prototype.connect; - /** - * dispose - * @returns {Tone.Follower} this - */ - Tone.Follower.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._filter.disconnect(); - this._filter = null; - this._frequencyValues.disconnect(); - this._frequencyValues = null; - this._delay.dispose(); - this._delay = null; - this._sub.disconnect(); - this._sub = null; - this._abs.dispose(); - this._abs = null; - this._mult.dispose(); - this._mult = null; - this._curve = null; - return this; - }; - return Tone.Follower; - }); - Module(function (Tone) { - - /** - * @class Tone.ScaledEnvelop is an envelope which can be scaled - * to any range. It's useful for applying an envelope - * to a frequency or any other non-NormalRange signal - * parameter. - * - * @extends {Tone.Envelope} - * @constructor - * @param {Time|Object} [attack] the attack time in seconds - * @param {Time} [decay] the decay time in seconds - * @param {number} [sustain] a percentage (0-1) of the full amplitude - * @param {Time} [release] the release time in seconds - * @example - * var scaledEnv = new Tone.ScaledEnvelope({ - * "attack" : 0.2, - * "min" : 200, - * "max" : 2000 - * }); - * scaledEnv.connect(oscillator.frequency); - */ - Tone.ScaledEnvelope = function () { - //get all of the defaults - var options = this.optionsObject(arguments, [ - 'attack', - 'decay', - 'sustain', - 'release' - ], Tone.Envelope.defaults); - Tone.Envelope.call(this, options); - options = this.defaultArg(options, Tone.ScaledEnvelope.defaults); - /** - * scale the incoming signal by an exponent - * @type {Tone.Pow} - * @private - */ - this._exp = this.output = new Tone.Pow(options.exponent); - /** - * scale the signal to the desired range - * @type {Tone.Multiply} - * @private - */ - this._scale = this.output = new Tone.Scale(options.min, options.max); - this._sig.chain(this._exp, this._scale); - }; - Tone.extend(Tone.ScaledEnvelope, Tone.Envelope); - /** - * the default parameters - * @static - */ - Tone.ScaledEnvelope.defaults = { - 'min': 0, - 'max': 1, - 'exponent': 1 - }; - /** - * The envelope's min output value. This is the value which it - * starts at. - * @memberOf Tone.ScaledEnvelope# - * @type {number} - * @name min - */ - Object.defineProperty(Tone.ScaledEnvelope.prototype, 'min', { - get: function () { - return this._scale.min; - }, - set: function (min) { - this._scale.min = min; - } - }); - /** - * The envelope's max output value. In other words, the value - * at the peak of the attack portion of the envelope. - * @memberOf Tone.ScaledEnvelope# - * @type {number} - * @name max - */ - Object.defineProperty(Tone.ScaledEnvelope.prototype, 'max', { - get: function () { - return this._scale.max; - }, - set: function (max) { - this._scale.max = max; - } - }); - /** - * The envelope's exponent value. - * @memberOf Tone.ScaledEnvelope# - * @type {number} - * @name exponent - */ - Object.defineProperty(Tone.ScaledEnvelope.prototype, 'exponent', { - get: function () { - return this._exp.value; - }, - set: function (exp) { - this._exp.value = exp; - } - }); - /** - * clean up - * @returns {Tone.ScaledEnvelope} this - */ - Tone.ScaledEnvelope.prototype.dispose = function () { - Tone.Envelope.prototype.dispose.call(this); - this._scale.dispose(); - this._scale = null; - this._exp.dispose(); - this._exp = null; - return this; - }; - return Tone.ScaledEnvelope; - }); - Module(function (Tone) { - - /** - * @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max` - * it's got a `baseFrequency` and `octaves` parameter. - * - * @extends {Tone.Envelope} - * @constructor - * @param {Time|Object} [attack] the attack time in seconds - * @param {Time} [decay] the decay time in seconds - * @param {number} [sustain] a percentage (0-1) of the full amplitude - * @param {Time} [release] the release time in seconds - * @example - * var env = new Tone.FrequencyEnvelope({ - * "attack" : 0.2, - * "baseFrequency" : "C2", - * "octaves" : 4 - * }); - * scaledEnv.connect(oscillator.frequency); - */ - Tone.FrequencyEnvelope = function () { - var options = this.optionsObject(arguments, [ - 'attack', - 'decay', - 'sustain', - 'release' - ], Tone.Envelope.defaults); - Tone.ScaledEnvelope.call(this, options); - options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults); - /** - * Stores the octave value - * @type {Positive} - * @private - */ - this._octaves = options.octaves; - //setup - this.baseFrequency = options.baseFrequency; - this.octaves = options.octaves; - }; - Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope); - /** - * the default parameters - * @static - */ - Tone.FrequencyEnvelope.defaults = { - 'baseFrequency': 200, - 'octaves': 4, - 'exponent': 2 - }; - /** - * The envelope's mininum output value. This is the value which it - * starts at. - * @memberOf Tone.FrequencyEnvelope# - * @type {Frequency} - * @name baseFrequency - */ - Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'baseFrequency', { - get: function () { - return this._scale.min; - }, - set: function (min) { - this._scale.min = this.toFrequency(min); - //also update the octaves - this.octaves = this._octaves; - } - }); - /** - * The number of octaves above the baseFrequency that the - * envelope will scale to. - * @memberOf Tone.FrequencyEnvelope# - * @type {Positive} - * @name octaves - */ - Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'octaves', { - get: function () { - return this._octaves; - }, - set: function (octaves) { - this._octaves = octaves; - this._scale.max = this.baseFrequency * Math.pow(2, octaves); - } - }); - /** - * The envelope's exponent value. - * @memberOf Tone.FrequencyEnvelope# - * @type {number} - * @name exponent - */ - Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'exponent', { - get: function () { - return this._exp.value; - }, - set: function (exp) { - this._exp.value = exp; - } - }); - /** - * clean up - * @returns {Tone.FrequencyEnvelope} this - */ - Tone.FrequencyEnvelope.prototype.dispose = function () { - Tone.ScaledEnvelope.prototype.dispose.call(this); - return this; - }; - return Tone.FrequencyEnvelope; - }); - Module(function (Tone) { - - /** - * @class Tone.Gate only passes a signal through when the incoming - * signal exceeds a specified threshold. To do this, Gate uses - * a Tone.Follower to follow the amplitude of the incoming signal. - * A common implementation of this class is a [Noise Gate](https://en.wikipedia.org/wiki/Noise_gate). - * - * @constructor - * @extends {Tone} - * @param {Decibels|Object} [threshold] The threshold above which the gate will open. - * @param {Time=} attack The follower's attack time - * @param {Time=} release The follower's release time - * @example - * var gate = new Tone.Gate(-30, 0.2, 0.3).toMaster(); - * var mic = new Tone.UserMedia().connect(gate); - * //the gate will only pass through the incoming - * //signal when it's louder than -30db - */ - Tone.Gate = function () { - this.createInsOuts(1, 1); - var options = this.optionsObject(arguments, [ - 'threshold', - 'attack', - 'release' - ], Tone.Gate.defaults); - /** - * @type {Tone.Follower} - * @private - */ - this._follower = new Tone.Follower(options.attack, options.release); - /** - * @type {Tone.GreaterThan} - * @private - */ - this._gt = new Tone.GreaterThan(this.dbToGain(options.threshold)); - //the connections - this.input.connect(this.output); - //the control signal - this.input.chain(this._gt, this._follower, this.output.gain); - }; - Tone.extend(Tone.Gate); - /** - * @const - * @static - * @type {Object} - */ - Tone.Gate.defaults = { - 'attack': 0.1, - 'release': 0.1, - 'threshold': -40 - }; - /** - * The threshold of the gate in decibels - * @memberOf Tone.Gate# - * @type {Decibels} - * @name threshold - */ - Object.defineProperty(Tone.Gate.prototype, 'threshold', { - get: function () { - return this.gainToDb(this._gt.value); - }, - set: function (thresh) { - this._gt.value = this.dbToGain(thresh); - } - }); - /** - * The attack speed of the gate - * @memberOf Tone.Gate# - * @type {Time} - * @name attack - */ - Object.defineProperty(Tone.Gate.prototype, 'attack', { - get: function () { - return this._follower.attack; - }, - set: function (attackTime) { - this._follower.attack = attackTime; - } - }); - /** - * The release speed of the gate - * @memberOf Tone.Gate# - * @type {Time} - * @name release - */ - Object.defineProperty(Tone.Gate.prototype, 'release', { - get: function () { - return this._follower.release; - }, - set: function (releaseTime) { - this._follower.release = releaseTime; - } - }); - /** - * Clean up. - * @returns {Tone.Gate} this - */ - Tone.Gate.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._follower.dispose(); - this._gt.dispose(); - this._follower = null; - this._gt = null; - return this; - }; - return Tone.Gate; - }); - Module(function (Tone) { - - /** - * @class A Timeline State. Provides the methods: setStateAtTime("state", time) - * and getValueAtTime(time). - * - * @extends {Tone.Timeline} - * @param {String} initial The initial state of the TimelineState. - * Defaults to undefined - */ - Tone.TimelineState = function (initial) { - Tone.Timeline.call(this); - /** - * The initial state - * @private - * @type {String} - */ - this._initial = initial; - }; - Tone.extend(Tone.TimelineState, Tone.Timeline); - /** - * Returns the scheduled state scheduled before or at - * the given time. - * @param {Number} time The time to query. - * @return {String} The name of the state input in setStateAtTime. - */ - Tone.TimelineState.prototype.getValueAtTime = function (time) { - var event = this.get(time); - if (event !== null) { - return event.state; - } else { - return this._initial; - } - }; - /** - * Returns the scheduled state scheduled before or at - * the given time. - * @param {String} state The name of the state to set. - * @param {Number} time The time to query. - */ - Tone.TimelineState.prototype.setStateAtTime = function (state, time) { - this.add({ - 'state': state, - 'time': time - }); - }; - return Tone.TimelineState; - }); - Module(function (Tone) { - - /** - * @class A sample accurate clock which provides a callback at the given rate. - * While the callback is not sample-accurate (it is still susceptible to - * loose JS timing), the time passed in as the argument to the callback - * is precise. For most applications, it is better to use Tone.Transport - * instead of the Clock by itself since you can synchronize multiple callbacks. - * - * @constructor - * @extends {Tone.Emitter} - * @param {function} callback The callback to be invoked with the time of the audio event - * @param {Frequency} frequency The rate of the callback - * @example - * //the callback will be invoked approximately once a second - * //and will print the time exactly once a second apart. - * var clock = new Tone.Clock(function(time){ - * console.log(time); - * }, 1); - */ - Tone.Clock = function () { - Tone.Emitter.call(this); - var options = this.optionsObject(arguments, [ - 'callback', - 'frequency' - ], Tone.Clock.defaults); - /** - * The callback function to invoke at the scheduled tick. - * @type {Function} - */ - this.callback = options.callback; - /** - * The next time the callback is scheduled. - * @type {Number} - * @private - */ - this._nextTick = 0; - /** - * The last state of the clock. - * @type {State} - * @private - */ - this._lastState = Tone.State.Stopped; - /** - * The rate the callback function should be invoked. - * @type {BPM} - * @signal - */ - this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); - this._readOnly('frequency'); - /** - * The number of times the callback was invoked. Starts counting at 0 - * and increments after the callback was invoked. - * @type {Ticks} - * @readOnly - */ - this.ticks = 0; - /** - * The state timeline - * @type {Tone.TimelineState} - * @private - */ - this._state = new Tone.TimelineState(Tone.State.Stopped); - /** - * The loop function bound to its context. - * This is necessary to remove the event in the end. - * @type {Function} - * @private - */ - this._boundLoop = this._loop.bind(this); - //bind a callback to the worker thread - this.context.on('tick', this._boundLoop); - }; - Tone.extend(Tone.Clock, Tone.Emitter); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.Clock.defaults = { - 'callback': Tone.noOp, - 'frequency': 1, - 'lookAhead': 'auto' - }; - /** - * Returns the playback state of the source, either "started", "stopped" or "paused". - * @type {Tone.State} - * @readOnly - * @memberOf Tone.Clock# - * @name state - */ - Object.defineProperty(Tone.Clock.prototype, 'state', { - get: function () { - return this._state.getValueAtTime(this.now()); - } - }); - /** - * Start the clock at the given time. Optionally pass in an offset - * of where to start the tick counter from. - * @param {Time} time The time the clock should start - * @param {Ticks=} offset Where the tick counter starts counting from. - * @return {Tone.Clock} this - */ - Tone.Clock.prototype.start = function (time, offset) { - time = this.toSeconds(time); - if (this._state.getValueAtTime(time) !== Tone.State.Started) { - this._state.add({ - 'state': Tone.State.Started, - 'time': time, - 'offset': offset - }); - } - return this; - }; - /** - * Stop the clock. Stopping the clock resets the tick counter to 0. - * @param {Time} [time=now] The time when the clock should stop. - * @returns {Tone.Clock} this - * @example - * clock.stop(); - */ - Tone.Clock.prototype.stop = function (time) { - time = this.toSeconds(time); - this._state.cancel(time); - this._state.setStateAtTime(Tone.State.Stopped, time); - return this; - }; - /** - * Pause the clock. Pausing does not reset the tick counter. - * @param {Time} [time=now] The time when the clock should stop. - * @returns {Tone.Clock} this - */ - Tone.Clock.prototype.pause = function (time) { - time = this.toSeconds(time); - if (this._state.getValueAtTime(time) === Tone.State.Started) { - this._state.setStateAtTime(Tone.State.Paused, time); - } - return this; - }; - /** - * The scheduling loop. - * @param {Number} time The current page time starting from 0 - * when the page was loaded. - * @private - */ - Tone.Clock.prototype._loop = function () { - //get the frequency value to compute the value of the next loop - var now = this.now(); - //if it's started - var lookAhead = this.context.lookAhead; - var updateInterval = this.context.updateInterval; - var lagCompensation = this.context.lag * 2; - var loopInterval = now + lookAhead + updateInterval + lagCompensation; - while (loopInterval > this._nextTick && this._state) { - var currentState = this._state.getValueAtTime(this._nextTick); - if (currentState !== this._lastState) { - this._lastState = currentState; - var event = this._state.get(this._nextTick); - // emit an event - if (currentState === Tone.State.Started) { - //correct the time - this._nextTick = event.time; - if (!this.isUndef(event.offset)) { - this.ticks = event.offset; - } - this.emit('start', event.time, this.ticks); - } else if (currentState === Tone.State.Stopped) { - this.ticks = 0; - this.emit('stop', event.time); - } else if (currentState === Tone.State.Paused) { - this.emit('pause', event.time); - } - } - var tickTime = this._nextTick; - if (this.frequency) { - this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); - if (currentState === Tone.State.Started) { - this.callback(tickTime); - this.ticks++; - } - } - } - }; - /** - * Returns the scheduled state at the given time. - * @param {Time} time The time to query. - * @return {String} The name of the state input in setStateAtTime. - * @example - * clock.start("+0.1"); - * clock.getStateAtTime("+0.1"); //returns "started" - */ - Tone.Clock.prototype.getStateAtTime = function (time) { - time = this.toSeconds(time); - return this._state.getValueAtTime(time); - }; - /** - * Clean up - * @returns {Tone.Clock} this - */ - Tone.Clock.prototype.dispose = function () { - Tone.Emitter.prototype.dispose.call(this); - this.context.off('tick', this._boundLoop); - this._writable('frequency'); - this.frequency.dispose(); - this.frequency = null; - this._boundLoop = null; - this._nextTick = Infinity; - this.callback = null; - this._state.dispose(); - this._state = null; - }; - return Tone.Clock; - }); - Module(function (Tone) { - - /** - * @class Similar to Tone.Timeline, but all events represent - * intervals with both "time" and "duration" times. The - * events are placed in a tree structure optimized - * for querying an intersection point with the timeline - * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree) - * to represent the data. - * @extends {Tone} - */ - Tone.IntervalTimeline = function () { - /** - * The root node of the inteval tree - * @type {IntervalNode} - * @private - */ - this._root = null; - /** - * Keep track of the length of the timeline. - * @type {Number} - * @private - */ - this._length = 0; - }; - Tone.extend(Tone.IntervalTimeline); - /** - * The event to add to the timeline. All events must - * have a time and duration value - * @param {Object} event The event to add to the timeline - * @return {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.add = function (event) { - if (this.isUndef(event.time) || this.isUndef(event.duration)) { - throw new Error('Tone.IntervalTimeline: events must have time and duration parameters'); - } - var node = new IntervalNode(event.time, event.time + event.duration, event); - if (this._root === null) { - this._root = node; - } else { - this._root.insert(node); - } - this._length++; - // Restructure tree to be balanced - while (node !== null) { - node.updateHeight(); - node.updateMax(); - this._rebalance(node); - node = node.parent; - } - return this; - }; - /** - * Remove an event from the timeline. - * @param {Object} event The event to remove from the timeline - * @return {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.remove = function (event) { - if (this._root !== null) { - var results = []; - this._root.search(event.time, results); - for (var i = 0; i < results.length; i++) { - var node = results[i]; - if (node.event === event) { - this._removeNode(node); - this._length--; - break; - } - } - } - return this; - }; - /** - * The number of items in the timeline. - * @type {Number} - * @memberOf Tone.IntervalTimeline# - * @name length - * @readOnly - */ - Object.defineProperty(Tone.IntervalTimeline.prototype, 'length', { - get: function () { - return this._length; - } - }); - /** - * Remove events whose time time is after the given time - * @param {Number} time The time to query. - * @returns {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.cancel = function (after) { - this.forEachAfter(after, function (event) { - this.remove(event); - }.bind(this)); - return this; - }; - /** - * Set the root node as the given node - * @param {IntervalNode} node - * @private - */ - Tone.IntervalTimeline.prototype._setRoot = function (node) { - this._root = node; - if (this._root !== null) { - this._root.parent = null; - } - }; - /** - * Replace the references to the node in the node's parent - * with the replacement node. - * @param {IntervalNode} node - * @param {IntervalNode} replacement - * @private - */ - Tone.IntervalTimeline.prototype._replaceNodeInParent = function (node, replacement) { - if (node.parent !== null) { - if (node.isLeftChild()) { - node.parent.left = replacement; - } else { - node.parent.right = replacement; - } - this._rebalance(node.parent); - } else { - this._setRoot(replacement); - } - }; - /** - * Remove the node from the tree and replace it with - * a successor which follows the schema. - * @param {IntervalNode} node - * @private - */ - Tone.IntervalTimeline.prototype._removeNode = function (node) { - if (node.left === null && node.right === null) { - this._replaceNodeInParent(node, null); - } else if (node.right === null) { - this._replaceNodeInParent(node, node.left); - } else if (node.left === null) { - this._replaceNodeInParent(node, node.right); - } else { - var balance = node.getBalance(); - var replacement, temp; - if (balance > 0) { - if (node.left.right === null) { - replacement = node.left; - replacement.right = node.right; - temp = replacement; - } else { - replacement = node.left.right; - while (replacement.right !== null) { - replacement = replacement.right; - } - replacement.parent.right = replacement.left; - temp = replacement.parent; - replacement.left = node.left; - replacement.right = node.right; - } - } else { - if (node.right.left === null) { - replacement = node.right; - replacement.left = node.left; - temp = replacement; - } else { - replacement = node.right.left; - while (replacement.left !== null) { - replacement = replacement.left; - } - replacement.parent = replacement.parent; - replacement.parent.left = replacement.right; - temp = replacement.parent; - replacement.left = node.left; - replacement.right = node.right; - } - } - if (node.parent !== null) { - if (node.isLeftChild()) { - node.parent.left = replacement; - } else { - node.parent.right = replacement; - } - } else { - this._setRoot(replacement); - } - // this._replaceNodeInParent(node, replacement); - this._rebalance(temp); - } - node.dispose(); - }; - /** - * Rotate the tree to the left - * @param {IntervalNode} node - * @private - */ - Tone.IntervalTimeline.prototype._rotateLeft = function (node) { - var parent = node.parent; - var isLeftChild = node.isLeftChild(); - // Make node.right the new root of this sub tree (instead of node) - var pivotNode = node.right; - node.right = pivotNode.left; - pivotNode.left = node; - if (parent !== null) { - if (isLeftChild) { - parent.left = pivotNode; - } else { - parent.right = pivotNode; - } - } else { - this._setRoot(pivotNode); - } - }; - /** - * Rotate the tree to the right - * @param {IntervalNode} node - * @private - */ - Tone.IntervalTimeline.prototype._rotateRight = function (node) { - var parent = node.parent; - var isLeftChild = node.isLeftChild(); - // Make node.left the new root of this sub tree (instead of node) - var pivotNode = node.left; - node.left = pivotNode.right; - pivotNode.right = node; - if (parent !== null) { - if (isLeftChild) { - parent.left = pivotNode; - } else { - parent.right = pivotNode; - } - } else { - this._setRoot(pivotNode); - } - }; - /** - * Balance the BST - * @param {IntervalNode} node - * @private - */ - Tone.IntervalTimeline.prototype._rebalance = function (node) { - var balance = node.getBalance(); - if (balance > 1) { - if (node.left.getBalance() < 0) { - this._rotateLeft(node.left); - } else { - this._rotateRight(node); - } - } else if (balance < -1) { - if (node.right.getBalance() > 0) { - this._rotateRight(node.right); - } else { - this._rotateLeft(node); - } - } - }; - /** - * Get an event whose time and duration span the give time. Will - * return the match whose "time" value is closest to the given time. - * @param {Object} event The event to add to the timeline - * @return {Object} The event which spans the desired time - */ - Tone.IntervalTimeline.prototype.get = function (time) { - if (this._root !== null) { - var results = []; - this._root.search(time, results); - if (results.length > 0) { - var max = results[0]; - for (var i = 1; i < results.length; i++) { - if (results[i].low > max.low) { - max = results[i]; - } - } - return max.event; - } - } - return null; - }; - /** - * Iterate over everything in the timeline. - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.forEach = function (callback) { - if (this._root !== null) { - var allNodes = []; - if (this._root !== null) { - this._root.traverse(function (node) { - allNodes.push(node); - }); - } - for (var i = 0; i < allNodes.length; i++) { - var ev = allNodes[i].event; - if (ev) { - callback(ev); - } - } - } - return this; - }; - /** - * Iterate over everything in the array in which the given time - * overlaps with the time and duration time of the event. - * @param {Number} time The time to check if items are overlapping - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.forEachAtTime = function (time, callback) { - if (this._root !== null) { - var results = []; - this._root.search(time, results); - for (var i = results.length - 1; i >= 0; i--) { - var ev = results[i].event; - if (ev) { - callback(ev); - } - } - } - return this; - }; - /** - * Iterate over everything in the array in which the time is greater - * than the given time. - * @param {Number} time The time to check if items are before - * @param {Function} callback The callback to invoke with every item - * @returns {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.forEachAfter = function (time, callback) { - if (this._root !== null) { - var results = []; - this._root.searchAfter(time, results); - for (var i = results.length - 1; i >= 0; i--) { - var ev = results[i].event; - if (ev) { - callback(ev); - } - } - } - return this; - }; - /** - * Clean up - * @return {Tone.IntervalTimeline} this - */ - Tone.IntervalTimeline.prototype.dispose = function () { - var allNodes = []; - if (this._root !== null) { - this._root.traverse(function (node) { - allNodes.push(node); - }); - } - for (var i = 0; i < allNodes.length; i++) { - allNodes[i].dispose(); - } - allNodes = null; - this._root = null; - return this; - }; - /////////////////////////////////////////////////////////////////////////// - // INTERVAL NODE HELPER - /////////////////////////////////////////////////////////////////////////// - /** - * Represents a node in the binary search tree, with the addition - * of a "high" value which keeps track of the highest value of - * its children. - * References: - * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/ - * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf - * @param {Number} low - * @param {Number} high - * @private - */ - var IntervalNode = function (low, high, event) { - //the event container - this.event = event; - //the low value - this.low = low; - //the high value - this.high = high; - //the high value for this and all child nodes - this.max = this.high; - //the nodes to the left - this._left = null; - //the nodes to the right - this._right = null; - //the parent node - this.parent = null; - //the number of child nodes - this.height = 0; - }; - /** - * Insert a node into the correct spot in the tree - * @param {IntervalNode} node - */ - IntervalNode.prototype.insert = function (node) { - if (node.low <= this.low) { - if (this.left === null) { - this.left = node; - } else { - this.left.insert(node); - } - } else { - if (this.right === null) { - this.right = node; - } else { - this.right.insert(node); - } - } - }; - /** - * Search the tree for nodes which overlap - * with the given point - * @param {Number} point The point to query - * @param {Array} results The array to put the results - */ - IntervalNode.prototype.search = function (point, results) { - // If p is to the right of the rightmost point of any interval - // in this node and all children, there won't be any matches. - if (point > this.max) { - return; - } - // Search left children - if (this.left !== null) { - this.left.search(point, results); - } - // Check this node - if (this.low <= point && this.high > point) { - results.push(this); - } - // If p is to the left of the time of this interval, - // then it can't be in any child to the right. - if (this.low > point) { - return; - } - // Search right children - if (this.right !== null) { - this.right.search(point, results); - } - }; - /** - * Search the tree for nodes which are less - * than the given point - * @param {Number} point The point to query - * @param {Array} results The array to put the results - */ - IntervalNode.prototype.searchAfter = function (point, results) { - // Check this node - if (this.low >= point) { - results.push(this); - if (this.left !== null) { - this.left.searchAfter(point, results); - } - } - // search the right side - if (this.right !== null) { - this.right.searchAfter(point, results); - } - }; - /** - * Invoke the callback on this element and both it's branches - * @param {Function} callback - */ - IntervalNode.prototype.traverse = function (callback) { - callback(this); - if (this.left !== null) { - this.left.traverse(callback); - } - if (this.right !== null) { - this.right.traverse(callback); - } - }; - /** - * Update the height of the node - */ - IntervalNode.prototype.updateHeight = function () { - if (this.left !== null && this.right !== null) { - this.height = Math.max(this.left.height, this.right.height) + 1; - } else if (this.right !== null) { - this.height = this.right.height + 1; - } else if (this.left !== null) { - this.height = this.left.height + 1; - } else { - this.height = 0; - } - }; - /** - * Update the height of the node - */ - IntervalNode.prototype.updateMax = function () { - this.max = this.high; - if (this.left !== null) { - this.max = Math.max(this.max, this.left.max); - } - if (this.right !== null) { - this.max = Math.max(this.max, this.right.max); - } - }; - /** - * The balance is how the leafs are distributed on the node - * @return {Number} Negative numbers are balanced to the right - */ - IntervalNode.prototype.getBalance = function () { - var balance = 0; - if (this.left !== null && this.right !== null) { - balance = this.left.height - this.right.height; - } else if (this.left !== null) { - balance = this.left.height + 1; - } else if (this.right !== null) { - balance = -(this.right.height + 1); - } - return balance; - }; - /** - * @returns {Boolean} true if this node is the left child - * of its parent - */ - IntervalNode.prototype.isLeftChild = function () { - return this.parent !== null && this.parent.left === this; - }; - /** - * get/set the left node - * @type {IntervalNode} - */ - Object.defineProperty(IntervalNode.prototype, 'left', { - get: function () { - return this._left; - }, - set: function (node) { - this._left = node; - if (node !== null) { - node.parent = this; - } - this.updateHeight(); - this.updateMax(); - } - }); - /** - * get/set the right node - * @type {IntervalNode} - */ - Object.defineProperty(IntervalNode.prototype, 'right', { - get: function () { - return this._right; - }, - set: function (node) { - this._right = node; - if (node !== null) { - node.parent = this; - } - this.updateHeight(); - this.updateMax(); - } - }); - /** - * null out references. - */ - IntervalNode.prototype.dispose = function () { - this.parent = null; - this._left = null; - this._right = null; - this.event = null; - }; - /////////////////////////////////////////////////////////////////////////// - // END INTERVAL NODE HELPER - /////////////////////////////////////////////////////////////////////////// - return Tone.IntervalTimeline; - }); - Module(function (Tone) { - - /** - * @class Transport for timing musical events. - * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame) - * Tone.Transport timing events pass in the exact time of the scheduled event - * in the argument of the callback function. Pass that time value to the object - * you're scheduling.

- * A single transport is created for you when the library is initialized. - *

- * The transport emits the events: "start", "stop", "pause", and "loop" which are - * called with the time of that event as the argument. - * - * @extends {Tone.Emitter} - * @singleton - * @example - * //repeated event every 8th note - * Tone.Transport.scheduleRepeat(function(time){ - * //do something with the time - * }, "8n"); - * @example - * //schedule an event on the 16th measure - * Tone.Transport.schedule(function(time){ - * //do something with the time - * }, "16:0:0"); - */ - Tone.Transport = function () { - Tone.Emitter.call(this); - /////////////////////////////////////////////////////////////////////// - // LOOPING - ////////////////////////////////////////////////////////////////////// - /** - * If the transport loops or not. - * @type {boolean} - */ - this.loop = false; - /** - * The loop start position in ticks - * @type {Ticks} - * @private - */ - this._loopStart = 0; - /** - * The loop end position in ticks - * @type {Ticks} - * @private - */ - this._loopEnd = 0; - /////////////////////////////////////////////////////////////////////// - // CLOCK/TEMPO - ////////////////////////////////////////////////////////////////////// - /** - * Pulses per quarter is the number of ticks per quarter note. - * @private - * @type {Number} - */ - this._ppq = TransportConstructor.defaults.PPQ; - /** - * watches the main oscillator for timing ticks - * initially starts at 120bpm - * @private - * @type {Tone.Clock} - */ - this._clock = new Tone.Clock({ - 'callback': this._processTick.bind(this), - 'frequency': 0 - }); - this._bindClockEvents(); - /** - * The Beats Per Minute of the Transport. - * @type {BPM} - * @signal - * @example - * Tone.Transport.bpm.value = 80; - * //ramp the bpm to 120 over 10 seconds - * Tone.Transport.bpm.rampTo(120, 10); - */ - this.bpm = this._clock.frequency; - this.bpm._toUnits = this._toUnits.bind(this); - this.bpm._fromUnits = this._fromUnits.bind(this); - this.bpm.units = Tone.Type.BPM; - this.bpm.value = TransportConstructor.defaults.bpm; - this._readOnly('bpm'); - /** - * The time signature, or more accurately the numerator - * of the time signature over a denominator of 4. - * @type {Number} - * @private - */ - this._timeSignature = TransportConstructor.defaults.timeSignature; - /////////////////////////////////////////////////////////////////////// - // TIMELINE EVENTS - ////////////////////////////////////////////////////////////////////// - /** - * All the events in an object to keep track by ID - * @type {Object} - * @private - */ - this._scheduledEvents = {}; - /** - * The event ID counter - * @type {Number} - * @private - */ - this._eventID = 0; - /** - * The scheduled events. - * @type {Tone.Timeline} - * @private - */ - this._timeline = new Tone.Timeline(); - /** - * Repeated events - * @type {Array} - * @private - */ - this._repeatedEvents = new Tone.IntervalTimeline(); - /** - * Events that occur once - * @type {Array} - * @private - */ - this._onceEvents = new Tone.Timeline(); - /** - * All of the synced Signals - * @private - * @type {Array} - */ - this._syncedSignals = []; - /////////////////////////////////////////////////////////////////////// - // SWING - ////////////////////////////////////////////////////////////////////// - /** - * The subdivision of the swing - * @type {Ticks} - * @private - */ - this._swingTicks = TransportConstructor.defaults.PPQ / 2; - //8n - /** - * The swing amount - * @type {NormalRange} - * @private - */ - this._swingAmount = 0; - }; - Tone.extend(Tone.Transport, Tone.Emitter); - /** - * the defaults - * @type {Object} - * @const - * @static - */ - Tone.Transport.defaults = { - 'bpm': 120, - 'swing': 0, - 'swingSubdivision': '8n', - 'timeSignature': 4, - 'loopStart': 0, - 'loopEnd': '4m', - 'PPQ': 192 - }; - /////////////////////////////////////////////////////////////////////////////// - // TICKS - /////////////////////////////////////////////////////////////////////////////// - /** - * called on every tick - * @param {number} tickTime clock relative tick time - * @private - */ - Tone.Transport.prototype._processTick = function (tickTime) { - var ticks = this._clock.ticks; - //handle swing - if (this._swingAmount > 0 && ticks % this._ppq !== 0 && //not on a downbeat - ticks % (this._swingTicks * 2) !== 0) { - //add some swing - var progress = ticks % (this._swingTicks * 2) / (this._swingTicks * 2); - var amount = Math.sin(progress * Math.PI) * this._swingAmount; - tickTime += Tone.Time(this._swingTicks * 2 / 3, 'i') * amount; - } - //do the loop test - if (this.loop) { - if (ticks === this._loopEnd) { - this.emit('loopEnd', tickTime); - this._clock.ticks = this._loopStart; - ticks = this._loopStart; - this.emit('loopStart', tickTime, this.seconds); - this.emit('loop', tickTime); - } - } - //process the single occurrence events - this._onceEvents.forEachBefore(ticks, function (event) { - event.callback(tickTime); - //remove the event - delete this._scheduledEvents[event.id.toString()]; - }.bind(this)); - //and clear the single occurrence timeline - this._onceEvents.cancelBefore(ticks); - //fire the next tick events if their time has come - this._timeline.forEachAtTime(ticks, function (event) { - event.callback(tickTime); - }); - //process the repeated events - this._repeatedEvents.forEachAtTime(ticks, function (event) { - if ((ticks - event.time) % event.interval === 0) { - event.callback(tickTime); - } - }); - }; - /////////////////////////////////////////////////////////////////////////////// - // SCHEDULABLE EVENTS - /////////////////////////////////////////////////////////////////////////////// - /** - * Schedule an event along the timeline. - * @param {Function} callback The callback to be invoked at the time. - * @param {TransportTime} time The time to invoke the callback at. - * @return {Number} The id of the event which can be used for canceling the event. - * @example - * //trigger the callback when the Transport reaches the desired time - * Tone.Transport.schedule(function(time){ - * envelope.triggerAttack(time); - * }, "128i"); - */ - Tone.Transport.prototype.schedule = function (callback, time) { - var event = { - 'time': this.toTicks(time), - 'callback': callback - }; - var id = this._eventID++; - this._scheduledEvents[id.toString()] = { - 'event': event, - 'timeline': this._timeline - }; - this._timeline.add(event); - return id; - }; - /** - * Schedule a repeated event along the timeline. The event will fire - * at the `interval` starting at the `startTime` and for the specified - * `duration`. - * @param {Function} callback The callback to invoke. - * @param {Time} interval The duration between successive - * callbacks. - * @param {TimelinePosition=} startTime When along the timeline the events should - * start being invoked. - * @param {Time} [duration=Infinity] How long the event should repeat. - * @return {Number} The ID of the scheduled event. Use this to cancel - * the event. - * @example - * //a callback invoked every eighth note after the first measure - * Tone.Transport.scheduleRepeat(callback, "8n", "1m"); - */ - Tone.Transport.prototype.scheduleRepeat = function (callback, interval, startTime, duration) { - if (interval <= 0) { - throw new Error('Tone.Transport: repeat events must have an interval larger than 0'); - } - var event = { - 'time': this.toTicks(startTime), - 'duration': this.toTicks(this.defaultArg(duration, Infinity)), - 'interval': this.toTicks(interval), - 'callback': callback - }; - var id = this._eventID++; - this._scheduledEvents[id.toString()] = { - 'event': event, - 'timeline': this._repeatedEvents - }; - this._repeatedEvents.add(event); - return id; - }; - /** - * Schedule an event that will be removed after it is invoked. - * Note that if the given time is less than the current transport time, - * the event will be invoked immediately. - * @param {Function} callback The callback to invoke once. - * @param {TransportTime} time The time the callback should be invoked. - * @returns {Number} The ID of the scheduled event. - */ - Tone.Transport.prototype.scheduleOnce = function (callback, time) { - var id = this._eventID++; - var event = { - 'time': this.toTicks(time), - 'callback': callback, - 'id': id - }; - this._scheduledEvents[id.toString()] = { - 'event': event, - 'timeline': this._onceEvents - }; - this._onceEvents.add(event); - return id; - }; - /** - * Clear the passed in event id from the timeline - * @param {Number} eventId The id of the event. - * @returns {Tone.Transport} this - */ - Tone.Transport.prototype.clear = function (eventId) { - if (this._scheduledEvents.hasOwnProperty(eventId)) { - var item = this._scheduledEvents[eventId.toString()]; - item.timeline.remove(item.event); - delete this._scheduledEvents[eventId.toString()]; - } - return this; - }; - /** - * Remove scheduled events from the timeline after - * the given time. Repeated events will be removed - * if their startTime is after the given time - * @param {TransportTime} [after=0] Clear all events after - * this time. - * @returns {Tone.Transport} this - */ - Tone.Transport.prototype.cancel = function (after) { - after = this.defaultArg(after, 0); - after = this.toTicks(after); - this._timeline.cancel(after); - this._onceEvents.cancel(after); - this._repeatedEvents.cancel(after); - return this; - }; - /////////////////////////////////////////////////////////////////////////////// - // START/STOP/PAUSE - /////////////////////////////////////////////////////////////////////////////// - /** - * Bind start/stop/pause events from the clock and emit them. - */ - Tone.Transport.prototype._bindClockEvents = function () { - this._clock.on('start', function (time, offset) { - offset = Tone.Time(this._clock.ticks, 'i').toSeconds(); - this.emit('start', time, offset); - }.bind(this)); - this._clock.on('stop', function (time) { - this.emit('stop', time); - }.bind(this)); - this._clock.on('pause', function (time) { - this.emit('pause', time); - }.bind(this)); - }; - /** - * Returns the playback state of the source, either "started", "stopped", or "paused" - * @type {Tone.State} - * @readOnly - * @memberOf Tone.Transport# - * @name state - */ - Object.defineProperty(Tone.Transport.prototype, 'state', { - get: function () { - return this._clock.getStateAtTime(this.now()); - } - }); - /** - * Start the transport and all sources synced to the transport. - * @param {Time} [time=now] The time when the transport should start. - * @param {TransportTime=} offset The timeline offset to start the transport. - * @returns {Tone.Transport} this - * @example - * //start the transport in one second starting at beginning of the 5th measure. - * Tone.Transport.start("+1", "4:0:0"); - */ - Tone.Transport.prototype.start = function (time, offset) { - //start the clock - if (!this.isUndef(offset)) { - offset = this.toTicks(offset); - } - this._clock.start(time, offset); - return this; - }; - /** - * Stop the transport and all sources synced to the transport. - * @param {Time} [time=now] The time when the transport should stop. - * @returns {Tone.Transport} this - * @example - * Tone.Transport.stop(); - */ - Tone.Transport.prototype.stop = function (time) { - this._clock.stop(time); - return this; - }; - /** - * Pause the transport and all sources synced to the transport. - * @param {Time} [time=now] - * @returns {Tone.Transport} this - */ - Tone.Transport.prototype.pause = function (time) { - this._clock.pause(time); - return this; - }; - /////////////////////////////////////////////////////////////////////////////// - // SETTERS/GETTERS - /////////////////////////////////////////////////////////////////////////////// - /** - * The time signature as just the numerator over 4. - * For example 4/4 would be just 4 and 6/8 would be 3. - * @memberOf Tone.Transport# - * @type {Number|Array} - * @name timeSignature - * @example - * //common time - * Tone.Transport.timeSignature = 4; - * // 7/8 - * Tone.Transport.timeSignature = [7, 8]; - * //this will be reduced to a single number - * Tone.Transport.timeSignature; //returns 3.5 - */ - Object.defineProperty(Tone.Transport.prototype, 'timeSignature', { - get: function () { - return this._timeSignature; - }, - set: function (timeSig) { - if (this.isArray(timeSig)) { - timeSig = timeSig[0] / timeSig[1] * 4; - } - this._timeSignature = timeSig; - } - }); - /** - * When the Tone.Transport.loop = true, this is the starting position of the loop. - * @memberOf Tone.Transport# - * @type {TransportTime} - * @name loopStart - */ - Object.defineProperty(Tone.Transport.prototype, 'loopStart', { - get: function () { - return Tone.TransportTime(this._loopStart, 'i').toSeconds(); - }, - set: function (startPosition) { - this._loopStart = this.toTicks(startPosition); - } - }); - /** - * When the Tone.Transport.loop = true, this is the ending position of the loop. - * @memberOf Tone.Transport# - * @type {TransportTime} - * @name loopEnd - */ - Object.defineProperty(Tone.Transport.prototype, 'loopEnd', { - get: function () { - return Tone.TransportTime(this._loopEnd, 'i').toSeconds(); - }, - set: function (endPosition) { - this._loopEnd = this.toTicks(endPosition); - } - }); - /** - * Set the loop start and stop at the same time. - * @param {TransportTime} startPosition - * @param {TransportTime} endPosition - * @returns {Tone.Transport} this - * @example - * //loop over the first measure - * Tone.Transport.setLoopPoints(0, "1m"); - * Tone.Transport.loop = true; - */ - Tone.Transport.prototype.setLoopPoints = function (startPosition, endPosition) { - this.loopStart = startPosition; - this.loopEnd = endPosition; - return this; - }; - /** - * The swing value. Between 0-1 where 1 equal to - * the note + half the subdivision. - * @memberOf Tone.Transport# - * @type {NormalRange} - * @name swing - */ - Object.defineProperty(Tone.Transport.prototype, 'swing', { - get: function () { - return this._swingAmount; - }, - set: function (amount) { - //scale the values to a normal range - this._swingAmount = amount; - } - }); - /** - * Set the subdivision which the swing will be applied to. - * The default value is an 8th note. Value must be less - * than a quarter note. - * - * @memberOf Tone.Transport# - * @type {Time} - * @name swingSubdivision - */ - Object.defineProperty(Tone.Transport.prototype, 'swingSubdivision', { - get: function () { - return Tone.Time(this._swingTicks, 'i').toNotation(); - }, - set: function (subdivision) { - this._swingTicks = this.toTicks(subdivision); - } - }); - /** - * The Transport's position in Bars:Beats:Sixteenths. - * Setting the value will jump to that position right away. - * @memberOf Tone.Transport# - * @type {BarsBeatsSixteenths} - * @name position - */ - Object.defineProperty(Tone.Transport.prototype, 'position', { - get: function () { - return Tone.TransportTime(this.ticks, 'i').toBarsBeatsSixteenths(); - }, - set: function (progress) { - var ticks = this.toTicks(progress); - this.ticks = ticks; - } - }); - /** - * The Transport's position in seconds - * Setting the value will jump to that position right away. - * @memberOf Tone.Transport# - * @type {Seconds} - * @name seconds - */ - Object.defineProperty(Tone.Transport.prototype, 'seconds', { - get: function () { - return Tone.TransportTime(this.ticks, 'i').toSeconds(); - }, - set: function (progress) { - var ticks = this.toTicks(progress); - this.ticks = ticks; - } - }); - /** - * The Transport's loop position as a normalized value. Always - * returns 0 if the transport if loop is not true. - * @memberOf Tone.Transport# - * @name progress - * @type {NormalRange} - */ - Object.defineProperty(Tone.Transport.prototype, 'progress', { - get: function () { - if (this.loop) { - return (this.ticks - this._loopStart) / (this._loopEnd - this._loopStart); - } else { - return 0; - } - } - }); - /** - * The transports current tick position. - * - * @memberOf Tone.Transport# - * @type {Ticks} - * @name ticks - */ - Object.defineProperty(Tone.Transport.prototype, 'ticks', { - get: function () { - return this._clock.ticks; - }, - set: function (t) { - if (this._clock.ticks !== t) { - var now = this.now(); - //stop everything synced to the transport - if (this.state === Tone.State.Started) { - this.emit('stop', now); - this._clock.ticks = t; - //restart it with the new time - this.emit('start', now, this.seconds); - } else { - this._clock.ticks = t; - } - } - } - }); - /** - * Pulses Per Quarter note. This is the smallest resolution - * the Transport timing supports. This should be set once - * on initialization and not set again. Changing this value - * after other objects have been created can cause problems. - * - * @memberOf Tone.Transport# - * @type {Number} - * @name PPQ - */ - Object.defineProperty(Tone.Transport.prototype, 'PPQ', { - get: function () { - return this._ppq; - }, - set: function (ppq) { - var bpm = this.bpm.value; - this._ppq = ppq; - this.bpm.value = bpm; - } - }); - /** - * The hint to the type of playback. Affects tradeoffs between audio - * output latency and responsiveness. - * - * In addition to setting the value in seconds, the latencyHint also - * accepts the strings "interactive" (prioritizes low latency), - * "playback" (prioritizes sustained playback), "balanced" (balances - * latency and performance), and "fastest" (lowest latency, might glitch more often). - * @memberOf Tone.Transport# - * @type {Seconds|String} - * @name latencyHint - */ - Object.defineProperty(Tone.Transport.prototype, 'latencyHint', { - get: function () { - return Tone.Clock.latencyHint; - }, - set: function (hint) { - Tone.Clock.latencyHint = hint; - } - }); - /** - * Convert from BPM to frequency (factoring in PPQ) - * @param {BPM} bpm The BPM value to convert to frequency - * @return {Frequency} The BPM as a frequency with PPQ factored in. - * @private - */ - Tone.Transport.prototype._fromUnits = function (bpm) { - return 1 / (60 / bpm / this.PPQ); - }; - /** - * Convert from frequency (with PPQ) into BPM - * @param {Frequency} freq The clocks frequency to convert to BPM - * @return {BPM} The frequency value as BPM. - * @private - */ - Tone.Transport.prototype._toUnits = function (freq) { - return freq / this.PPQ * 60; - }; - /////////////////////////////////////////////////////////////////////////////// - // SYNCING - /////////////////////////////////////////////////////////////////////////////// - /** - * Returns the time aligned to the next subdivision - * of the Transport. If the Transport is not started, - * it will return 0. - * Note: this will not work precisely during tempo ramps. - * @param {Time} subdivision The subdivision to quantize to - * @return {Number} The context time of the next subdivision. - * @example - * Tone.Transport.start(); //the transport must be started - * Tone.Transport.nextSubdivision("4n"); - */ - Tone.Transport.prototype.nextSubdivision = function (subdivision) { - subdivision = this.toSeconds(subdivision); - //if the transport's not started, return 0 - var now; - if (this.state === Tone.State.Started) { - now = this._clock._nextTick; - } else { - return 0; - } - var transportPos = Tone.Time(this.ticks, 'i'); - var remainingTime = subdivision - transportPos % subdivision; - if (remainingTime === 0) { - remainingTime = subdivision; - } - return now + remainingTime; - }; - /** - * Attaches the signal to the tempo control signal so that - * any changes in the tempo will change the signal in the same - * ratio. - * - * @param {Tone.Signal} signal - * @param {number=} ratio Optionally pass in the ratio between - * the two signals. Otherwise it will be computed - * based on their current values. - * @returns {Tone.Transport} this - */ - Tone.Transport.prototype.syncSignal = function (signal, ratio) { - if (!ratio) { - //get the sync ratio - if (signal._param.value !== 0) { - ratio = signal._param.value / this.bpm._param.value; - } else { - ratio = 0; - } - } - var ratioSignal = new Tone.Gain(ratio); - this.bpm.chain(ratioSignal, signal._param); - this._syncedSignals.push({ - 'ratio': ratioSignal, - 'signal': signal, - 'initial': signal._param.value - }); - signal._param.value = 0; - return this; - }; - /** - * Unsyncs a previously synced signal from the transport's control. - * See Tone.Transport.syncSignal. - * @param {Tone.Signal} signal - * @returns {Tone.Transport} this - */ - Tone.Transport.prototype.unsyncSignal = function (signal) { - for (var i = this._syncedSignals.length - 1; i >= 0; i--) { - var syncedSignal = this._syncedSignals[i]; - if (syncedSignal.signal === signal) { - syncedSignal.ratio.dispose(); - syncedSignal.signal._param.value = syncedSignal.initial; - this._syncedSignals.splice(i, 1); - } - } - return this; - }; - /** - * Clean up. - * @returns {Tone.Transport} this - * @private - */ - Tone.Transport.prototype.dispose = function () { - Tone.Emitter.prototype.dispose.call(this); - this._clock.dispose(); - this._clock = null; - this._writable('bpm'); - this.bpm = null; - this._timeline.dispose(); - this._timeline = null; - this._onceEvents.dispose(); - this._onceEvents = null; - this._repeatedEvents.dispose(); - this._repeatedEvents = null; - return this; - }; - /////////////////////////////////////////////////////////////////////////////// - // INITIALIZATION - /////////////////////////////////////////////////////////////////////////////// - var TransportConstructor = Tone.Transport; - Tone.Transport = new TransportConstructor(); - Tone.Context.on('init', function (context) { - if (context.Transport instanceof TransportConstructor) { - Tone.Transport = context.Transport; - } else { - Tone.Transport = new TransportConstructor(); - //store the Transport on the context so it can be retrieved later - context.Transport = Tone.Transport; - } - }); - return Tone.Transport; - }); - Module(function (Tone) { - - /** - * @class Tone.Volume is a simple volume node, useful for creating a volume fader. - * - * @extends {Tone} - * @constructor - * @param {Decibels} [volume=0] the initial volume - * @example - * var vol = new Tone.Volume(-12); - * instrument.chain(vol, Tone.Master); - */ - Tone.Volume = function () { - var options = this.optionsObject(arguments, ['volume'], Tone.Volume.defaults); - /** - * the output node - * @type {GainNode} - * @private - */ - this.output = this.input = new Tone.Gain(options.volume, Tone.Type.Decibels); - /** - * The unmuted volume - * @type {Decibels} - * @private - */ - this._unmutedVolume = options.volume; - /** - * The volume control in decibels. - * @type {Decibels} - * @signal - */ - this.volume = this.output.gain; - this._readOnly('volume'); - //set the mute initially - this.mute = options.mute; - }; - Tone.extend(Tone.Volume); - /** - * Defaults - * @type {Object} - * @const - * @static - */ - Tone.Volume.defaults = { - 'volume': 0, - 'mute': false - }; - /** - * Mute the output. - * @memberOf Tone.Volume# - * @type {boolean} - * @name mute - * @example - * //mute the output - * volume.mute = true; - */ - Object.defineProperty(Tone.Volume.prototype, 'mute', { - get: function () { - return this.volume.value === -Infinity; - }, - set: function (mute) { - if (!this.mute && mute) { - this._unmutedVolume = this.volume.value; - //maybe it should ramp here? - this.volume.value = -Infinity; - } else if (this.mute && !mute) { - this.volume.value = this._unmutedVolume; - } - } - }); - /** - * clean up - * @returns {Tone.Volume} this - */ - Tone.Volume.prototype.dispose = function () { - this.input.dispose(); - Tone.prototype.dispose.call(this); - this._writable('volume'); - this.volume.dispose(); - this.volume = null; - return this; - }; - return Tone.Volume; - }); - Module(function (Tone) { - - /** - * @class A single master output which is connected to the - * AudioDestinationNode (aka your speakers). - * It provides useful conveniences such as the ability - * to set the volume and mute the entire application. - * It also gives you the ability to apply master effects to your application. - *

- * Like Tone.Transport, A single Tone.Master is created - * on initialization and you do not need to explicitly construct one. - * - * @constructor - * @extends {Tone} - * @singleton - * @example - * //the audio will go from the oscillator to the speakers - * oscillator.connect(Tone.Master); - * //a convenience for connecting to the master output is also provided: - * oscillator.toMaster(); - * //the above two examples are equivalent. - */ - Tone.Master = function () { - this.createInsOuts(1, 1); - /** - * The private volume node - * @type {Tone.Volume} - * @private - */ - this._volume = this.output = new Tone.Volume(); - /** - * The volume of the master output. - * @type {Decibels} - * @signal - */ - this.volume = this._volume.volume; - this._readOnly('volume'); - //connections - this.input.chain(this.output, this.context.destination); - }; - Tone.extend(Tone.Master); - /** - * @type {Object} - * @const - */ - Tone.Master.defaults = { - 'volume': 0, - 'mute': false - }; - /** - * Mute the output. - * @memberOf Tone.Master# - * @type {boolean} - * @name mute - * @example - * //mute the output - * Tone.Master.mute = true; - */ - Object.defineProperty(Tone.Master.prototype, 'mute', { - get: function () { - return this._volume.mute; - }, - set: function (mute) { - this._volume.mute = mute; - } - }); - /** - * Add a master effects chain. NOTE: this will disconnect any nodes which were previously - * chained in the master effects chain. - * @param {AudioNode|Tone...} args All arguments will be connected in a row - * and the Master will be routed through it. - * @return {Tone.Master} this - * @example - * //some overall compression to keep the levels in check - * var masterCompressor = new Tone.Compressor({ - * "threshold" : -6, - * "ratio" : 3, - * "attack" : 0.5, - * "release" : 0.1 - * }); - * //give a little boost to the lows - * var lowBump = new Tone.Filter(200, "lowshelf"); - * //route everything through the filter - * //and compressor before going to the speakers - * Tone.Master.chain(lowBump, masterCompressor); - */ - Tone.Master.prototype.chain = function () { - this.input.disconnect(); - this.input.chain.apply(this.input, arguments); - arguments[arguments.length - 1].connect(this.output); - }; - /** - * Clean up - * @return {Tone.Master} this - */ - Tone.Master.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable('volume'); - this._volume.dispose(); - this._volume = null; - this.volume = null; - }; - /////////////////////////////////////////////////////////////////////////// - // AUGMENT TONE's PROTOTYPE - /////////////////////////////////////////////////////////////////////////// - /** - * Connect 'this' to the master output. Shorthand for this.connect(Tone.Master) - * @returns {Tone} this - * @example - * //connect an oscillator to the master output - * var osc = new Tone.Oscillator().toMaster(); - */ - Tone.prototype.toMaster = function () { - this.connect(Tone.Master); - return this; - }; - /** - * Also augment AudioNode's prototype to include toMaster - * as a convenience - * @returns {AudioNode} this - */ - AudioNode.prototype.toMaster = function () { - this.connect(Tone.Master); - return this; - }; - /** - * initialize the module and listen for new audio contexts - */ - var MasterConstructor = Tone.Master; - Tone.Master = new MasterConstructor(); - Tone.Context.on('init', function (context) { - // if it already exists, just restore it - if (context.Master instanceof MasterConstructor) { - Tone.Master = context.Master; - } else { - Tone.Master = new MasterConstructor(); - } - context.Master = Tone.Master; - }); - return Tone.Master; - }); - Module(function (Tone) { - - /** - * @class Base class for sources. Sources have start/stop methods - * and the ability to be synced to the - * start/stop of Tone.Transport. - * - * @constructor - * @extends {Tone} - * @example - * //Multiple state change events can be chained together, - * //but must be set in the correct order and with ascending times - * - * // OK - * state.start().stop("+0.2"); - * // AND - * state.start().stop("+0.2").start("+0.4").stop("+0.7") - * - * // BAD - * state.stop("+0.2").start(); - * // OR - * state.start("+0.3").stop("+0.2"); - * - */ - Tone.Source = function (options) { - // this.createInsOuts(0, 1); - options = this.defaultArg(options, Tone.Source.defaults); - /** - * The output volume node - * @type {Tone.Volume} - * @private - */ - this._volume = this.output = new Tone.Volume(options.volume); - /** - * The volume of the output in decibels. - * @type {Decibels} - * @signal - * @example - * source.volume.value = -6; - */ - this.volume = this._volume.volume; - this._readOnly('volume'); - /** - * Keep track of the scheduled state. - * @type {Tone.TimelineState} - * @private - */ - this._state = new Tone.TimelineState(Tone.State.Stopped); - this._state.memory = 10; - /** - * The synced `start` callback function from the transport - * @type {Function} - * @private - */ - this._synced = false; - /** - * Keep track of all of the scheduled event ids - * @type {Array} - * @private - */ - this._scheduled = []; - //make the output explicitly stereo - this._volume.output.output.channelCount = 2; - this._volume.output.output.channelCountMode = 'explicit'; - //mute initially - this.mute = options.mute; - }; - Tone.extend(Tone.Source); - /** - * The default parameters - * @static - * @const - * @type {Object} - */ - Tone.Source.defaults = { - 'volume': 0, - 'mute': false - }; - /** - * Returns the playback state of the source, either "started" or "stopped". - * @type {Tone.State} - * @readOnly - * @memberOf Tone.Source# - * @name state - */ - Object.defineProperty(Tone.Source.prototype, 'state', { - get: function () { - if (this._synced) { - if (Tone.Transport.state === Tone.State.Started) { - return this._state.getValueAtTime(Tone.Transport.seconds); - } else { - return Tone.State.Stopped; - } - } else { - return this._state.getValueAtTime(this.now()); - } - } - }); - /** - * Mute the output. - * @memberOf Tone.Source# - * @type {boolean} - * @name mute - * @example - * //mute the output - * source.mute = true; - */ - Object.defineProperty(Tone.Source.prototype, 'mute', { - get: function () { - return this._volume.mute; - }, - set: function (mute) { - this._volume.mute = mute; - } - }); - //overwrite these functions - Tone.Source.prototype._start = Tone.noOp; - Tone.Source.prototype._stop = Tone.noOp; - /** - * Start the source at the specified time. If no time is given, - * start the source now. - * @param {Time} [time=now] When the source should be started. - * @returns {Tone.Source} this - * @example - * source.start("+0.5"); //starts the source 0.5 seconds from now - */ - Tone.Source.prototype.start = function (time, offset, duration) { - if (this.isUndef(time) && this._synced) { - time = Tone.Transport.seconds; - } else { - time = this.toSeconds(time); - } - //if it's started, stop it and restart it - if (!this.retrigger && this._state.getValueAtTime(time) === Tone.State.Started) { - this.stop(time); - } - this._state.setStateAtTime(Tone.State.Started, time); - if (this._synced) { - // add the offset time to the event - var event = this._state.get(time); - event.offset = this.defaultArg(offset, 0); - event.duration = duration; - var sched = Tone.Transport.schedule(function (t) { - this._start(t, offset, duration); - }.bind(this), time); - this._scheduled.push(sched); - } else { - this._start.apply(this, arguments); - } - return this; - }; - /** - * Stop the source at the specified time. If no time is given, - * stop the source now. - * @param {Time} [time=now] When the source should be stopped. - * @returns {Tone.Source} this - * @example - * source.stop(); // stops the source immediately - */ - Tone.Source.prototype.stop = function (time) { - if (this.isUndef(time) && this._synced) { - time = Tone.Transport.seconds; - } else { - time = this.toSeconds(time); - } - this._state.cancel(time); - this._state.setStateAtTime(Tone.State.Stopped, time); - if (!this._synced) { - this._stop.apply(this, arguments); - } else { - var sched = Tone.Transport.schedule(this._stop.bind(this), time); - this._scheduled.push(sched); - } - return this; - }; - /** - * Sync the source to the Transport so that all subsequent - * calls to `start` and `stop` are synced to the TransportTime - * instead of the AudioContext time. - * - * @returns {Tone.Source} this - * @example - * //sync the source so that it plays between 0 and 0.3 on the Transport's timeline - * source.sync().start(0).stop(0.3); - * //start the transport. - * Tone.Transport.start(); - * - * @example - * //start the transport with an offset and the sync'ed sources - * //will start in the correct position - * source.sync().start(0.1); - * //the source will be invoked with an offset of 0.4 - * Tone.Transport.start("+0.5", 0.5); - */ - Tone.Source.prototype.sync = function () { - this._synced = true; - Tone.Transport.on('start loopStart', function (time, offset) { - if (offset > 0) { - // get the playback state at that time - var stateEvent = this._state.get(offset); - // listen for start events which may occur in the middle of the sync'ed time - if (stateEvent && stateEvent.state === Tone.State.Started && stateEvent.time !== offset) { - // get the offset - var startOffset = offset - this.toSeconds(stateEvent.time); - var duration; - if (stateEvent.duration) { - duration = this.toSeconds(stateEvent.duration) - startOffset; - } - this._start(time, this.toSeconds(stateEvent.offset) + startOffset, duration); - } - } - }.bind(this)); - Tone.Transport.on('stop pause loopEnd', function (time) { - if (this._state.getValueAtTime(Tone.Transport.seconds) === Tone.State.Started) { - this._stop(time); - } - }.bind(this)); - return this; - }; - /** - * Unsync the source to the Transport. See Tone.Source.sync - * @returns {Tone.Source} this - */ - Tone.Source.prototype.unsync = function () { - this._synced = false; - Tone.Transport.off('start stop pause loopEnd loopStart'); - // clear all of the scheduled ids - for (var i = 0; i < this._scheduled.length; i++) { - var id = this._scheduled[i]; - Tone.Transport.clear(id); - } - this._scheduled = []; - this._state.cancel(0); - return this; - }; - /** - * Clean up. - * @return {Tone.Source} this - */ - Tone.Source.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this.unsync(); - this._scheduled = null; - this._writable('volume'); - this._volume.dispose(); - this._volume = null; - this.volume = null; - this._state.dispose(); - this._state = null; - }; - return Tone.Source; - }); - Module(function (Tone) { - - /** - * OscillatorNode shim - * @private - */ - if (window.OscillatorNode && !OscillatorNode.prototype.start) { - OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; - OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; - if (!OscillatorNode.prototype.setPeriodicWave) { - OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; - } - if (!AudioContext.prototype.createPeriodicWave) { - AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; - } - } - /** - * @class Tone.Oscillator supports a number of features including - * phase rotation, multiple oscillator types (see Tone.Oscillator.type), - * and Transport syncing (see Tone.Oscillator.syncFrequency). - * - * @constructor - * @extends {Tone.Source} - * @param {Frequency} [frequency] Starting frequency - * @param {string} [type] The oscillator type. Read more about type below. - * @example - * //make and start a 440hz sine tone - * var osc = new Tone.Oscillator(440, "sine").toMaster().start(); - */ - Tone.Oscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'type' - ], Tone.Oscillator.defaults); - Tone.Source.call(this, options); - /** - * the main oscillator - * @type {OscillatorNode} - * @private - */ - this._oscillator = null; - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The detune control signal. - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - /** - * the periodic wave - * @type {PeriodicWave} - * @private - */ - this._wave = null; - /** - * The partials of the oscillator - * @type {Array} - * @private - */ - this._partials = this.defaultArg(options.partials, [1]); - /** - * the phase of the oscillator - * between 0 - 360 - * @type {number} - * @private - */ - this._phase = options.phase; - /** - * the type of the oscillator - * @type {string} - * @private - */ - this._type = null; - //setup - this.type = options.type; - this.phase = this._phase; - this._readOnly([ - 'frequency', - 'detune' - ]); - }; - Tone.extend(Tone.Oscillator, Tone.Source); - /** - * the default parameters - * @type {Object} - */ - Tone.Oscillator.defaults = { - 'type': 'sine', - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'partials': [] - }; - /** - * The Oscillator types - * @enum {String} - */ - Tone.Oscillator.Type = { - Sine: 'sine', - Triangle: 'triangle', - Sawtooth: 'sawtooth', - Square: 'square', - Custom: 'custom' - }; - /** - * start the oscillator - * @param {Time} [time=now] - * @private - */ - Tone.Oscillator.prototype._start = function (time) { - //new oscillator with previous values - this._oscillator = this.context.createOscillator(); - this._oscillator.setPeriodicWave(this._wave); - //connect the control signal to the oscillator frequency & detune - this._oscillator.connect(this.output); - this.frequency.connect(this._oscillator.frequency); - this.detune.connect(this._oscillator.detune); - //start the oscillator - this._oscillator.start(this.toSeconds(time)); - }; - /** - * stop the oscillator - * @private - * @param {Time} [time=now] (optional) timing parameter - * @returns {Tone.Oscillator} this - */ - Tone.Oscillator.prototype._stop = function (time) { - if (this._oscillator) { - this._oscillator.stop(this.toSeconds(time)); - this._oscillator = null; - } - return this; - }; - /** - * Sync the signal to the Transport's bpm. Any changes to the transports bpm, - * will also affect the oscillators frequency. - * @returns {Tone.Oscillator} this - * @example - * Tone.Transport.bpm.value = 120; - * osc.frequency.value = 440; - * //the ration between the bpm and the frequency will be maintained - * osc.syncFrequency(); - * Tone.Transport.bpm.value = 240; - * // the frequency of the oscillator is doubled to 880 - */ - Tone.Oscillator.prototype.syncFrequency = function () { - Tone.Transport.syncSignal(this.frequency); - return this; - }; - /** - * Unsync the oscillator's frequency from the Transport. - * See Tone.Oscillator.syncFrequency - * @returns {Tone.Oscillator} this - */ - Tone.Oscillator.prototype.unsyncFrequency = function () { - Tone.Transport.unsyncSignal(this.frequency); - return this; - }; - /** - * The type of the oscillator: either sine, square, triangle, or sawtooth. Also capable of - * setting the first x number of partials of the oscillator. For example: "sine4" would - * set be the first 4 partials of the sine wave and "triangle8" would set the first - * 8 partials of the triangle wave. - *

- * Uses PeriodicWave internally even for native types so that it can set the phase. - * PeriodicWave equations are from the - * [Webkit Web Audio implementation](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium). - * - * @memberOf Tone.Oscillator# - * @type {string} - * @name type - * @example - * //set it to a square wave - * osc.type = "square"; - * @example - * //set the first 6 partials of a sawtooth wave - * osc.type = "sawtooth6"; - */ - Object.defineProperty(Tone.Oscillator.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - var coefs = this._getRealImaginary(type, this._phase); - var periodicWave = this.context.createPeriodicWave(coefs[0], coefs[1]); - this._wave = periodicWave; - if (this._oscillator !== null) { - this._oscillator.setPeriodicWave(this._wave); - } - this._type = type; - } - }); - /** - * Returns the real and imaginary components based - * on the oscillator type. - * @returns {Array} [real, imaginary] - * @private - */ - Tone.Oscillator.prototype._getRealImaginary = function (type, phase) { - var fftSize = 4096; - var periodicWaveSize = fftSize / 2; - var real = new Float32Array(periodicWaveSize); - var imag = new Float32Array(periodicWaveSize); - var partialCount = 1; - if (type === Tone.Oscillator.Type.Custom) { - partialCount = this._partials.length + 1; - periodicWaveSize = partialCount; - } else { - var partial = /^(sine|triangle|square|sawtooth)(\d+)$/.exec(type); - if (partial) { - partialCount = parseInt(partial[2]) + 1; - type = partial[1]; - partialCount = Math.max(partialCount, 2); - periodicWaveSize = partialCount; - } - } - for (var n = 1; n < periodicWaveSize; ++n) { - var piFactor = 2 / (n * Math.PI); - var b; - switch (type) { - case Tone.Oscillator.Type.Sine: - b = n <= partialCount ? 1 : 0; - break; - case Tone.Oscillator.Type.Square: - b = n & 1 ? 2 * piFactor : 0; - break; - case Tone.Oscillator.Type.Sawtooth: - b = piFactor * (n & 1 ? 1 : -1); - break; - case Tone.Oscillator.Type.Triangle: - if (n & 1) { - b = 2 * (piFactor * piFactor) * (n - 1 >> 1 & 1 ? -1 : 1); - } else { - b = 0; - } - break; - case Tone.Oscillator.Type.Custom: - b = this._partials[n - 1]; - break; - default: - throw new TypeError('Tone.Oscillator: invalid type: ' + type); - } - if (b !== 0) { - real[n] = -b * Math.sin(phase * n); - imag[n] = b * Math.cos(phase * n); - } else { - real[n] = 0; - imag[n] = 0; - } - } - return [ - real, - imag - ]; - }; - /** - * Compute the inverse FFT for a given phase. - * @param {Float32Array} real - * @param {Float32Array} imag - * @param {NormalRange} phase - * @return {AudioRange} - * @private - */ - Tone.Oscillator.prototype._inverseFFT = function (real, imag, phase) { - var sum = 0; - var len = real.length; - for (var i = 0; i < len; i++) { - sum += real[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase); - } - return sum; - }; - /** - * Returns the initial value of the oscillator. - * @return {AudioRange} - * @private - */ - Tone.Oscillator.prototype._getInitialValue = function () { - var coefs = this._getRealImaginary(this._type, 0); - var real = coefs[0]; - var imag = coefs[1]; - var maxValue = 0; - var twoPi = Math.PI * 2; - //check for peaks in 8 places - for (var i = 0; i < 8; i++) { - maxValue = Math.max(this._inverseFFT(real, imag, i / 8 * twoPi), maxValue); - } - return -this._inverseFFT(real, imag, this._phase) / maxValue; - }; - /** - * The partials of the waveform. A partial represents - * the amplitude at a harmonic. The first harmonic is the - * fundamental frequency, the second is the octave and so on - * following the harmonic series. - * Setting this value will automatically set the type to "custom". - * The value is an empty array when the type is not "custom". - * @memberOf Tone.Oscillator# - * @type {Array} - * @name partials - * @example - * osc.partials = [1, 0.2, 0.01]; - */ - Object.defineProperty(Tone.Oscillator.prototype, 'partials', { - get: function () { - if (this._type !== Tone.Oscillator.Type.Custom) { - return []; - } else { - return this._partials; - } - }, - set: function (partials) { - this._partials = partials; - this.type = Tone.Oscillator.Type.Custom; - } - }); - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.Oscillator# - * @type {Degrees} - * @name phase - * @example - * osc.phase = 180; //flips the phase of the oscillator - */ - Object.defineProperty(Tone.Oscillator.prototype, 'phase', { - get: function () { - return this._phase * (180 / Math.PI); - }, - set: function (phase) { - this._phase = phase * Math.PI / 180; - //reset the type - this.type = this._type; - } - }); - /** - * Dispose and disconnect. - * @return {Tone.Oscillator} this - */ - Tone.Oscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - if (this._oscillator !== null) { - this._oscillator.disconnect(); - this._oscillator = null; - } - this._wave = null; - this._writable([ - 'frequency', - 'detune' - ]); - this.frequency.dispose(); - this.frequency = null; - this.detune.dispose(); - this.detune = null; - this._partials = null; - return this; - }; - return Tone.Oscillator; - }); - Module(function (Tone) { - /** - * @class Tone.Zero outputs 0's at audio-rate. The reason this has to be - * it's own class is that many browsers optimize out Tone.Signal - * with a value of 0 and will not process nodes further down the graph. - * @extends {Tone} - */ - Tone.Zero = function () { - /** - * The gain node - * @type {Tone.Gain} - * @private - */ - this._gain = this.input = this.output = new Tone.Gain(); - this.context.getConstant(0).connect(this._gain); - }; - Tone.extend(Tone.Zero); - /** - * clean up - * @return {Tone.Zero} this - */ - Tone.Zero.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._gain.dispose(); - this._gain = null; - return this; - }; - return Tone.Zero; - }); - Module(function (Tone) { - - /** - * @class LFO stands for low frequency oscillator. Tone.LFO produces an output signal - * which can be attached to an AudioParam or Tone.Signal - * in order to modulate that parameter with an oscillator. The LFO can - * also be synced to the transport to start/stop and change when the tempo changes. - * - * @constructor - * @extends {Tone.Oscillator} - * @param {Frequency|Object} [frequency] The frequency of the oscillation. Typically, LFOs will be - * in the frequency range of 0.1 to 10 hertz. - * @param {number=} min The minimum output value of the LFO. - * @param {number=} max The maximum value of the LFO. - * @example - * var lfo = new Tone.LFO("4n", 400, 4000); - * lfo.connect(filter.frequency); - */ - Tone.LFO = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'min', - 'max' - ], Tone.LFO.defaults); - /** - * The oscillator. - * @type {Tone.Oscillator} - * @private - */ - this._oscillator = new Tone.Oscillator({ - 'frequency': options.frequency, - 'type': options.type - }); - /** - * the lfo's frequency - * @type {Frequency} - * @signal - */ - this.frequency = this._oscillator.frequency; - /** - * The amplitude of the LFO, which controls the output range between - * the min and max output. For example if the min is -10 and the max - * is 10, setting the amplitude to 0.5 would make the LFO modulate - * between -5 and 5. - * @type {Number} - * @signal - */ - this.amplitude = this._oscillator.volume; - this.amplitude.units = Tone.Type.NormalRange; - this.amplitude.value = options.amplitude; - /** - * The signal which is output when the LFO is stopped - * @type {Tone.Signal} - * @private - */ - this._stoppedSignal = new Tone.Signal(0, Tone.Type.AudioRange); - /** - * Just outputs zeros. - * @type {Tone.Zero} - * @private - */ - this._zeros = new Tone.Zero(); - /** - * The value that the LFO outputs when it's stopped - * @type {AudioRange} - * @private - */ - this._stoppedValue = 0; - /** - * @type {Tone.AudioToGain} - * @private - */ - this._a2g = new Tone.AudioToGain(); - /** - * @type {Tone.Scale} - * @private - */ - this._scaler = this.output = new Tone.Scale(options.min, options.max); - /** - * the units of the LFO (used for converting) - * @type {Tone.Type} - * @private - */ - this._units = Tone.Type.Default; - this.units = options.units; - //connect it up - this._oscillator.chain(this._a2g, this._scaler); - this._zeros.connect(this._a2g); - this._stoppedSignal.connect(this._a2g); - this._readOnly([ - 'amplitude', - 'frequency' - ]); - this.phase = options.phase; - }; - Tone.extend(Tone.LFO, Tone.Oscillator); - /** - * the default parameters - * - * @static - * @const - * @type {Object} - */ - Tone.LFO.defaults = { - 'type': 'sine', - 'min': 0, - 'max': 1, - 'phase': 0, - 'frequency': '4n', - 'amplitude': 1, - 'units': Tone.Type.Default - }; - /** - * Start the LFO. - * @param {Time} [time=now] the time the LFO will start - * @returns {Tone.LFO} this - */ - Tone.LFO.prototype.start = function (time) { - time = this.toSeconds(time); - this._stoppedSignal.setValueAtTime(0, time); - this._oscillator.start(time); - return this; - }; - /** - * Stop the LFO. - * @param {Time} [time=now] the time the LFO will stop - * @returns {Tone.LFO} this - */ - Tone.LFO.prototype.stop = function (time) { - time = this.toSeconds(time); - this._stoppedSignal.setValueAtTime(this._stoppedValue, time); - this._oscillator.stop(time); - return this; - }; - /** - * Sync the start/stop/pause to the transport - * and the frequency to the bpm of the transport - * @returns {Tone.LFO} this - * @example - * lfo.frequency.value = "8n"; - * lfo.sync().start(0) - * //the rate of the LFO will always be an eighth note, - * //even as the tempo changes - */ - Tone.LFO.prototype.sync = function () { - this._oscillator.sync(); - this._oscillator.syncFrequency(); - return this; - }; - /** - * unsync the LFO from transport control - * @returns {Tone.LFO} this - */ - Tone.LFO.prototype.unsync = function () { - this._oscillator.unsync(); - this._oscillator.unsyncFrequency(); - return this; - }; - /** - * The miniumum output of the LFO. - * @memberOf Tone.LFO# - * @type {number} - * @name min - */ - Object.defineProperty(Tone.LFO.prototype, 'min', { - get: function () { - return this._toUnits(this._scaler.min); - }, - set: function (min) { - min = this._fromUnits(min); - this._scaler.min = min; - } - }); - /** - * The maximum output of the LFO. - * @memberOf Tone.LFO# - * @type {number} - * @name max - */ - Object.defineProperty(Tone.LFO.prototype, 'max', { - get: function () { - return this._toUnits(this._scaler.max); - }, - set: function (max) { - max = this._fromUnits(max); - this._scaler.max = max; - } - }); - /** - * The type of the oscillator: sine, square, sawtooth, triangle. - * @memberOf Tone.LFO# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.LFO.prototype, 'type', { - get: function () { - return this._oscillator.type; - }, - set: function (type) { - this._oscillator.type = type; - this._stoppedValue = this._oscillator._getInitialValue(); - this._stoppedSignal.value = this._stoppedValue; - } - }); - /** - * The phase of the LFO. - * @memberOf Tone.LFO# - * @type {number} - * @name phase - */ - Object.defineProperty(Tone.LFO.prototype, 'phase', { - get: function () { - return this._oscillator.phase; - }, - set: function (phase) { - this._oscillator.phase = phase; - this._stoppedValue = this._oscillator._getInitialValue(); - this._stoppedSignal.value = this._stoppedValue; - } - }); - /** - * The output units of the LFO. - * @memberOf Tone.LFO# - * @type {Tone.Type} - * @name units - */ - Object.defineProperty(Tone.LFO.prototype, 'units', { - get: function () { - return this._units; - }, - set: function (val) { - var currentMin = this.min; - var currentMax = this.max; - //convert the min and the max - this._units = val; - this.min = currentMin; - this.max = currentMax; - } - }); - /** - * Mute the output. - * @memberOf Tone.LFO# - * @type {Boolean} - * @name mute - */ - Object.defineProperty(Tone.LFO.prototype, 'mute', { - get: function () { - return this._oscillator.mute; - }, - set: function (mute) { - this._oscillator.mute = mute; - } - }); - /** - * Returns the playback state of the source, either "started" or "stopped". - * @type {Tone.State} - * @readOnly - * @memberOf Tone.LFO# - * @name state - */ - Object.defineProperty(Tone.LFO.prototype, 'state', { - get: function () { - return this._oscillator.state; - } - }); - /** - * Connect the output of the LFO to an AudioParam, AudioNode, or Tone Node. - * Tone.LFO will automatically convert to the destination units of the - * will get the units from the connected node. - * @param {Tone | AudioParam | AudioNode} node - * @param {number} [outputNum=0] optionally which output to connect from - * @param {number} [inputNum=0] optionally which input to connect to - * @returns {Tone.LFO} this - * @private - */ - Tone.LFO.prototype.connect = function (node) { - if (node.constructor === Tone.Signal || node.constructor === Tone.Param || node.constructor === Tone.TimelineSignal) { - this.convert = node.convert; - this.units = node.units; - } - Tone.Signal.prototype.connect.apply(this, arguments); - return this; - }; - /** - * private method borrowed from Param converts - * units from their destination value - * @function - * @private - */ - Tone.LFO.prototype._fromUnits = Tone.Param.prototype._fromUnits; - /** - * private method borrowed from Param converts - * units to their destination value - * @function - * @private - */ - Tone.LFO.prototype._toUnits = Tone.Param.prototype._toUnits; - /** - * disconnect and dispose - * @returns {Tone.LFO} this - */ - Tone.LFO.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'amplitude', - 'frequency' - ]); - this._oscillator.dispose(); - this._oscillator = null; - this._stoppedSignal.dispose(); - this._stoppedSignal = null; - this._zeros.dispose(); - this._zeros = null; - this._scaler.dispose(); - this._scaler = null; - this._a2g.dispose(); - this._a2g = null; - this.frequency = null; - this.amplitude = null; - return this; - }; - return Tone.LFO; - }); - Module(function (Tone) { - - /** - * @class Tone.Limiter will limit the loudness of an incoming signal. - * It is composed of a Tone.Compressor with a fast attack - * and release. Limiters are commonly used to safeguard against - * signal clipping. Unlike a compressor, limiters do not provide - * smooth gain reduction and almost completely prevent - * additional gain above the threshold. - * - * @extends {Tone} - * @constructor - * @param {number} threshold The theshold above which the limiting is applied. - * @example - * var limiter = new Tone.Limiter(-6); - */ - Tone.Limiter = function () { - var options = this.optionsObject(arguments, ['threshold'], Tone.Limiter.defaults); - /** - * the compressor - * @private - * @type {Tone.Compressor} - */ - this._compressor = this.input = this.output = new Tone.Compressor({ - 'attack': 0.001, - 'decay': 0.001, - 'threshold': options.threshold - }); - /** - * The threshold of of the limiter - * @type {Decibel} - * @signal - */ - this.threshold = this._compressor.threshold; - this._readOnly('threshold'); - }; - Tone.extend(Tone.Limiter); - /** - * The default value - * @type {Object} - * @const - * @static - */ - Tone.Limiter.defaults = { 'threshold': -12 }; - /** - * Clean up. - * @returns {Tone.Limiter} this - */ - Tone.Limiter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._compressor.dispose(); - this._compressor = null; - this._writable('threshold'); - this.threshold = null; - return this; - }; - return Tone.Limiter; - }); - Module(function (Tone) { - - /** - * @class Tone.Lowpass is a lowpass feedback comb filter. It is similar to - * Tone.FeedbackCombFilter, but includes a lowpass filter. - * - * @extends {Tone} - * @constructor - * @param {Time|Object} [delayTime] The delay time of the comb filter - * @param {NormalRange=} resonance The resonance (feedback) of the comb filter - * @param {Frequency=} dampening The cutoff of the lowpass filter dampens the - * signal as it is fedback. - */ - Tone.LowpassCombFilter = function () { - this.createInsOuts(1, 1); - var options = this.optionsObject(arguments, [ - 'delayTime', - 'resonance', - 'dampening' - ], Tone.LowpassCombFilter.defaults); - /** - * the delay node - * @type {DelayNode} - * @private - */ - this._delay = this.input = new Tone.Delay(options.delayTime); - /** - * The delayTime of the comb filter. - * @type {Time} - * @signal - */ - this.delayTime = this._delay.delayTime; - /** - * the lowpass filter - * @type {BiquadFilterNode} - * @private - */ - this._lowpass = this.output = this.context.createBiquadFilter(); - this._lowpass.Q.value = -3.0102999566398125; - this._lowpass.type = 'lowpass'; - /** - * The dampening control of the feedback - * @type {Frequency} - * @signal - */ - this.dampening = new Tone.Param({ - 'param': this._lowpass.frequency, - 'units': Tone.Type.Frequency, - 'value': options.dampening - }); - /** - * the feedback gain - * @type {Tone.Gain} - * @private - */ - this._feedback = new Tone.Gain(options.resonance, Tone.Type.NormalRange); - /** - * The amount of feedback of the delayed signal. - * @type {NormalRange} - * @signal - */ - this.resonance = this._feedback.gain; - //connections - this._delay.chain(this._lowpass, this._feedback, this._delay); - this._readOnly([ - 'dampening', - 'resonance', - 'delayTime' - ]); - }; - Tone.extend(Tone.LowpassCombFilter); - /** - * the default parameters - * @static - * @const - * @type {Object} - */ - Tone.LowpassCombFilter.defaults = { - 'delayTime': 0.1, - 'resonance': 0.5, - 'dampening': 3000 - }; - /** - * Clean up. - * @returns {Tone.LowpassCombFilter} this - */ - Tone.LowpassCombFilter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'dampening', - 'resonance', - 'delayTime' - ]); - this.dampening.dispose(); - this.dampening = null; - this.resonance.dispose(); - this.resonance = null; - this._delay.dispose(); - this._delay = null; - this.delayTime = null; - this._lowpass.disconnect(); - this._lowpass = null; - this._feedback.disconnect(); - this._feedback = null; - return this; - }; - return Tone.LowpassCombFilter; - }); - Module(function (Tone) { - - /** - * @class Tone.Merge brings two signals into the left and right - * channels of a single stereo channel. - * - * @constructor - * @extends {Tone} - * @example - * var merge = new Tone.Merge().toMaster(); - * //routing a sine tone in the left channel - * //and noise in the right channel - * var osc = new Tone.Oscillator().connect(merge.left); - * var noise = new Tone.Noise().connect(merge.right); - * //starting our oscillators - * noise.start(); - * osc.start(); - */ - Tone.Merge = function () { - this.createInsOuts(2, 0); - /** - * The left input channel. - * Alias for input[0] - * @type {GainNode} - */ - this.left = this.input[0] = new Tone.Gain(); - /** - * The right input channel. - * Alias for input[1]. - * @type {GainNode} - */ - this.right = this.input[1] = new Tone.Gain(); - /** - * the merger node for the two channels - * @type {ChannelMergerNode} - * @private - */ - this._merger = this.output = this.context.createChannelMerger(2); - //connections - this.left.connect(this._merger, 0, 0); - this.right.connect(this._merger, 0, 1); - this.left.channelCount = 1; - this.right.channelCount = 1; - this.left.channelCountMode = 'explicit'; - this.right.channelCountMode = 'explicit'; - }; - Tone.extend(Tone.Merge); - /** - * Clean up. - * @returns {Tone.Merge} this - */ - Tone.Merge.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this.left.dispose(); - this.left = null; - this.right.dispose(); - this.right = null; - this._merger.disconnect(); - this._merger = null; - return this; - }; - return Tone.Merge; - }); - Module(function (Tone) { - - /** - * @class Tone.Meter gets the [RMS](https://en.wikipedia.org/wiki/Root_mean_square) - * of an input signal with some averaging applied. It can also get the raw - * value of the input signal. - * - * @constructor - * @extends {Tone} - * @param {String} type Either "level" or "signal". - * @param {Number} smoothing The amount of smoothing applied between frames. - * @example - * var meter = new Tone.Meter(); - * var mic = new Tone.UserMedia().start(); - * //connect mic to the meter - * mic.connect(meter); - * //the current level of the mic input - * var level = meter.value; - */ - Tone.Meter = function () { - var options = this.optionsObject(arguments, [ - 'type', - 'smoothing' - ], Tone.Meter.defaults); - /** - * The type of the meter, either "level" or "signal". - * A "level" meter will return the volume level (rms) of the - * input signal and a "signal" meter will return - * the signal value of the input. - * @type {String} - */ - this.type = options.type; - /** - * The analyser node which computes the levels. - * @private - * @type {Tone.Analyser} - */ - this.input = this.output = this._analyser = new Tone.Analyser('waveform', 512); - this._analyser.returnType = 'float'; - /** - * The amount of carryover between the current and last frame. - * Only applied meter for "level" type. - * @type {Number} - */ - this.smoothing = options.smoothing; - /** - * The last computed value - * @type {Number} - * @private - */ - this._lastValue = 0; - }; - Tone.extend(Tone.Meter); - /** - * @private - * @enum {String} - */ - Tone.Meter.Type = { - Level: 'level', - Signal: 'signal' - }; - /** - * The defaults - * @type {Object} - * @static - * @const - */ - Tone.Meter.defaults = { - 'smoothing': 0.8, - 'type': Tone.Meter.Type.Level - }; - /** - * The current value of the meter. A value of 1 is - * "unity". - * @memberOf Tone.Meter# - * @type {Number} - * @name value - * @readOnly - */ - Object.defineProperty(Tone.Meter.prototype, 'value', { - get: function () { - var signal = this._analyser.analyse(); - if (this.type === Tone.Meter.Type.Level) { - //rms - var sum = 0; - for (var i = 0; i < signal.length; i++) { - sum += Math.pow(signal[i], 2); - } - var rms = Math.sqrt(sum / signal.length); - //smooth it - rms = Math.max(rms, this._lastValue * this.smoothing); - this._lastValue = rms; - //scale it - var unity = 0.35; - var val = rms / unity; - //scale the output curve - return Math.sqrt(val); - } else { - return signal[0]; - } - } - }); - /** - * Clean up. - * @returns {Tone.Meter} this - */ - Tone.Meter.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._analyser.dispose(); - this._analyser = null; - return this; - }; - return Tone.Meter; - }); - Module(function (Tone) { - - /** - * @class Tone.Split splits an incoming signal into left and right channels. - * - * @constructor - * @extends {Tone} - * @example - * var split = new Tone.Split(); - * stereoSignal.connect(split); - */ - Tone.Split = function () { - this.createInsOuts(0, 2); - /** - * @type {ChannelSplitterNode} - * @private - */ - this._splitter = this.input = this.context.createChannelSplitter(2); - /** - * Left channel output. - * Alias for output[0] - * @type {Tone.Gain} - */ - this.left = this.output[0] = new Tone.Gain(); - /** - * Right channel output. - * Alias for output[1] - * @type {Tone.Gain} - */ - this.right = this.output[1] = new Tone.Gain(); - //connections - this._splitter.connect(this.left, 0, 0); - this._splitter.connect(this.right, 1, 0); - }; - Tone.extend(Tone.Split); - /** - * Clean up. - * @returns {Tone.Split} this - */ - Tone.Split.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._splitter.disconnect(); - this.left.dispose(); - this.left = null; - this.right.dispose(); - this.right = null; - this._splitter = null; - return this; - }; - return Tone.Split; - }); - Module(function (Tone) { - - /** - * @class Mid/Side processing separates the the 'mid' signal - * (which comes out of both the left and the right channel) - * and the 'side' (which only comes out of the the side channels).

- * - * Mid = (Left+Right)/sqrt(2); // obtain mid-signal from left and right
- * Side = (Left-Right)/sqrt(2); // obtain side-signal from left and righ
- *
- * - * @extends {Tone} - * @constructor - */ - Tone.MidSideSplit = function () { - this.createInsOuts(0, 2); - /** - * split the incoming signal into left and right channels - * @type {Tone.Split} - * @private - */ - this._split = this.input = new Tone.Split(); - /** - * The mid send. Connect to mid processing. Alias for - * output[0] - * @type {Tone.Expr} - */ - this.mid = this.output[0] = new Tone.Expr('($0 + $1) * $2'); - /** - * The side output. Connect to side processing. Alias for - * output[1] - * @type {Tone.Expr} - */ - this.side = this.output[1] = new Tone.Expr('($0 - $1) * $2'); - this._split.connect(this.mid, 0, 0); - this._split.connect(this.mid, 1, 1); - this._split.connect(this.side, 0, 0); - this._split.connect(this.side, 1, 1); - this.context.getConstant(Math.SQRT1_2).connect(this.mid, 0, 2); - this.context.getConstant(Math.SQRT1_2).connect(this.side, 0, 2); - }; - Tone.extend(Tone.MidSideSplit); - /** - * clean up - * @returns {Tone.MidSideSplit} this - */ - Tone.MidSideSplit.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this.mid.dispose(); - this.mid = null; - this.side.dispose(); - this.side = null; - this._split.dispose(); - this._split = null; - return this; - }; - return Tone.MidSideSplit; - }); - Module(function (Tone) { - - /** - * @class Mid/Side processing separates the the 'mid' signal - * (which comes out of both the left and the right channel) - * and the 'side' (which only comes out of the the side channels). - * MidSideMerge merges the mid and side signal after they've been seperated - * by Tone.MidSideSplit.

- * - * Left = (Mid+Side)/sqrt(2); // obtain left signal from mid and side
- * Right = (Mid-Side)/sqrt(2); // obtain right signal from mid and side
- *
- * - * @extends {Tone.StereoEffect} - * @constructor - */ - Tone.MidSideMerge = function () { - this.createInsOuts(2, 0); - /** - * The mid signal input. Alias for - * input[0] - * @type {Tone.Gain} - */ - this.mid = this.input[0] = new Tone.Gain(); - /** - * recombine the mid/side into Left - * @type {Tone.Expr} - * @private - */ - this._left = new Tone.Expr('($0 + $1) * $2'); - /** - * The side signal input. Alias for - * input[1] - * @type {Tone.Gain} - */ - this.side = this.input[1] = new Tone.Gain(); - /** - * recombine the mid/side into Right - * @type {Tone.Expr} - * @private - */ - this._right = new Tone.Expr('($0 - $1) * $2'); - /** - * Merge the left/right signal back into a stereo signal. - * @type {Tone.Merge} - * @private - */ - this._merge = this.output = new Tone.Merge(); - this.mid.connect(this._left, 0, 0); - this.side.connect(this._left, 0, 1); - this.mid.connect(this._right, 0, 0); - this.side.connect(this._right, 0, 1); - this._left.connect(this._merge, 0, 0); - this._right.connect(this._merge, 0, 1); - this.context.getConstant(Math.SQRT1_2).connect(this._left, 0, 2); - this.context.getConstant(Math.SQRT1_2).connect(this._right, 0, 2); - }; - Tone.extend(Tone.MidSideMerge); - /** - * clean up - * @returns {Tone.MidSideMerge} this - */ - Tone.MidSideMerge.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this.mid.dispose(); - this.mid = null; - this.side.dispose(); - this.side = null; - this._left.dispose(); - this._left = null; - this._right.dispose(); - this._right = null; - this._merge.dispose(); - this._merge = null; - return this; - }; - return Tone.MidSideMerge; - }); - Module(function (Tone) { - - /** - * @class Tone.MidSideCompressor applies two different compressors to the mid - * and side signal components. See Tone.MidSideSplit. - * - * @extends {Tone} - * @param {Object} options The options that are passed to the mid and side - * compressors. - * @constructor - */ - Tone.MidSideCompressor = function (options) { - options = this.defaultArg(options, Tone.MidSideCompressor.defaults); - /** - * the mid/side split - * @type {Tone.MidSideSplit} - * @private - */ - this._midSideSplit = this.input = new Tone.MidSideSplit(); - /** - * the mid/side recombination - * @type {Tone.MidSideMerge} - * @private - */ - this._midSideMerge = this.output = new Tone.MidSideMerge(); - /** - * The compressor applied to the mid signal - * @type {Tone.Compressor} - */ - this.mid = new Tone.Compressor(options.mid); - /** - * The compressor applied to the side signal - * @type {Tone.Compressor} - */ - this.side = new Tone.Compressor(options.side); - this._midSideSplit.mid.chain(this.mid, this._midSideMerge.mid); - this._midSideSplit.side.chain(this.side, this._midSideMerge.side); - this._readOnly([ - 'mid', - 'side' - ]); - }; - Tone.extend(Tone.MidSideCompressor); - /** - * @const - * @static - * @type {Object} - */ - Tone.MidSideCompressor.defaults = { - 'mid': { - 'ratio': 3, - 'threshold': -24, - 'release': 0.03, - 'attack': 0.02, - 'knee': 16 - }, - 'side': { - 'ratio': 6, - 'threshold': -30, - 'release': 0.25, - 'attack': 0.03, - 'knee': 10 - } - }; - /** - * Clean up. - * @returns {Tone.MidSideCompressor} this - */ - Tone.MidSideCompressor.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'mid', - 'side' - ]); - this.mid.dispose(); - this.mid = null; - this.side.dispose(); - this.side = null; - this._midSideSplit.dispose(); - this._midSideSplit = null; - this._midSideMerge.dispose(); - this._midSideMerge = null; - return this; - }; - return Tone.MidSideCompressor; - }); - Module(function (Tone) { - - /** - * @class Tone.Mono coerces the incoming mono or stereo signal into a mono signal - * where both left and right channels have the same value. This can be useful - * for [stereo imaging](https://en.wikipedia.org/wiki/Stereo_imaging). - * - * @extends {Tone} - * @constructor - */ - Tone.Mono = function () { - this.createInsOuts(1, 0); - /** - * merge the signal - * @type {Tone.Merge} - * @private - */ - this._merge = this.output = new Tone.Merge(); - this.input.connect(this._merge, 0, 0); - this.input.connect(this._merge, 0, 1); - this.input.gain.value = this.dbToGain(-10); - }; - Tone.extend(Tone.Mono); - /** - * clean up - * @returns {Tone.Mono} this - */ - Tone.Mono.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._merge.dispose(); - this._merge = null; - return this; - }; - return Tone.Mono; - }); - Module(function (Tone) { - - /** - * @class A compressor with seperate controls over low/mid/high dynamics - * - * @extends {Tone} - * @constructor - * @param {Object} options The low/mid/high compressor settings. - * @example - * var multiband = new Tone.MultibandCompressor({ - * "lowFrequency" : 200, - * "highFrequency" : 1300 - * "low" : { - * "threshold" : -12 - * } - * }) - */ - Tone.MultibandCompressor = function (options) { - options = this.defaultArg(arguments, Tone.MultibandCompressor.defaults); - /** - * split the incoming signal into high/mid/low - * @type {Tone.MultibandSplit} - * @private - */ - this._splitter = this.input = new Tone.MultibandSplit({ - 'lowFrequency': options.lowFrequency, - 'highFrequency': options.highFrequency - }); - /** - * low/mid crossover frequency. - * @type {Frequency} - * @signal - */ - this.lowFrequency = this._splitter.lowFrequency; - /** - * mid/high crossover frequency. - * @type {Frequency} - * @signal - */ - this.highFrequency = this._splitter.highFrequency; - /** - * the output - * @type {Tone.Gain} - * @private - */ - this.output = new Tone.Gain(); - /** - * The compressor applied to the low frequencies. - * @type {Tone.Compressor} - */ - this.low = new Tone.Compressor(options.low); - /** - * The compressor applied to the mid frequencies. - * @type {Tone.Compressor} - */ - this.mid = new Tone.Compressor(options.mid); - /** - * The compressor applied to the high frequencies. - * @type {Tone.Compressor} - */ - this.high = new Tone.Compressor(options.high); - //connect the compressor - this._splitter.low.chain(this.low, this.output); - this._splitter.mid.chain(this.mid, this.output); - this._splitter.high.chain(this.high, this.output); - this._readOnly([ - 'high', - 'mid', - 'low', - 'highFrequency', - 'lowFrequency' - ]); - }; - Tone.extend(Tone.MultibandCompressor); - /** - * @const - * @static - * @type {Object} - */ - Tone.MultibandCompressor.defaults = { - 'low': Tone.Compressor.defaults, - 'mid': Tone.Compressor.defaults, - 'high': Tone.Compressor.defaults, - 'lowFrequency': 250, - 'highFrequency': 2000 - }; - /** - * clean up - * @returns {Tone.MultibandCompressor} this - */ - Tone.MultibandCompressor.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._splitter.dispose(); - this._writable([ - 'high', - 'mid', - 'low', - 'highFrequency', - 'lowFrequency' - ]); - this.low.dispose(); - this.mid.dispose(); - this.high.dispose(); - this._splitter = null; - this.low = null; - this.mid = null; - this.high = null; - this.lowFrequency = null; - this.highFrequency = null; - return this; - }; - return Tone.MultibandCompressor; - }); - Module(function (Tone) { - - /** - * @class Tone.Panner is an equal power Left/Right Panner and does not - * support 3D. Panner uses the StereoPannerNode when available. - * - * @constructor - * @extends {Tone} - * @param {NormalRange} [initialPan=0] The initail panner value (defaults to 0 = center) - * @example - * //pan the input signal hard right. - * var panner = new Tone.Panner(1); - */ - Tone.Panner = function (initialPan) { - if (this._hasStereoPanner) { - /** - * the panner node - * @type {StereoPannerNode} - * @private - */ - this._panner = this.input = this.output = this.context.createStereoPanner(); - /** - * The pan control. -1 = hard left, 1 = hard right. - * @type {NormalRange} - * @signal - */ - this.pan = this._panner.pan; - } else { - /** - * the dry/wet knob - * @type {Tone.CrossFade} - * @private - */ - this._crossFade = new Tone.CrossFade(); - /** - * @type {Tone.Merge} - * @private - */ - this._merger = this.output = new Tone.Merge(); - /** - * @type {Tone.Split} - * @private - */ - this._splitter = this.input = new Tone.Split(); - /** - * The pan control. -1 = hard left, 1 = hard right. - * @type {AudioRange} - * @signal - */ - this.pan = new Tone.Signal(0, Tone.Type.AudioRange); - /** - * always sends 0 - * @type {Tone.Zero} - * @private - */ - this._zero = new Tone.Zero(); - /** - * The analog to gain conversion - * @type {Tone.AudioToGain} - * @private - */ - this._a2g = new Tone.AudioToGain(); - //CONNECTIONS: - this._zero.connect(this._a2g); - this.pan.chain(this._a2g, this._crossFade.fade); - //left channel is a, right channel is b - this._splitter.connect(this._crossFade, 0, 0); - this._splitter.connect(this._crossFade, 1, 1); - //merge it back together - this._crossFade.a.connect(this._merger, 0, 0); - this._crossFade.b.connect(this._merger, 0, 1); - } - //initial value - this.pan.value = this.defaultArg(initialPan, 0); - this._readOnly('pan'); - }; - Tone.extend(Tone.Panner); - /** - * indicates if the panner is using the new StereoPannerNode internally - * @type {boolean} - * @private - */ - Tone.Panner.prototype._hasStereoPanner = Tone.prototype.isFunction(Tone.context.createStereoPanner); - /** - * Clean up. - * @returns {Tone.Panner} this - */ - Tone.Panner.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable('pan'); - if (this._hasStereoPanner) { - this._panner.disconnect(); - this._panner = null; - this.pan = null; - } else { - this._zero.dispose(); - this._zero = null; - this._crossFade.dispose(); - this._crossFade = null; - this._splitter.dispose(); - this._splitter = null; - this._merger.dispose(); - this._merger = null; - this.pan.dispose(); - this.pan = null; - this._a2g.dispose(); - this._a2g = null; - } - return this; - }; - return Tone.Panner; - }); - Module(function (Tone) { - - /** - * @class A spatialized panner node which supports equalpower or HRTF panning. - * Tries to normalize the API across various browsers. See Tone.Listener - * - * @constructor - * @extends {Tone} - * @param {Number} positionX The initial x position. - * @param {Number} positionY The initial y position. - * @param {Number} positionZ The initial z position. - */ - Tone.Panner3D = function () { - var options = this.optionsObject(arguments, [ - 'positionX', - 'positionY', - 'positionZ' - ], Tone.Panner3D.defaults); - /** - * The panner node - * @type {PannerNode} - * @private - */ - this._panner = this.input = this.output = this.context.createPanner(); - //set some values - this._panner.panningModel = options.panningModel; - this._panner.maxDistance = options.maxDistance; - this._panner.distanceModel = options.distanceModel; - this._panner.coneOuterGain = options.coneOuterGain; - this._panner.coneOuterAngle = options.coneOuterAngle; - this._panner.coneInnerAngle = options.coneInnerAngle; - this._panner.refDistance = options.refDistance; - this._panner.rolloffFactor = options.rolloffFactor; - /** - * Holds the current orientation - * @type {Array} - * @private - */ - this._orientation = [ - options.orientationX, - options.orientationY, - options.orientationZ - ]; - /** - * Holds the current position - * @type {Array} - * @private - */ - this._position = [ - options.positionX, - options.positionY, - options.positionZ - ]; - // set the default position/orientation - this.orientationX = options.orientationX; - this.orientationY = options.orientationY; - this.orientationZ = options.orientationZ; - this.positionX = options.positionX; - this.positionY = options.positionY; - this.positionZ = options.positionZ; - }; - Tone.extend(Tone.Panner3D); - /** - * the default parameters - * @static - * @const - * @type {Object} - * Defaults according to the specification - */ - Tone.Panner3D.defaults = { - 'positionX': 0, - 'positionY': 0, - 'positionZ': 0, - 'orientationX': 0, - 'orientationY': 0, - 'orientationZ': 0, - 'panningModel': 'equalpower', - 'maxDistance': 10000, - 'distanceModel': 'inverse', - 'coneOuterGain': 0, - 'coneOuterAngle': 360, - 'coneInnerAngle': 360, - 'refDistance': 1, - 'rolloffFactor': 1 - }; - /** - * The ramp time which is applied to the setTargetAtTime - * @type {Number} - * @private - */ - Tone.Panner3D.prototype._rampTimeConstant = 0.01; - /** - * Sets the position of the source in 3d space. - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @return {Tone.Panner3D} this - */ - Tone.Panner3D.prototype.setPosition = function (x, y, z) { - if (this._panner.positionX) { - var now = this.now(); - this._panner.positionX.setTargetAtTime(x, now, this._rampTimeConstant); - this._panner.positionY.setTargetAtTime(y, now, this._rampTimeConstant); - this._panner.positionZ.setTargetAtTime(z, now, this._rampTimeConstant); - } else { - this._panner.setPosition(x, y, z); - } - this._position = Array.prototype.slice.call(arguments); - return this; - }; - /** - * Sets the orientation of the source in 3d space. - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @return {Tone.Panner3D} this - */ - Tone.Panner3D.prototype.setOrientation = function (x, y, z) { - if (this._panner.orientationX) { - var now = this.now(); - this._panner.orientationX.setTargetAtTime(x, now, this._rampTimeConstant); - this._panner.orientationY.setTargetAtTime(y, now, this._rampTimeConstant); - this._panner.orientationZ.setTargetAtTime(z, now, this._rampTimeConstant); - } else { - this._panner.setOrientation(x, y, z); - } - this._orientation = Array.prototype.slice.call(arguments); - return this; - }; - /** - * The x position of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name positionX - */ - Object.defineProperty(Tone.Panner3D.prototype, 'positionX', { - set: function (pos) { - this._position[0] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[0]; - } - }); - /** - * The y position of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name positionY - */ - Object.defineProperty(Tone.Panner3D.prototype, 'positionY', { - set: function (pos) { - this._position[1] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[1]; - } - }); - /** - * The z position of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name positionZ - */ - Object.defineProperty(Tone.Panner3D.prototype, 'positionZ', { - set: function (pos) { - this._position[2] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[2]; - } - }); - /** - * The x orientation of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name orientationX - */ - Object.defineProperty(Tone.Panner3D.prototype, 'orientationX', { - set: function (pos) { - this._orientation[0] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[0]; - } - }); - /** - * The y orientation of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name orientationY - */ - Object.defineProperty(Tone.Panner3D.prototype, 'orientationY', { - set: function (pos) { - this._orientation[1] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[1]; - } - }); - /** - * The z orientation of the panner object. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name orientationZ - */ - Object.defineProperty(Tone.Panner3D.prototype, 'orientationZ', { - set: function (pos) { - this._orientation[2] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[2]; - } - }); - /** - * Proxy a property on the panner to an exposed public propery - * @param {String} prop - * @private - */ - Tone.Panner3D._aliasProperty = function (prop) { - Object.defineProperty(Tone.Panner3D.prototype, prop, { - set: function (val) { - this._panner[prop] = val; - }, - get: function () { - return this._panner[prop]; - } - }); - }; - /** - * The panning model. Either "equalpower" or "HRTF". - * @type {String} - * @memberOf Tone.Panner3D# - * @name panningModel - */ - Tone.Panner3D._aliasProperty('panningModel'); - /** - * A reference distance for reducing volume as source move further from the listener - * @type {Number} - * @memberOf Tone.Panner3D# - * @name refDistance - */ - Tone.Panner3D._aliasProperty('refDistance'); - /** - * Describes how quickly the volume is reduced as source moves away from listener. - * @type {Number} - * @memberOf Tone.Panner3D# - * @name rolloffFactor - */ - Tone.Panner3D._aliasProperty('rolloffFactor'); - /** - * The distance model used by, "linear", "inverse", or "exponential". - * @type {String} - * @memberOf Tone.Panner3D# - * @name distanceModel - */ - Tone.Panner3D._aliasProperty('distanceModel'); - /** - * The angle, in degrees, inside of which there will be no volume reduction - * @type {Degrees} - * @memberOf Tone.Panner3D# - * @name coneInnerAngle - */ - Tone.Panner3D._aliasProperty('coneInnerAngle'); - /** - * The angle, in degrees, outside of which the volume will be reduced - * to a constant value of coneOuterGain - * @type {Degrees} - * @memberOf Tone.Panner3D# - * @name coneOuterAngle - */ - Tone.Panner3D._aliasProperty('coneOuterAngle'); - /** - * The gain outside of the coneOuterAngle - * @type {Gain} - * @memberOf Tone.Panner3D# - * @name coneOuterGain - */ - Tone.Panner3D._aliasProperty('coneOuterGain'); - /** - * The maximum distance between source and listener, - * after which the volume will not be reduced any further. - * @type {Positive} - * @memberOf Tone.Panner3D# - * @name maxDistance - */ - Tone.Panner3D._aliasProperty('maxDistance'); - /** - * Clean up. - * @returns {Tone.Panner3D} this - */ - Tone.Panner3D.prototype.dispose = function () { - this._panner.disconnect(); - this._panner = null; - this._orientation = null; - this._position = null; - return this; - }; - return Tone.Panner3D; - }); - Module(function (Tone) { - - /** - * @class Tone.PanVol is a Tone.Panner and Tone.Volume in one. - * - * @extends {Tone} - * @constructor - * @param {AudioRange} pan the initial pan - * @param {number} volume The output volume. - * @example - * //pan the incoming signal left and drop the volume - * var panVol = new Tone.PanVol(0.25, -12); - */ - Tone.PanVol = function () { - var options = this.optionsObject(arguments, [ - 'pan', - 'volume' - ], Tone.PanVol.defaults); - /** - * The panning node - * @type {Tone.Panner} - * @private - */ - this._panner = this.input = new Tone.Panner(options.pan); - /** - * The L/R panning control. - * @type {AudioRange} - * @signal - */ - this.pan = this._panner.pan; - /** - * The volume node - * @type {Tone.Volume} - */ - this._volume = this.output = new Tone.Volume(options.volume); - /** - * The volume control in decibels. - * @type {Decibels} - * @signal - */ - this.volume = this._volume.volume; - //connections - this._panner.connect(this._volume); - this._readOnly([ - 'pan', - 'volume' - ]); - }; - Tone.extend(Tone.PanVol); - /** - * The defaults - * @type {Object} - * @const - * @static - */ - Tone.PanVol.defaults = { - 'pan': 0.5, - 'volume': 0 - }; - /** - * clean up - * @returns {Tone.PanVol} this - */ - Tone.PanVol.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._writable([ - 'pan', - 'volume' - ]); - this._panner.dispose(); - this._panner = null; - this.pan = null; - this._volume.dispose(); - this._volume = null; - this.volume = null; - return this; - }; - return Tone.PanVol; - }); - Module(function (Tone) { - - /** - * @class Tone.CtrlInterpolate will interpolate between given values based - * on the "index" property. Passing in an array or object literal - * will interpolate each of the parameters. Note (i.e. "C3") - * and Time (i.e. "4n + 2") can be interpolated. All other values are - * assumed to be numbers. - * @example - * var interp = new Tone.CtrlInterpolate([0, 2, 9, 4]); - * interp.index = 0.75; - * interp.value; //returns 1.5 - * - * @example - * var interp = new Tone.CtrlInterpolate([ - * [2, 4, 5], - * [9, 3, 2], - * ]); - * @param {Array} values The array of values to interpolate over - * @param {Positive} index The initial interpolation index. - * @extends {Tone} - */ - Tone.CtrlInterpolate = function () { - var options = this.optionsObject(arguments, [ - 'values', - 'index' - ], Tone.CtrlInterpolate.defaults); - /** - * The values to interpolate between - * @type {Array} - */ - this.values = options.values; - /** - * The interpolated index between values. For example: a value of 1.5 - * would interpolate equally between the value at index 1 - * and the value at index 2. - * @example - * interp.index = 0; - * interp.value; //returns the value at 0 - * interp.index = 0.5; - * interp.value; //returns the value between indices 0 and 1. - * @type {Positive} - */ - this.index = options.index; - }; - Tone.extend(Tone.CtrlInterpolate); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.CtrlInterpolate.defaults = { - 'index': 0, - 'values': [] - }; - /** - * The current interpolated value based on the index - * @readOnly - * @memberOf Tone.CtrlInterpolate# - * @type {*} - * @name value - */ - Object.defineProperty(Tone.CtrlInterpolate.prototype, 'value', { - get: function () { - var index = this.index; - index = Math.min(index, this.values.length - 1); - var lowerPosition = Math.floor(index); - var lower = this.values[lowerPosition]; - var upper = this.values[Math.ceil(index)]; - return this._interpolate(index - lowerPosition, lower, upper); - } - }); - /** - * Internal interpolation routine - * @param {NormalRange} index The index between the lower and upper - * @param {*} lower - * @param {*} upper - * @return {*} The interpolated value - * @private - */ - Tone.CtrlInterpolate.prototype._interpolate = function (index, lower, upper) { - if (this.isArray(lower)) { - var retArray = []; - for (var i = 0; i < lower.length; i++) { - retArray[i] = this._interpolate(index, lower[i], upper[i]); - } - return retArray; - } else if (this.isObject(lower)) { - var retObj = {}; - for (var attr in lower) { - retObj[attr] = this._interpolate(index, lower[attr], upper[attr]); - } - return retObj; - } else { - lower = this._toNumber(lower); - upper = this._toNumber(upper); - return (1 - index) * lower + index * upper; - } - }; - /** - * Convert from the given type into a number - * @param {Number|String} value - * @return {Number} - * @private - */ - Tone.CtrlInterpolate.prototype._toNumber = function (val) { - if (this.isNumber(val)) { - return val; - } else { - //otherwise assume that it's Time... - return this.toSeconds(val); - } - }; - /** - * Clean up - * @return {Tone.CtrlInterpolate} this - */ - Tone.CtrlInterpolate.prototype.dispose = function () { - this.values = null; - }; - return Tone.CtrlInterpolate; - }); - Module(function (Tone) { - - /** - * @class Tone.CtrlMarkov represents a Markov Chain where each call - * to Tone.CtrlMarkov.next will move to the next state. If the next - * state choice is an array, the next state is chosen randomly with - * even probability for all of the choices. For a weighted probability - * of the next choices, pass in an object with "state" and "probability" attributes. - * The probabilities will be normalized and then chosen. If no next options - * are given for the current state, the state will stay there. - * @extends {Tone} - * @example - * var chain = new Tone.CtrlMarkov({ - * "beginning" : ["end", "middle"], - * "middle" : "end" - * }); - * chain.value = "beginning"; - * chain.next(); //returns "end" or "middle" with 50% probability - * - * @example - * var chain = new Tone.CtrlMarkov({ - * "beginning" : [{"value" : "end", "probability" : 0.8}, - * {"value" : "middle", "probability" : 0.2}], - * "middle" : "end" - * }); - * chain.value = "beginning"; - * chain.next(); //returns "end" with 80% probability or "middle" with 20%. - * @param {Object} values An object with the state names as the keys - * and the next state(s) as the values. - */ - Tone.CtrlMarkov = function (values, initial) { - /** - * The Markov values with states as the keys - * and next state(s) as the values. - * @type {Object} - */ - this.values = this.defaultArg(values, {}); - /** - * The current state of the Markov values. The next - * state will be evaluated and returned when Tone.CtrlMarkov.next - * is invoked. - * @type {String} - */ - this.value = this.defaultArg(initial, Object.keys(this.values)[0]); - }; - Tone.extend(Tone.CtrlMarkov); - /** - * Returns the next state of the Markov values. - * @return {String} - */ - Tone.CtrlMarkov.prototype.next = function () { - if (this.values.hasOwnProperty(this.value)) { - var next = this.values[this.value]; - if (this.isArray(next)) { - var distribution = this._getProbDistribution(next); - var rand = Math.random(); - var total = 0; - for (var i = 0; i < distribution.length; i++) { - var dist = distribution[i]; - if (rand > total && rand < total + dist) { - var chosen = next[i]; - if (this.isObject(chosen)) { - this.value = chosen.value; - } else { - this.value = chosen; - } - } - total += dist; - } - } else { - this.value = next; - } - } - return this.value; - }; - /** - * Choose randomly from an array weighted options in the form - * {"state" : string, "probability" : number} or an array of values - * @param {Array} options - * @return {Array} The randomly selected choice - * @private - */ - Tone.CtrlMarkov.prototype._getProbDistribution = function (options) { - var distribution = []; - var total = 0; - var needsNormalizing = false; - for (var i = 0; i < options.length; i++) { - var option = options[i]; - if (this.isObject(option)) { - needsNormalizing = true; - distribution[i] = option.probability; - } else { - distribution[i] = 1 / options.length; - } - total += distribution[i]; - } - if (needsNormalizing) { - //normalize the values - for (var j = 0; j < distribution.length; j++) { - distribution[j] = distribution[j] / total; - } - } - return distribution; - }; - /** - * Clean up - * @return {Tone.CtrlMarkov} this - */ - Tone.CtrlMarkov.prototype.dispose = function () { - this.values = null; - }; - return Tone.CtrlMarkov; - }); - Module(function (Tone) { - - /** - * @class Generate patterns from an array of values. - * Has a number of arpeggiation and randomized - * selection patterns. - * - * @param {Array} values An array of options to choose from. - * @param {Tone.CtrlPattern.Type=} type The name of the pattern. - * @extends {Tone} - */ - Tone.CtrlPattern = function () { - var options = this.optionsObject(arguments, [ - 'values', - 'type' - ], Tone.CtrlPattern.defaults); - /** - * The array of values to arpeggiate over - * @type {Array} - */ - this.values = options.values; - /** - * The current position in the values array - * @type {Number} - */ - this.index = 0; - /** - * The type placeholder - * @type {Tone.CtrlPattern.Type} - * @private - */ - this._type = null; - /** - * Shuffled values for the RandomOnce type - * @type {Array} - * @private - */ - this._shuffled = null; - /** - * The direction of the movement - * @type {String} - * @private - */ - this._direction = null; - this.type = options.type; - }; - Tone.extend(Tone.CtrlPattern); - /** - * The Control Patterns - * @type {Object} - * @static - */ - Tone.CtrlPattern.Type = { - Up: 'up', - Down: 'down', - UpDown: 'upDown', - DownUp: 'downUp', - AlternateUp: 'alternateUp', - AlternateDown: 'alternateDown', - Random: 'random', - RandomWalk: 'randomWalk', - RandomOnce: 'randomOnce' - }; - /** - * The default values. - * @type {Object} - */ - Tone.CtrlPattern.defaults = { - 'type': Tone.CtrlPattern.Type.Up, - 'values': [] - }; - /** - * The value at the current index of the pattern. - * @readOnly - * @memberOf Tone.CtrlPattern# - * @type {*} - * @name value - */ - Object.defineProperty(Tone.CtrlPattern.prototype, 'value', { - get: function () { - //some safeguards - if (this.values.length === 0) { - return; - } else if (this.values.length === 1) { - return this.values[0]; - } - this.index = Math.min(this.index, this.values.length - 1); - var val = this.values[this.index]; - if (this.type === Tone.CtrlPattern.Type.RandomOnce) { - if (this.values.length !== this._shuffled.length) { - this._shuffleValues(); - } - val = this.values[this._shuffled[this.index]]; - } - return val; - } - }); - /** - * The pattern used to select the next - * item from the values array - * @memberOf Tone.CtrlPattern# - * @type {Tone.CtrlPattern.Type} - * @name type - */ - Object.defineProperty(Tone.CtrlPattern.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - this._type = type; - this._shuffled = null; - //the first index - if (this._type === Tone.CtrlPattern.Type.Up || this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.RandomOnce || this._type === Tone.CtrlPattern.Type.AlternateUp) { - this.index = 0; - } else if (this._type === Tone.CtrlPattern.Type.Down || this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { - this.index = this.values.length - 1; - } - //the direction - if (this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.AlternateUp) { - this._direction = Tone.CtrlPattern.Type.Up; - } else if (this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { - this._direction = Tone.CtrlPattern.Type.Down; - } - //randoms - if (this._type === Tone.CtrlPattern.Type.RandomOnce) { - this._shuffleValues(); - } else if (this._type === Tone.CtrlPattern.Random) { - this.index = Math.floor(Math.random() * this.values.length); - } - } - }); - /** - * Return the next value given the current position - * and pattern. - * @return {*} The next value - */ - Tone.CtrlPattern.prototype.next = function () { - var type = this.type; - //choose the next index - if (type === Tone.CtrlPattern.Type.Up) { - this.index++; - if (this.index >= this.values.length) { - this.index = 0; - } - } else if (type === Tone.CtrlPattern.Type.Down) { - this.index--; - if (this.index < 0) { - this.index = this.values.length - 1; - } - } else if (type === Tone.CtrlPattern.Type.UpDown || type === Tone.CtrlPattern.Type.DownUp) { - if (this._direction === Tone.CtrlPattern.Type.Up) { - this.index++; - } else { - this.index--; - } - if (this.index < 0) { - this.index = 1; - this._direction = Tone.CtrlPattern.Type.Up; - } else if (this.index >= this.values.length) { - this.index = this.values.length - 2; - this._direction = Tone.CtrlPattern.Type.Down; - } - } else if (type === Tone.CtrlPattern.Type.Random) { - this.index = Math.floor(Math.random() * this.values.length); - } else if (type === Tone.CtrlPattern.Type.RandomWalk) { - if (Math.random() < 0.5) { - this.index--; - this.index = Math.max(this.index, 0); - } else { - this.index++; - this.index = Math.min(this.index, this.values.length - 1); - } - } else if (type === Tone.CtrlPattern.Type.RandomOnce) { - this.index++; - if (this.index >= this.values.length) { - this.index = 0; - //reshuffle the values for next time - this._shuffleValues(); - } - } else if (type === Tone.CtrlPattern.Type.AlternateUp) { - if (this._direction === Tone.CtrlPattern.Type.Up) { - this.index += 2; - this._direction = Tone.CtrlPattern.Type.Down; - } else { - this.index -= 1; - this._direction = Tone.CtrlPattern.Type.Up; - } - if (this.index >= this.values.length) { - this.index = 0; - this._direction = Tone.CtrlPattern.Type.Up; - } - } else if (type === Tone.CtrlPattern.Type.AlternateDown) { - if (this._direction === Tone.CtrlPattern.Type.Up) { - this.index += 1; - this._direction = Tone.CtrlPattern.Type.Down; - } else { - this.index -= 2; - this._direction = Tone.CtrlPattern.Type.Up; - } - if (this.index < 0) { - this.index = this.values.length - 1; - this._direction = Tone.CtrlPattern.Type.Down; - } - } - return this.value; - }; - /** - * Shuffles the values and places the results into the _shuffled - * @private - */ - Tone.CtrlPattern.prototype._shuffleValues = function () { - var copy = []; - this._shuffled = []; - for (var i = 0; i < this.values.length; i++) { - copy[i] = i; - } - while (copy.length > 0) { - var randVal = copy.splice(Math.floor(copy.length * Math.random()), 1); - this._shuffled.push(randVal[0]); - } - }; - /** - * Clean up - * @returns {Tone.CtrlPattern} this - */ - Tone.CtrlPattern.prototype.dispose = function () { - this._shuffled = null; - this.values = null; - }; - return Tone.CtrlPattern; - }); - Module(function (Tone) { - - /** - * @class Choose a random value. - * @extends {Tone} - * @example - * var randomWalk = new Tone.CtrlRandom({ - * "min" : 0, - * "max" : 10, - * "integer" : true - * }); - * randomWalk.eval(); - * - * @param {Number|Time=} min The minimum return value. - * @param {Number|Time=} max The maximum return value. - */ - Tone.CtrlRandom = function () { - var options = this.optionsObject(arguments, [ - 'min', - 'max' - ], Tone.CtrlRandom.defaults); - /** - * The minimum return value - * @type {Number|Time} - */ - this.min = options.min; - /** - * The maximum return value - * @type {Number|Time} - */ - this.max = options.max; - /** - * If the return value should be an integer - * @type {Boolean} - */ - this.integer = options.integer; - }; - Tone.extend(Tone.CtrlRandom); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.CtrlRandom.defaults = { - 'min': 0, - 'max': 1, - 'integer': false - }; - /** - * Return a random value between min and max. - * @readOnly - * @memberOf Tone.CtrlRandom# - * @type {*} - * @name value - */ - Object.defineProperty(Tone.CtrlRandom.prototype, 'value', { - get: function () { - var min = this.toSeconds(this.min); - var max = this.toSeconds(this.max); - var rand = Math.random(); - var val = rand * min + (1 - rand) * max; - if (this.integer) { - val = Math.floor(val); - } - return val; - } - }); - return Tone.CtrlRandom; - }); - Module(function (Tone) { - - /** - * AudioBuffer.copyToChannel polyfill - * @private - */ - if (window.AudioBuffer && !AudioBuffer.prototype.copyToChannel) { - AudioBuffer.prototype.copyToChannel = function (src, chanNum, start) { - var channel = this.getChannelData(chanNum); - start = start || 0; - for (var i = 0; i < channel.length; i++) { - channel[i + start] = src[i]; - } - }; - AudioBuffer.prototype.copyFromChannel = function (dest, chanNum, start) { - var channel = this.getChannelData(chanNum); - start = start || 0; - for (var i = 0; i < channel.length; i++) { - dest[i] = channel[i + start]; - } - }; - } - /** - * @class Buffer loading and storage. Tone.Buffer is used internally by all - * classes that make requests for audio files such as Tone.Player, - * Tone.Sampler and Tone.Convolver. - *

- * Aside from load callbacks from individual buffers, Tone.Buffer - * provides static methods which keep track of the loading progress - * of all of the buffers. These methods are Tone.Buffer.on("load" / "progress" / "error") - * - * @constructor - * @extends {Tone} - * @param {AudioBuffer|string} url The url to load, or the audio buffer to set. - * @param {Function=} onload A callback which is invoked after the buffer is loaded. - * It's recommended to use Tone.Buffer.onload instead - * since it will give you a callback when ALL buffers are loaded. - * @param {Function=} onerror The callback to invoke if there is an error - * @example - * var buffer = new Tone.Buffer("path/to/sound.mp3", function(){ - * //the buffer is now available. - * var buff = buffer.get(); - * }); - */ - Tone.Buffer = function () { - var options = this.optionsObject(arguments, [ - 'url', - 'onload', - 'onerror' - ], Tone.Buffer.defaults); - /** - * stores the loaded AudioBuffer - * @type {AudioBuffer} - * @private - */ - this._buffer = null; - /** - * indicates if the buffer should be reversed or not - * @type {Boolean} - * @private - */ - this._reversed = options.reverse; - /** - * The XHR - * @type {XMLHttpRequest} - * @private - */ - this._xhr = null; - if (options.url instanceof AudioBuffer || options.url instanceof Tone.Buffer) { - this.set(options.url); - // invoke the onload callback - if (options.onload) { - options.onload(this); - } - } else if (this.isString(options.url)) { - this.load(options.url, options.onload, options.onerror); - } - }; - Tone.extend(Tone.Buffer); - /** - * the default parameters - * @type {Object} - */ - Tone.Buffer.defaults = { - 'url': undefined, - 'reverse': false - }; - /** - * Pass in an AudioBuffer or Tone.Buffer to set the value - * of this buffer. - * @param {AudioBuffer|Tone.Buffer} buffer the buffer - * @returns {Tone.Buffer} this - */ - Tone.Buffer.prototype.set = function (buffer) { - if (buffer instanceof Tone.Buffer) { - this._buffer = buffer.get(); - } else { - this._buffer = buffer; - } - return this; - }; - /** - * @return {AudioBuffer} The audio buffer stored in the object. - */ - Tone.Buffer.prototype.get = function () { - return this._buffer; - }; - /** - * Makes an xhr reqest for the selected url then decodes - * the file as an audio buffer. Invokes - * the callback once the audio buffer loads. - * @param {String} url The url of the buffer to load. - * filetype support depends on the - * browser. - * @returns {Promise} returns a Promise which resolves with the Tone.Buffer - */ - Tone.Buffer.prototype.load = function (url, onload, onerror) { - var promise = new Promise(function (load, error) { - this._xhr = Tone.Buffer.load(url, //success - function (buff) { - this._xhr = null; - this.set(buff); - load(this); - if (onload) { - onload(this); - } - }.bind(this), //error - function (err) { - this._xhr = null; - error(err); - if (onerror) { - onerror(err); - } - }.bind(this)); - }.bind(this)); - return promise; - }; - /** - * dispose and disconnect - * @returns {Tone.Buffer} this - */ - Tone.Buffer.prototype.dispose = function () { - Tone.Emitter.prototype.dispose.call(this); - this._buffer = null; - if (this._xhr) { - Tone.Buffer._currentDownloads--; - this._xhr.abort(); - this._xhr = null; - } - return this; - }; - /** - * If the buffer is loaded or not - * @memberOf Tone.Buffer# - * @type {Boolean} - * @name loaded - * @readOnly - */ - Object.defineProperty(Tone.Buffer.prototype, 'loaded', { - get: function () { - return this.length > 0; - } - }); - /** - * The duration of the buffer. - * @memberOf Tone.Buffer# - * @type {Number} - * @name duration - * @readOnly - */ - Object.defineProperty(Tone.Buffer.prototype, 'duration', { - get: function () { - if (this._buffer) { - return this._buffer.duration; - } else { - return 0; - } - } - }); - /** - * The length of the buffer in samples - * @memberOf Tone.Buffer# - * @type {Number} - * @name length - * @readOnly - */ - Object.defineProperty(Tone.Buffer.prototype, 'length', { - get: function () { - if (this._buffer) { - return this._buffer.length; - } else { - return 0; - } - } - }); - /** - * The number of discrete audio channels. Returns 0 if no buffer - * is loaded. - * @memberOf Tone.Buffer# - * @type {Number} - * @name numberOfChannels - * @readOnly - */ - Object.defineProperty(Tone.Buffer.prototype, 'numberOfChannels', { - get: function () { - if (this._buffer) { - return this._buffer.numberOfChannels; - } else { - return 0; - } - } - }); - /** - * Set the audio buffer from the array - * @param {Float32Array} array The array to fill the audio buffer - * @param {Number} [channels=1] The number of channels contained in the array. - * If the channel is more than 1, the input array - * is expected to be a multidimensional array - * with dimensions equal to the number of channels. - * @return {Tone.Buffer} this - */ - Tone.Buffer.prototype.fromArray = function (array) { - var isMultidimensional = array[0].length > 0; - var channels = isMultidimensional ? array.length : 1; - var len = isMultidimensional ? array[0].length : array.length; - var buffer = this.context.createBuffer(channels, len, this.context.sampleRate); - if (!isMultidimensional && channels === 1) { - array = [array]; - } - for (var c = 0; c < channels; c++) { - buffer.copyToChannel(array[c], c); - } - this._buffer = buffer; - return this; - }; - /** - * Sums muliple channels into 1 channel - * @param {Number=} channel Optionally only copy a single channel from the array. - * @return {Array} - */ - Tone.Buffer.prototype.toMono = function (chanNum) { - if (this.isNumber(chanNum)) { - this.fromArray(this.toArray(chanNum)); - } else { - var outputArray = new Float32Array(this.length); - var numChannels = this.numberOfChannels; - for (var channel = 0; channel < numChannels; channel++) { - var channelArray = this.toArray(channel); - for (var i = 0; i < channelArray.length; i++) { - outputArray[i] += channelArray[i]; - } - } - //divide by the number of channels - outputArray = outputArray.map(function (sample) { - return sample / numChannels; - }); - this.fromArray(outputArray); - } - return this; - }; - /** - * Get the buffer as an array. Single channel buffers will return a 1-dimensional - * Float32Array, and multichannel buffers will return multidimensional arrays. - * @param {Number=} channel Optionally only copy a single channel from the array. - * @return {Array} - */ - Tone.Buffer.prototype.toArray = function (channel) { - if (this.isNumber(channel)) { - return this.getChannelData(channel); - } else if (this.numberOfChannels === 1) { - return this.toArray(0); - } else { - var ret = []; - for (var c = 0; c < this.numberOfChannels; c++) { - ret[c] = this.getChannelData(c); - } - return ret; - } - }; - /** - * Returns the Float32Array representing the PCM audio data for the specific channel. - * @param {Number} channel The channel number to return - * @return {Float32Array} The audio as a TypedArray - */ - Tone.Buffer.prototype.getChannelData = function (channel) { - return this._buffer.getChannelData(channel); - }; - /** - * Cut a subsection of the array and return a buffer of the - * subsection. Does not modify the original buffer - * @param {Time} start The time to start the slice - * @param {Time=} end The end time to slice. If none is given - * will default to the end of the buffer - * @return {Tone.Buffer} this - */ - Tone.Buffer.prototype.slice = function (start, end) { - end = this.defaultArg(end, this.duration); - var startSamples = Math.floor(this.context.sampleRate * this.toSeconds(start)); - var endSamples = Math.floor(this.context.sampleRate * this.toSeconds(end)); - var replacement = []; - for (var i = 0; i < this.numberOfChannels; i++) { - replacement[i] = this.toArray(i).slice(startSamples, endSamples); - } - var retBuffer = new Tone.Buffer().fromArray(replacement); - return retBuffer; - }; - /** - * Reverse the buffer. - * @private - * @return {Tone.Buffer} this - */ - Tone.Buffer.prototype._reverse = function () { - if (this.loaded) { - for (var i = 0; i < this.numberOfChannels; i++) { - Array.prototype.reverse.call(this.getChannelData(i)); - } - } - return this; - }; - /** - * Reverse the buffer. - * @memberOf Tone.Buffer# - * @type {Boolean} - * @name reverse - */ - Object.defineProperty(Tone.Buffer.prototype, 'reverse', { - get: function () { - return this._reversed; - }, - set: function (rev) { - if (this._reversed !== rev) { - this._reversed = rev; - this._reverse(); - } - } - }); - /////////////////////////////////////////////////////////////////////////// - // STATIC METHODS - /////////////////////////////////////////////////////////////////////////// - //statically inherits Emitter methods - Tone.Emitter.mixin(Tone.Buffer); - /** - * the static queue for all of the xhr requests - * @type {Array} - * @private - */ - Tone.Buffer._downloadQueue = []; - /** - * the total number of downloads - * @type {Number} - * @private - */ - Tone.Buffer._currentDownloads = 0; - /** - * A path which is prefixed before every url. - * @type {String} - * @static - */ - Tone.Buffer.baseUrl = ''; - /** - * Loads a url using XMLHttpRequest. - * @param {String} url - * @param {Function} onload - * @param {Function} onerror - * @param {Function} onprogress - * @return {XMLHttpRequest} - */ - Tone.Buffer.load = function (url, onload, onerror) { - //default - onload = onload || Tone.noOp; - function onError(e) { - if (onerror) { - onerror(e); - Tone.Buffer.emit('error', e); - } else { - throw new Error(e); - } - } - function onProgress() { - //calculate the progress - var totalProgress = 0; - for (var i = 0; i < Tone.Buffer._downloadQueue.length; i++) { - totalProgress += Tone.Buffer._downloadQueue[i].progress; - } - Tone.Buffer.emit('progress', totalProgress / Tone.Buffer._downloadQueue.length); - } - var request = new XMLHttpRequest(); - request.open('GET', Tone.Buffer.baseUrl + url, true); - request.responseType = 'arraybuffer'; - //start out as 0 - request.progress = 0; - Tone.Buffer._currentDownloads++; - Tone.Buffer._downloadQueue.push(request); - request.addEventListener('load', function () { - if (request.status === 200) { - Tone.context.decodeAudioData(request.response, function (buff) { - request.progress = 1; - onProgress(); - onload(buff); - Tone.Buffer._currentDownloads--; - if (Tone.Buffer._currentDownloads === 0) { - // clear the downloads - Tone.Buffer._downloadQueue = []; - //emit the event at the end - Tone.Buffer.emit('load'); - } - }, function () { - onError('Tone.Buffer: could not decode audio data: ' + url); - }); - } else { - onError('Tone.Buffer: could not locate file: ' + url); - } - }); - request.addEventListener('error', onError); - request.addEventListener('progress', function (event) { - if (event.lengthComputable) { - //only go to 95%, the last 5% is when the audio is decoded - request.progress = event.loaded / event.total * 0.95; - onProgress(); - } - }); - request.send(); - return request; - }; - /** - * Stop all of the downloads in progress - * @return {Tone.Buffer} - * @static - */ - Tone.Buffer.cancelDownloads = function () { - Tone.Buffer._downloadQueue.forEach(function (request) { - request.abort(); - }); - Tone.Buffer._currentDownloads = 0; - return Tone.Buffer; - }; - /** - * Checks a url's extension to see if the current browser can play that file type. - * @param {String} url The url/extension to test - * @return {Boolean} If the file extension can be played - * @static - * @example - * Tone.Buffer.supportsType("wav"); //returns true - * Tone.Buffer.supportsType("path/to/file.wav"); //returns true - */ - Tone.Buffer.supportsType = function (url) { - var extension = url.split('.'); - extension = extension[extension.length - 1]; - var response = document.createElement('audio').canPlayType('audio/' + extension); - return response !== ''; - }; - /** - * Returns a Promise which resolves when all of the buffers have loaded - * @return {Promise} - */ - Tone.loaded = function () { - var onload, onerror; - function removeEvents() { - //remove the events when it's resolved - Tone.Buffer.off('load', onload); - Tone.Buffer.off('error', onerror); - } - return new Promise(function (success, fail) { - onload = function () { - success(); - }; - onerror = function () { - fail(); - }; - //add the event listeners - Tone.Buffer.on('load', onload); - Tone.Buffer.on('error', onerror); - }).then(removeEvents).catch(function (e) { - removeEvents(); - throw new Error(e); - }); - }; - return Tone.Buffer; - }); - Module(function (Tone) { - /** - * @class A data structure for holding multiple buffers. - * - * @param {Object|Array} urls An object literal or array - * of urls to load. - * @param {Function=} callback The callback to invoke when - * the buffers are loaded. - * @extends {Tone} - * @example - * //load a whole bank of piano samples - * var pianoSamples = new Tone.Buffers({ - * "C4" : "path/to/C4.mp3" - * "C#4" : "path/to/C#4.mp3" - * "D4" : "path/to/D4.mp3" - * "D#4" : "path/to/D#4.mp3" - * ... - * }, function(){ - * //play one of the samples when they all load - * player.buffer = pianoSamples.get("C4"); - * player.start(); - * }); - * - */ - Tone.Buffers = function (urls, onload, baseUrl) { - /** - * All of the buffers - * @type {Object} - * @private - */ - this._buffers = {}; - /** - * A path which is prefixed before every url. - * @type {String} - */ - this.baseUrl = this.defaultArg(baseUrl, ''); - urls = this._flattenUrls(urls); - this._loadingCount = 0; - //add each one - for (var key in urls) { - this._loadingCount++; - this.add(key, urls[key], this._bufferLoaded.bind(this, onload)); - } - }; - Tone.extend(Tone.Buffers); - /** - * True if the buffers object has a buffer by that name. - * @param {String|Number} name The key or index of the - * buffer. - * @return {Boolean} - */ - Tone.Buffers.prototype.has = function (name) { - return this._buffers.hasOwnProperty(name); - }; - /** - * Get a buffer by name. If an array was loaded, - * then use the array index. - * @param {String|Number} name The key or index of the - * buffer. - * @return {Tone.Buffer} - */ - Tone.Buffers.prototype.get = function (name) { - if (this.has(name)) { - return this._buffers[name]; - } else { - throw new Error('Tone.Buffers: no buffer named ' + name); - } - }; - /** - * A buffer was loaded. decrement the counter. - * @param {Function} callback - * @private - */ - Tone.Buffers.prototype._bufferLoaded = function (callback) { - this._loadingCount--; - if (this._loadingCount === 0 && callback) { - callback(this); - } - }; - /** - * If the buffers are loaded or not - * @memberOf Tone.Buffers# - * @type {Boolean} - * @name loaded - * @readOnly - */ - Object.defineProperty(Tone.Buffers.prototype, 'loaded', { - get: function () { - var isLoaded = true; - for (var buffName in this._buffers) { - var buff = this.get(buffName); - isLoaded = isLoaded && buff.loaded; - } - return isLoaded; - } - }); - /** - * Add a buffer by name and url to the Buffers - * @param {String} name A unique name to give - * the buffer - * @param {String|Tone.Buffer|Audiobuffer} url Either the url of the bufer, - * or a buffer which will be added - * with the given name. - * @param {Function=} callback The callback to invoke - * when the url is loaded. - */ - Tone.Buffers.prototype.add = function (name, url, callback) { - callback = this.defaultArg(callback, Tone.noOp); - if (url instanceof Tone.Buffer) { - this._buffers[name] = url; - callback(this); - } else if (url instanceof AudioBuffer) { - this._buffers[name] = new Tone.Buffer(url); - callback(this); - } else if (this.isString(url)) { - this._buffers[name] = new Tone.Buffer(this.baseUrl + url, callback); - } - return this; - }; - /** - * Flatten an object into a single depth object. - * thanks to https://gist.github.com/penguinboy/762197 - * @param {Object} ob - * @return {Object} - * @private - */ - Tone.Buffers.prototype._flattenUrls = function (ob) { - var toReturn = {}; - for (var i in ob) { - if (!ob.hasOwnProperty(i)) - continue; - if (this.isObject(ob[i])) { - var flatObject = this._flattenUrls(ob[i]); - for (var x in flatObject) { - if (!flatObject.hasOwnProperty(x)) - continue; - toReturn[i + '.' + x] = flatObject[x]; - } - } else { - toReturn[i] = ob[i]; - } - } - return toReturn; - }; - /** - * Clean up. - * @return {Tone.Buffers} this - */ - Tone.Buffers.prototype.dispose = function () { - for (var name in this._buffers) { - this._buffers[name].dispose(); - } - this._buffers = null; - return this; - }; - return Tone.Buffers; - }); - Module(function (Tone) { - - /** - * buses are another way of routing audio - * - * augments Tone.prototype to include send and recieve - */ - /** - * All of the routes - * - * @type {Object} - * @static - * @private - */ - var Buses = {}; - /** - * Send this signal to the channel name. - * @param {string} channelName A named channel to send the signal to. - * @param {Decibels} amount The amount of the source to send to the bus. - * @return {GainNode} The gain node which connects this node to the desired channel. - * Can be used to adjust the levels of the send. - * @example - * source.send("reverb", -12); - */ - Tone.prototype.send = function (channelName, amount) { - if (!Buses.hasOwnProperty(channelName)) { - Buses[channelName] = this.context.createGain(); - } - amount = this.defaultArg(amount, 0); - var sendKnob = new Tone.Gain(amount, Tone.Type.Decibels); - this.output.chain(sendKnob, Buses[channelName]); - return sendKnob; - }; - /** - * Recieve the input from the desired channelName to the input - * - * @param {string} channelName A named channel to send the signal to. - * @param {AudioNode} [input] If no input is selected, the - * input of the current node is - * chosen. - * @returns {Tone} this - * @example - * reverbEffect.receive("reverb"); - */ - Tone.prototype.receive = function (channelName, input) { - if (!Buses.hasOwnProperty(channelName)) { - Buses[channelName] = this.context.createGain(); - } - if (this.isUndef(input)) { - input = this.input; - } - Buses[channelName].connect(input); - return this; - }; - //remove all the send/receives when a new audio context is passed in - Tone.Context.on('init', function (context) { - if (context.Buses) { - Buses = context.Buses; - } else { - Buses = {}; - context.Buses = Buses; - } - }); - return Tone; - }); - Module(function (Tone) { - - /** - * @class Tone.Draw is useful for synchronizing visuals and audio events. - * Callbacks from Tone.Transport or any of the Tone.Event classes - * always happen _before_ the scheduled time and are not synchronized - * to the animation frame so they are not good for triggering tightly - * synchronized visuals and sound. Tone.Draw makes it easy to schedule - * callbacks using the AudioContext time and uses requestAnimationFrame. - * - * @singleton - * @extends {Tone} - * @example - * Tone.Transport.schedule(function(time){ - * //use the time argument to schedule a callback with Tone.Draw - * Tone.Draw.schedule(function(){ - * //do drawing or DOM manipulation here - * }, time) - * }, "+0.5") - */ - Tone.Draw = function () { - /** - * All of the events. - * @type {Tone.Timeline} - * @private - */ - this._events = new Tone.Timeline(); - /** - * The duration after which events are not invoked. - * @type {Number} - * @default 0.25 - */ - this.expiration = 0.25; - /** - * The amount of time before the scheduled time - * that the callback can be invoked. Default is - * half the time of an animation frame (0.008 seconds). - * @type {Number} - * @default 0.008 - */ - this.anticipation = 0.008; - /** - * The draw loop - * @type {Function} - * @private - */ - this._boundDrawLoop = this._drawLoop.bind(this); - }; - Tone.extend(Tone.Draw); - /** - * Schedule a function at the given time to be invoked - * on the nearest animation frame. - * @param {Function} callback Callback is invoked at the given time. - * @param {Time} time The time relative to the AudioContext time - * to invoke the callback. - * @return {Tone.Draw} this - */ - Tone.Draw.prototype.schedule = function (callback, time) { - this._events.add({ - callback: callback, - time: this.toSeconds(time) - }); - //start the draw loop on the first event - if (this._events.length === 1) { - requestAnimationFrame(this._boundDrawLoop); - } - return this; - }; - /** - * Cancel events scheduled after the given time - * @param {Time=} after Time after which scheduled events will - * be removed from the scheduling timeline. - * @return {Tone.Draw} this - */ - Tone.Draw.prototype.cancel = function (after) { - this._events.cancel(this.toSeconds(after)); - return this; - }; - /** - * The draw loop - * @private - */ - Tone.Draw.prototype._drawLoop = function () { - var now = Tone.now(); - while (this._events.length && this._events.peek().time - this.anticipation <= now) { - var event = this._events.shift(); - if (now - event.time <= this.expiration) { - event.callback(); - } - } - if (this._events.length > 0) { - requestAnimationFrame(this._boundDrawLoop); - } - }; - //make a singleton - Tone.Draw = new Tone.Draw(); - return Tone.Draw; - }); - Module(function (Tone) { - - /** - * @class Both Tone.Panner3D and Tone.Listener have a position in 3D space - * using a right-handed cartesian coordinate system. - * The units used in the coordinate system are not defined; - * these coordinates are independent/invariant of any particular - * units such as meters or feet. Tone.Panner3D objects have an forward - * vector representing the direction the sound is projecting. Additionally, - * they have a sound cone representing how directional the sound is. - * For example, the sound could be omnidirectional, in which case it would - * be heard anywhere regardless of its forward, or it can be more directional - * and heard only if it is facing the listener. Tone.Listener objects - * (representing a person's ears) have an forward and up vector - * representing in which direction the person is facing. Because both the - * source stream and the listener can be moving, they both have a velocity - * vector representing both the speed and direction of movement. Taken together, - * these two velocities can be used to generate a doppler shift effect which changes the pitch. - *

- * Note: the position of the Listener will have no effect on nodes not connected to a Tone.Panner3D - * - * @constructor - * @extends {Tone} - * @singleton - * @param {Number} positionX The initial x position. - * @param {Number} positionY The initial y position. - * @param {Number} positionZ The initial z position. - */ - Tone.Listener = function () { - var options = this.optionsObject(arguments, [ - 'positionX', - 'positionY', - 'positionZ' - ], ListenerConstructor.defaults); - /** - * Holds the current forward orientation - * @type {Array} - * @private - */ - this._orientation = [ - options.forwardX, - options.forwardY, - options.forwardZ, - options.upX, - options.upY, - options.upZ - ]; - /** - * Holds the current position - * @type {Array} - * @private - */ - this._position = [ - options.positionX, - options.positionY, - options.positionZ - ]; - // set the default position/forward - this.forwardX = options.forwardX; - this.forwardY = options.forwardY; - this.forwardZ = options.forwardZ; - this.upX = options.upX; - this.upY = options.upY; - this.upZ = options.upZ; - this.positionX = options.positionX; - this.positionY = options.positionY; - this.positionZ = options.positionZ; - }; - Tone.extend(Tone.Listener); - /** - * the default parameters - * @static - * @const - * @type {Object} - * Defaults according to the specification - */ - Tone.Listener.defaults = { - 'positionX': 0, - 'positionY': 0, - 'positionZ': 0, - 'forwardX': 0, - 'forwardY': 0, - 'forwardZ': 1, - 'upX': 0, - 'upY': 1, - 'upZ': 0 - }; - /** - * The ramp time which is applied to the setTargetAtTime - * @type {Number} - * @private - */ - Tone.Listener.prototype._rampTimeConstant = 0.01; - /** - * Sets the position of the listener in 3d space. - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @return {Tone.Listener} this - */ - Tone.Listener.prototype.setPosition = function (x, y, z) { - if (this.context.listener.positionX) { - var now = this.now(); - this.context.listener.positionX.setTargetAtTime(x, now, this._rampTimeConstant); - this.context.listener.positionY.setTargetAtTime(y, now, this._rampTimeConstant); - this.context.listener.positionZ.setTargetAtTime(z, now, this._rampTimeConstant); - } else { - this.context.listener.setPosition(x, y, z); - } - this._position = Array.prototype.slice.call(arguments); - return this; - }; - /** - * Sets the orientation of the listener using two vectors, the forward - * vector (which direction the listener is facing) and the up vector - * (which the up direction of the listener). An up vector - * of 0, 0, 1 is equivalent to the listener standing up in the Z direction. - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {Number} upX - * @param {Number} upY - * @param {Number} upZ - * @return {Tone.Listener} this - */ - Tone.Listener.prototype.setOrientation = function (x, y, z, upX, upY, upZ) { - if (this.context.listener.forwardX) { - var now = this.now(); - this.context.listener.forwardX.setTargetAtTime(x, now, this._rampTimeConstant); - this.context.listener.forwardY.setTargetAtTime(y, now, this._rampTimeConstant); - this.context.listener.forwardZ.setTargetAtTime(z, now, this._rampTimeConstant); - this.context.listener.upX.setTargetAtTime(upX, now, this._rampTimeConstant); - this.context.listener.upY.setTargetAtTime(upY, now, this._rampTimeConstant); - this.context.listener.upZ.setTargetAtTime(upZ, now, this._rampTimeConstant); - } else { - this.context.listener.setOrientation(x, y, z, upX, upY, upZ); - } - this._orientation = Array.prototype.slice.call(arguments); - return this; - }; - /** - * The x position of the panner object. - * @type {Number} - * @memberOf Tone.Listener# - * @name positionX - */ - Object.defineProperty(Tone.Listener.prototype, 'positionX', { - set: function (pos) { - this._position[0] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[0]; - } - }); - /** - * The y position of the panner object. - * @type {Number} - * @memberOf Tone.Listener# - * @name positionY - */ - Object.defineProperty(Tone.Listener.prototype, 'positionY', { - set: function (pos) { - this._position[1] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[1]; - } - }); - /** - * The z position of the panner object. - * @type {Number} - * @memberOf Tone.Listener# - * @name positionZ - */ - Object.defineProperty(Tone.Listener.prototype, 'positionZ', { - set: function (pos) { - this._position[2] = pos; - this.setPosition.apply(this, this._position); - }, - get: function () { - return this._position[2]; - } - }); - /** - * The x coordinate of the listeners front direction. i.e. - * which way they are facing. - * @type {Number} - * @memberOf Tone.Listener# - * @name forwardX - */ - Object.defineProperty(Tone.Listener.prototype, 'forwardX', { - set: function (pos) { - this._orientation[0] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[0]; - } - }); - /** - * The y coordinate of the listeners front direction. i.e. - * which way they are facing. - * @type {Number} - * @memberOf Tone.Listener# - * @name forwardY - */ - Object.defineProperty(Tone.Listener.prototype, 'forwardY', { - set: function (pos) { - this._orientation[1] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[1]; - } - }); - /** - * The z coordinate of the listeners front direction. i.e. - * which way they are facing. - * @type {Number} - * @memberOf Tone.Listener# - * @name forwardZ - */ - Object.defineProperty(Tone.Listener.prototype, 'forwardZ', { - set: function (pos) { - this._orientation[2] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[2]; - } - }); - /** - * The x coordinate of the listener's up direction. i.e. - * the direction the listener is standing in. - * @type {Number} - * @memberOf Tone.Listener# - * @name upX - */ - Object.defineProperty(Tone.Listener.prototype, 'upX', { - set: function (pos) { - this._orientation[3] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[3]; - } - }); - /** - * The y coordinate of the listener's up direction. i.e. - * the direction the listener is standing in. - * @type {Number} - * @memberOf Tone.Listener# - * @name upY - */ - Object.defineProperty(Tone.Listener.prototype, 'upY', { - set: function (pos) { - this._orientation[4] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[4]; - } - }); - /** - * The z coordinate of the listener's up direction. i.e. - * the direction the listener is standing in. - * @type {Number} - * @memberOf Tone.Listener# - * @name upZ - */ - Object.defineProperty(Tone.Listener.prototype, 'upZ', { - set: function (pos) { - this._orientation[5] = pos; - this.setOrientation.apply(this, this._orientation); - }, - get: function () { - return this._orientation[5]; - } - }); - /** - * Clean up. - * @returns {Tone.Listener} this - */ - Tone.Listener.prototype.dispose = function () { - this._orientation = null; - this._position = null; - return this; - }; - //SINGLETON SETUP - var ListenerConstructor = Tone.Listener; - Tone.Listener = new ListenerConstructor(); - Tone.Context.on('init', function (context) { - if (context.Listener instanceof ListenerConstructor) { - //a single listener object - Tone.Listener = context.Listener; - } else { - //make new Listener insides - Tone.Listener = new ListenerConstructor(); - } - context.Listener = Tone.Listener; - }); - //END SINGLETON SETUP - return Tone.Listener; - }); - Module(function (Tone) { - /** - * shim - * @private - */ - if (!window.hasOwnProperty('OfflineAudioContext') && window.hasOwnProperty('webkitOfflineAudioContext')) { - window.OfflineAudioContext = window.webkitOfflineAudioContext; - } - /** - * @class Wrapper around the OfflineAudioContext - * @extends {Tone.Context - * @param {Number} channels The number of channels to render - * @param {Number} duration The duration to render in samples - * @param {Number} sampleRate the sample rate to render at - */ - Tone.OfflineContext = function (channels, duration, sampleRate) { - /** - * The offline context - * @private - * @type {OfflineAudioContext} - */ - var offlineContext = new OfflineAudioContext(channels, duration * sampleRate, sampleRate); - //wrap the methods/members - Tone.Context.call(this, offlineContext); - /** - * A private reference to the duration - * @private - * @type {Number} - */ - this._duration = duration; - /** - * An artificial clock source - * @type {Number} - * @private - */ - this._currentTime = 0; - //modify the lookAhead and updateInterval to one block - this.lookAhead = this.blockTime; - this.updateInterval = this.blockTime; - }; - Tone.extend(Tone.OfflineContext, Tone.Context); - /** - * Override the now method to point to the internal clock time - * @return {Number} - */ - Tone.OfflineContext.prototype.now = function () { - return this._currentTime; - }; - /** - * Overwrite this method since the worker is not necessary for the offline context - * @private - */ - Tone.OfflineContext.prototype._createWorker = function () { - //dummy worker that does nothing - return { - postMessage: function () { - } - }; - }; - /** - * Render the output of the OfflineContext - * @return {Promise} - */ - Tone.OfflineContext.prototype.render = function () { - while (this._duration - this._currentTime >= 0) { - //invoke all the callbacks on that time - this.emit('tick'); - //increment the clock - this._currentTime += Tone.prototype.blockTime; - } - //promise returned is not yet implemented in all browsers - return new Promise(function (done) { - this._context.oncomplete = function (e) { - done(e.renderedBuffer); - }; - this._context.startRendering(); - }.bind(this)); - }; - return Tone.OfflineContext; - }); - Module(function (Tone) { - /** - * Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext. - * The OfflineAudioContext is capable of rendering much faster than real time in many cases. - * The callback function also passes in an offline instance of Tone.Transport which can be used - * to schedule events along the Transport. - * @param {Function} callback All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer. - * @param {Time} duration the amount of time to record for. - * @return {Promise} The promise which is invoked with the Tone.Buffer of the recorded output. - * @example - * //render 2 seconds of the oscillator - * Tone.Offline(function(){ - * //only nodes created in this callback will be recorded - * var oscillator = new Tone.Oscillator().toMaster().start(0) - * //schedule their events - * }, 2).then(function(buffer){ - * //do something with the output buffer - * }) - * @example - * //can also schedule events along the Transport - * //using the passed in Offline Transport - * Tone.Offline(function(Transport){ - * var osc = new Tone.Oscillator().toMaster() - * Transport.schedule(function(time){ - * osc.start(time).stop(time + 0.1) - * }, 1) - * Transport.start(0.2) - * }, 4).then(function(buffer){ - * //do something with the output buffer - * }) - */ - Tone.Offline = function (callback, duration) { - //set the OfflineAudioContext - var sampleRate = Tone.context.sampleRate; - var originalContext = Tone.context; - var context = new Tone.OfflineContext(2, duration, sampleRate); - Tone.context = context; - //invoke the callback/scheduling - callback(Tone.Transport); - //process the audio - var rendered = context.render(); - //return the original AudioContext - Tone.context = originalContext; - //return the audio - return rendered.then(function (buffer) { - //wrap it in a Tone.Buffer - return new Tone.Buffer(buffer); - }); - }; - return Tone.Offline; - }); - Module(function (Tone) { - - /** - * @class Tone.Effect is the base class for effects. Connect the effect between - * the effectSend and effectReturn GainNodes, then control the amount of - * effect which goes to the output using the wet control. - * - * @constructor - * @extends {Tone} - * @param {NormalRange|Object} [wet] The starting wet value. - */ - Tone.Effect = function () { - this.createInsOuts(1, 1); - //get all of the defaults - var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); - /** - * the drywet knob to control the amount of effect - * @type {Tone.CrossFade} - * @private - */ - this._dryWet = new Tone.CrossFade(options.wet); - /** - * The wet control is how much of the effected - * will pass through to the output. 1 = 100% effected - * signal, 0 = 100% dry signal. - * @type {NormalRange} - * @signal - */ - this.wet = this._dryWet.fade; - /** - * connect the effectSend to the input of hte effect - * @type {Tone.Gain} - * @private - */ - this.effectSend = new Tone.Gain(); - /** - * connect the output of the effect to the effectReturn - * @type {Tone.Gain} - * @private - */ - this.effectReturn = new Tone.Gain(); - //connections - this.input.connect(this._dryWet.a); - this.input.connect(this.effectSend); - this.effectReturn.connect(this._dryWet.b); - this._dryWet.connect(this.output); - this._readOnly(['wet']); - }; - Tone.extend(Tone.Effect); - /** - * @static - * @type {Object} - */ - Tone.Effect.defaults = { 'wet': 1 }; - /** - * chains the effect in between the effectSend and effectReturn - * @param {Tone} effect - * @private - * @returns {Tone.Effect} this - */ - Tone.Effect.prototype.connectEffect = function (effect) { - this.effectSend.chain(effect, this.effectReturn); - return this; - }; - /** - * Clean up. - * @returns {Tone.Effect} this - */ - Tone.Effect.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._dryWet.dispose(); - this._dryWet = null; - this.effectSend.dispose(); - this.effectSend = null; - this.effectReturn.dispose(); - this.effectReturn = null; - this._writable(['wet']); - this.wet = null; - return this; - }; - return Tone.Effect; - }); - Module(function (Tone) { - - /** - * @class Tone.AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency. - * Setting the LFO rate and depth allows for control over the filter modulation rate - * and depth. - * - * @constructor - * @extends {Tone.Effect} - * @param {Time|Object} [frequency] The rate of the LFO. - * @param {Frequency=} baseFrequency The lower value of the LFOs oscillation - * @param {Frequency=} octaves The number of octaves above the baseFrequency - * @example - * //create an autofilter and start it's LFO - * var autoFilter = new Tone.AutoFilter("4n").toMaster().start(); - * //route an oscillator through the filter and start it - * var oscillator = new Tone.Oscillator().connect(autoFilter).start(); - */ - Tone.AutoFilter = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'baseFrequency', - 'octaves' - ], Tone.AutoFilter.defaults); - Tone.Effect.call(this, options); - /** - * the lfo which drives the filter cutoff - * @type {Tone.LFO} - * @private - */ - this._lfo = new Tone.LFO({ - 'frequency': options.frequency, - 'amplitude': options.depth - }); - /** - * The range of the filter modulating between the min and max frequency. - * 0 = no modulation. 1 = full modulation. - * @type {NormalRange} - * @signal - */ - this.depth = this._lfo.amplitude; - /** - * How fast the filter modulates between min and max. - * @type {Frequency} - * @signal - */ - this.frequency = this._lfo.frequency; - /** - * The filter node - * @type {Tone.Filter} - */ - this.filter = new Tone.Filter(options.filter); - /** - * The octaves placeholder - * @type {Positive} - * @private - */ - this._octaves = 0; - //connections - this.connectEffect(this.filter); - this._lfo.connect(this.filter.frequency); - this.type = options.type; - this._readOnly([ - 'frequency', - 'depth' - ]); - this.octaves = options.octaves; - this.baseFrequency = options.baseFrequency; - }; - //extend Effect - Tone.extend(Tone.AutoFilter, Tone.Effect); - /** - * defaults - * @static - * @type {Object} - */ - Tone.AutoFilter.defaults = { - 'frequency': 1, - 'type': 'sine', - 'depth': 1, - 'baseFrequency': 200, - 'octaves': 2.6, - 'filter': { - 'type': 'lowpass', - 'rolloff': -12, - 'Q': 1 - } - }; - /** - * Start the effect. - * @param {Time} [time=now] When the LFO will start. - * @returns {Tone.AutoFilter} this - */ - Tone.AutoFilter.prototype.start = function (time) { - this._lfo.start(time); - return this; - }; - /** - * Stop the effect. - * @param {Time} [time=now] When the LFO will stop. - * @returns {Tone.AutoFilter} this - */ - Tone.AutoFilter.prototype.stop = function (time) { - this._lfo.stop(time); - return this; - }; - /** - * Sync the filter to the transport. - * @param {Time} [delay=0] Delay time before starting the effect after the - * Transport has started. - * @returns {Tone.AutoFilter} this - */ - Tone.AutoFilter.prototype.sync = function (delay) { - this._lfo.sync(delay); - return this; - }; - /** - * Unsync the filter from the transport. - * @returns {Tone.AutoFilter} this - */ - Tone.AutoFilter.prototype.unsync = function () { - this._lfo.unsync(); - return this; - }; - /** - * Type of oscillator attached to the AutoFilter. - * Possible values: "sine", "square", "triangle", "sawtooth". - * @memberOf Tone.AutoFilter# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.AutoFilter.prototype, 'type', { - get: function () { - return this._lfo.type; - }, - set: function (type) { - this._lfo.type = type; - } - }); - /** - * The minimum value of the filter's cutoff frequency. - * @memberOf Tone.AutoFilter# - * @type {Frequency} - * @name min - */ - Object.defineProperty(Tone.AutoFilter.prototype, 'baseFrequency', { - get: function () { - return this._lfo.min; - }, - set: function (freq) { - this._lfo.min = this.toFrequency(freq); - //and set the max - this.octaves = this._octaves; - } - }); - /** - * The maximum value of the filter's cutoff frequency. - * @memberOf Tone.AutoFilter# - * @type {Positive} - * @name octaves - */ - Object.defineProperty(Tone.AutoFilter.prototype, 'octaves', { - get: function () { - return this._octaves; - }, - set: function (oct) { - this._octaves = oct; - this._lfo.max = this.baseFrequency * Math.pow(2, oct); - } - }); - /** - * Clean up. - * @returns {Tone.AutoFilter} this - */ - Tone.AutoFilter.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._lfo.dispose(); - this._lfo = null; - this.filter.dispose(); - this.filter = null; - this._writable([ - 'frequency', - 'depth' - ]); - this.frequency = null; - this.depth = null; - return this; - }; - return Tone.AutoFilter; - }); - Module(function (Tone) { - - /** - * @class Tone.AutoPanner is a Tone.Panner with an LFO connected to the pan amount. - * More on using autopanners [here](https://www.ableton.com/en/blog/autopan-chopper-effect-and-more-liveschool/). - * - * @constructor - * @extends {Tone.Effect} - * @param {Frequency|Object} [frequency] Rate of left-right oscillation. - * @example - * //create an autopanner and start it's LFO - * var autoPanner = new Tone.AutoPanner("4n").toMaster().start(); - * //route an oscillator through the panner and start it - * var oscillator = new Tone.Oscillator().connect(autoPanner).start(); - */ - Tone.AutoPanner = function () { - var options = this.optionsObject(arguments, ['frequency'], Tone.AutoPanner.defaults); - Tone.Effect.call(this, options); - /** - * the lfo which drives the panning - * @type {Tone.LFO} - * @private - */ - this._lfo = new Tone.LFO({ - 'frequency': options.frequency, - 'amplitude': options.depth, - 'min': -1, - 'max': 1 - }); - /** - * The amount of panning between left and right. - * 0 = always center. 1 = full range between left and right. - * @type {NormalRange} - * @signal - */ - this.depth = this._lfo.amplitude; - /** - * the panner node which does the panning - * @type {Tone.Panner} - * @private - */ - this._panner = new Tone.Panner(); - /** - * How fast the panner modulates between left and right. - * @type {Frequency} - * @signal - */ - this.frequency = this._lfo.frequency; - //connections - this.connectEffect(this._panner); - this._lfo.connect(this._panner.pan); - this.type = options.type; - this._readOnly([ - 'depth', - 'frequency' - ]); - }; - //extend Effect - Tone.extend(Tone.AutoPanner, Tone.Effect); - /** - * defaults - * @static - * @type {Object} - */ - Tone.AutoPanner.defaults = { - 'frequency': 1, - 'type': 'sine', - 'depth': 1 - }; - /** - * Start the effect. - * @param {Time} [time=now] When the LFO will start. - * @returns {Tone.AutoPanner} this - */ - Tone.AutoPanner.prototype.start = function (time) { - this._lfo.start(time); - return this; - }; - /** - * Stop the effect. - * @param {Time} [time=now] When the LFO will stop. - * @returns {Tone.AutoPanner} this - */ - Tone.AutoPanner.prototype.stop = function (time) { - this._lfo.stop(time); - return this; - }; - /** - * Sync the panner to the transport. - * @param {Time} [delay=0] Delay time before starting the effect after the - * Transport has started. - * @returns {Tone.AutoPanner} this - */ - Tone.AutoPanner.prototype.sync = function (delay) { - this._lfo.sync(delay); - return this; - }; - /** - * Unsync the panner from the transport - * @returns {Tone.AutoPanner} this - */ - Tone.AutoPanner.prototype.unsync = function () { - this._lfo.unsync(); - return this; - }; - /** - * Type of oscillator attached to the AutoFilter. - * Possible values: "sine", "square", "triangle", "sawtooth". - * @memberOf Tone.AutoFilter# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.AutoPanner.prototype, 'type', { - get: function () { - return this._lfo.type; - }, - set: function (type) { - this._lfo.type = type; - } - }); - /** - * clean up - * @returns {Tone.AutoPanner} this - */ - Tone.AutoPanner.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._lfo.dispose(); - this._lfo = null; - this._panner.dispose(); - this._panner = null; - this._writable([ - 'depth', - 'frequency' - ]); - this.frequency = null; - this.depth = null; - return this; - }; - return Tone.AutoPanner; - }); - Module(function (Tone) { - - /** - * @class Tone.AutoWah connects a Tone.Follower to a bandpass filter (Tone.Filter). - * The frequency of the filter is adjusted proportionally to the - * incoming signal's amplitude. Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna). - * - * @constructor - * @extends {Tone.Effect} - * @param {Frequency|Object} [baseFrequency] The frequency the filter is set - * to at the low point of the wah - * @param {Positive} [octaves] The number of octaves above the baseFrequency - * the filter will sweep to when fully open - * @param {Decibels} [sensitivity] The decibel threshold sensitivity for - * the incoming signal. Normal range of -40 to 0. - * @example - * var autoWah = new Tone.AutoWah(50, 6, -30).toMaster(); - * //initialize the synth and connect to autowah - * var synth = new Synth.connect(autoWah); - * //Q value influences the effect of the wah - default is 2 - * autoWah.Q.value = 6; - * //more audible on higher notes - * synth.triggerAttackRelease("C4", "8n") - */ - Tone.AutoWah = function () { - var options = this.optionsObject(arguments, [ - 'baseFrequency', - 'octaves', - 'sensitivity' - ], Tone.AutoWah.defaults); - Tone.Effect.call(this, options); - /** - * The envelope follower. Set the attack/release - * timing to adjust how the envelope is followed. - * @type {Tone.Follower} - * @private - */ - this.follower = new Tone.Follower(options.follower); - /** - * scales the follower value to the frequency domain - * @type {Tone} - * @private - */ - this._sweepRange = new Tone.ScaleExp(0, 1, 0.5); - /** - * @type {number} - * @private - */ - this._baseFrequency = options.baseFrequency; - /** - * @type {number} - * @private - */ - this._octaves = options.octaves; - /** - * the input gain to adjust the sensitivity - * @type {Tone.Gain} - * @private - */ - this._inputBoost = new Tone.Gain(); - /** - * @type {BiquadFilterNode} - * @private - */ - this._bandpass = new Tone.Filter({ - 'rolloff': -48, - 'frequency': 0, - 'Q': options.Q - }); - /** - * @type {Tone.Filter} - * @private - */ - this._peaking = new Tone.Filter(0, 'peaking'); - this._peaking.gain.value = options.gain; - /** - * The gain of the filter. - * @type {Number} - * @signal - */ - this.gain = this._peaking.gain; - /** - * The quality of the filter. - * @type {Positive} - * @signal - */ - this.Q = this._bandpass.Q; - //the control signal path - this.effectSend.chain(this._inputBoost, this.follower, this._sweepRange); - this._sweepRange.connect(this._bandpass.frequency); - this._sweepRange.connect(this._peaking.frequency); - //the filtered path - this.effectSend.chain(this._bandpass, this._peaking, this.effectReturn); - //set the initial value - this._setSweepRange(); - this.sensitivity = options.sensitivity; - this._readOnly([ - 'gain', - 'Q' - ]); - }; - Tone.extend(Tone.AutoWah, Tone.Effect); - /** - * @static - * @type {Object} - */ - Tone.AutoWah.defaults = { - 'baseFrequency': 100, - 'octaves': 6, - 'sensitivity': 0, - 'Q': 2, - 'gain': 2, - 'follower': { - 'attack': 0.3, - 'release': 0.5 - } - }; - /** - * The number of octaves that the filter will sweep above the - * baseFrequency. - * @memberOf Tone.AutoWah# - * @type {Number} - * @name octaves - */ - Object.defineProperty(Tone.AutoWah.prototype, 'octaves', { - get: function () { - return this._octaves; - }, - set: function (octaves) { - this._octaves = octaves; - this._setSweepRange(); - } - }); - /** - * The base frequency from which the sweep will start from. - * @memberOf Tone.AutoWah# - * @type {Frequency} - * @name baseFrequency - */ - Object.defineProperty(Tone.AutoWah.prototype, 'baseFrequency', { - get: function () { - return this._baseFrequency; - }, - set: function (baseFreq) { - this._baseFrequency = baseFreq; - this._setSweepRange(); - } - }); - /** - * The sensitivity to control how responsive to the input signal the filter is. - * @memberOf Tone.AutoWah# - * @type {Decibels} - * @name sensitivity - */ - Object.defineProperty(Tone.AutoWah.prototype, 'sensitivity', { - get: function () { - return this.gainToDb(1 / this._inputBoost.gain.value); - }, - set: function (sensitivy) { - this._inputBoost.gain.value = 1 / this.dbToGain(sensitivy); - } - }); - /** - * sets the sweep range of the scaler - * @private - */ - Tone.AutoWah.prototype._setSweepRange = function () { - this._sweepRange.min = this._baseFrequency; - this._sweepRange.max = Math.min(this._baseFrequency * Math.pow(2, this._octaves), this.context.sampleRate / 2); - }; - /** - * Clean up. - * @returns {Tone.AutoWah} this - */ - Tone.AutoWah.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this.follower.dispose(); - this.follower = null; - this._sweepRange.dispose(); - this._sweepRange = null; - this._bandpass.dispose(); - this._bandpass = null; - this._peaking.dispose(); - this._peaking = null; - this._inputBoost.dispose(); - this._inputBoost = null; - this._writable([ - 'gain', - 'Q' - ]); - this.gain = null; - this.Q = null; - return this; - }; - return Tone.AutoWah; - }); - Module(function (Tone) { - - /** - * @class Tone.Bitcrusher downsamples the incoming signal to a different bitdepth. - * Lowering the bitdepth of the signal creates distortion. Read more about Bitcrushing - * on [Wikipedia](https://en.wikipedia.org/wiki/Bitcrusher). - * - * @constructor - * @extends {Tone.Effect} - * @param {Number} bits The number of bits to downsample the signal. Nominal range - * of 1 to 8. - * @example - * //initialize crusher and route a synth through it - * var crusher = new Tone.BitCrusher(4).toMaster(); - * var synth = new Tone.MonoSynth().connect(crusher); - */ - Tone.BitCrusher = function () { - var options = this.optionsObject(arguments, ['bits'], Tone.BitCrusher.defaults); - Tone.Effect.call(this, options); - var invStepSize = 1 / Math.pow(2, options.bits - 1); - /** - * Subtract the input signal and the modulus of the input signal - * @type {Tone.Subtract} - * @private - */ - this._subtract = new Tone.Subtract(); - /** - * The mod function - * @type {Tone.Modulo} - * @private - */ - this._modulo = new Tone.Modulo(invStepSize); - /** - * keeps track of the bits - * @type {number} - * @private - */ - this._bits = options.bits; - //connect it up - this.effectSend.fan(this._subtract, this._modulo); - this._modulo.connect(this._subtract, 0, 1); - this._subtract.connect(this.effectReturn); - }; - Tone.extend(Tone.BitCrusher, Tone.Effect); - /** - * the default values - * @static - * @type {Object} - */ - Tone.BitCrusher.defaults = { 'bits': 4 }; - /** - * The bit depth of the effect. Nominal range of 1-8. - * @memberOf Tone.BitCrusher# - * @type {number} - * @name bits - */ - Object.defineProperty(Tone.BitCrusher.prototype, 'bits', { - get: function () { - return this._bits; - }, - set: function (bits) { - this._bits = bits; - var invStepSize = 1 / Math.pow(2, bits - 1); - this._modulo.value = invStepSize; - } - }); - /** - * Clean up. - * @returns {Tone.BitCrusher} this - */ - Tone.BitCrusher.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._subtract.dispose(); - this._subtract = null; - this._modulo.dispose(); - this._modulo = null; - return this; - }; - return Tone.BitCrusher; - }); - Module(function (Tone) { - - /** - * @class Tone.ChebyShev is a Chebyshev waveshaper, an effect which is good - * for making different types of distortion sounds. - * Note that odd orders sound very different from even ones, - * and order = 1 is no change. - * Read more at [music.columbia.edu](http://music.columbia.edu/cmc/musicandcomputers/chapter4/04_06.php). - * - * @extends {Tone.Effect} - * @constructor - * @param {Positive|Object} [order] The order of the chebyshev polynomial. Normal range between 1-100. - * @example - * //create a new cheby - * var cheby = new Tone.Chebyshev(50); - * //create a monosynth connected to our cheby - * synth = new Tone.MonoSynth().connect(cheby); - */ - Tone.Chebyshev = function () { - var options = this.optionsObject(arguments, ['order'], Tone.Chebyshev.defaults); - Tone.Effect.call(this, options); - /** - * @type {WaveShaperNode} - * @private - */ - this._shaper = new Tone.WaveShaper(4096); - /** - * holds onto the order of the filter - * @type {number} - * @private - */ - this._order = options.order; - this.connectEffect(this._shaper); - this.order = options.order; - this.oversample = options.oversample; - }; - Tone.extend(Tone.Chebyshev, Tone.Effect); - /** - * @static - * @const - * @type {Object} - */ - Tone.Chebyshev.defaults = { - 'order': 1, - 'oversample': 'none' - }; - /** - * get the coefficient for that degree - * @param {number} x the x value - * @param {number} degree - * @param {Object} memo memoize the computed value. - * this speeds up computation greatly. - * @return {number} the coefficient - * @private - */ - Tone.Chebyshev.prototype._getCoefficient = function (x, degree, memo) { - if (memo.hasOwnProperty(degree)) { - return memo[degree]; - } else if (degree === 0) { - memo[degree] = 0; - } else if (degree === 1) { - memo[degree] = x; - } else { - memo[degree] = 2 * x * this._getCoefficient(x, degree - 1, memo) - this._getCoefficient(x, degree - 2, memo); - } - return memo[degree]; - }; - /** - * The order of the Chebyshev polynomial which creates - * the equation which is applied to the incoming - * signal through a Tone.WaveShaper. The equations - * are in the form:
- * order 2: 2x^2 + 1
- * order 3: 4x^3 + 3x
- * @memberOf Tone.Chebyshev# - * @type {Positive} - * @name order - */ - Object.defineProperty(Tone.Chebyshev.prototype, 'order', { - get: function () { - return this._order; - }, - set: function (order) { - this._order = order; - var curve = new Array(4096); - var len = curve.length; - for (var i = 0; i < len; ++i) { - var x = i * 2 / len - 1; - if (x === 0) { - //should output 0 when input is 0 - curve[i] = 0; - } else { - curve[i] = this._getCoefficient(x, order, {}); - } - } - this._shaper.curve = curve; - } - }); - /** - * The oversampling of the effect. Can either be "none", "2x" or "4x". - * @memberOf Tone.Chebyshev# - * @type {string} - * @name oversample - */ - Object.defineProperty(Tone.Chebyshev.prototype, 'oversample', { - get: function () { - return this._shaper.oversample; - }, - set: function (oversampling) { - this._shaper.oversample = oversampling; - } - }); - /** - * Clean up. - * @returns {Tone.Chebyshev} this - */ - Tone.Chebyshev.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._shaper.dispose(); - this._shaper = null; - return this; - }; - return Tone.Chebyshev; - }); - Module(function (Tone) { - - /** - * @class Base class for Stereo effects. Provides effectSendL/R and effectReturnL/R. - * - * @constructor - * @extends {Tone.Effect} - */ - Tone.StereoEffect = function () { - this.createInsOuts(1, 1); - //get the defaults - var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); - /** - * the drywet knob to control the amount of effect - * @type {Tone.CrossFade} - * @private - */ - this._dryWet = new Tone.CrossFade(options.wet); - /** - * The wet control, i.e. how much of the effected - * will pass through to the output. - * @type {NormalRange} - * @signal - */ - this.wet = this._dryWet.fade; - /** - * then split it - * @type {Tone.Split} - * @private - */ - this._split = new Tone.Split(); - /** - * the effects send LEFT - * @type {GainNode} - * @private - */ - this.effectSendL = this._split.left; - /** - * the effects send RIGHT - * @type {GainNode} - * @private - */ - this.effectSendR = this._split.right; - /** - * the stereo effect merger - * @type {Tone.Merge} - * @private - */ - this._merge = new Tone.Merge(); - /** - * the effect return LEFT - * @type {GainNode} - * @private - */ - this.effectReturnL = this._merge.left; - /** - * the effect return RIGHT - * @type {GainNode} - * @private - */ - this.effectReturnR = this._merge.right; - //connections - this.input.connect(this._split); - //dry wet connections - this.input.connect(this._dryWet, 0, 0); - this._merge.connect(this._dryWet, 0, 1); - this._dryWet.connect(this.output); - this._readOnly(['wet']); - }; - Tone.extend(Tone.StereoEffect, Tone.Effect); - /** - * Clean up. - * @returns {Tone.StereoEffect} this - */ - Tone.StereoEffect.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._dryWet.dispose(); - this._dryWet = null; - this._split.dispose(); - this._split = null; - this._merge.dispose(); - this._merge = null; - this.effectSendL = null; - this.effectSendR = null; - this.effectReturnL = null; - this.effectReturnR = null; - this._writable(['wet']); - this.wet = null; - return this; - }; - return Tone.StereoEffect; - }); - Module(function (Tone) { - - /** - * @class Tone.FeedbackEffect provides a loop between an - * audio source and its own output. This is a base-class - * for feedback effects. - * - * @constructor - * @extends {Tone.Effect} - * @param {NormalRange|Object} [feedback] The initial feedback value. - */ - Tone.FeedbackEffect = function () { - var options = this.optionsObject(arguments, ['feedback']); - options = this.defaultArg(options, Tone.FeedbackEffect.defaults); - Tone.Effect.call(this, options); - /** - * the gain which controls the feedback - * @type {Tone.Gain} - * @private - */ - this._feedbackGain = new Tone.Gain(options.feedback, Tone.Type.NormalRange); - /** - * The amount of signal which is fed back into the effect input. - * @type {NormalRange} - * @signal - */ - this.feedback = this._feedbackGain.gain; - //the feedback loop - this.effectReturn.chain(this._feedbackGain, this.effectSend); - this._readOnly(['feedback']); - }; - Tone.extend(Tone.FeedbackEffect, Tone.Effect); - /** - * @static - * @type {Object} - */ - Tone.FeedbackEffect.defaults = { 'feedback': 0.125 }; - /** - * Clean up. - * @returns {Tone.FeedbackEffect} this - */ - Tone.FeedbackEffect.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._writable(['feedback']); - this._feedbackGain.dispose(); - this._feedbackGain = null; - this.feedback = null; - return this; - }; - return Tone.FeedbackEffect; - }); - Module(function (Tone) { - - /** - * @class Just like a stereo feedback effect, but the feedback is routed from left to right - * and right to left instead of on the same channel. - * - * @constructor - * @extends {Tone.FeedbackEffect} - */ - Tone.StereoXFeedbackEffect = function () { - var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); - Tone.StereoEffect.call(this, options); - /** - * The amount of feedback from the output - * back into the input of the effect (routed - * across left and right channels). - * @type {NormalRange} - * @signal - */ - this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); - /** - * the left side feeback - * @type {Tone.Gain} - * @private - */ - this._feedbackLR = new Tone.Gain(); - /** - * the right side feeback - * @type {Tone.Gain} - * @private - */ - this._feedbackRL = new Tone.Gain(); - //connect it up - this.effectReturnL.chain(this._feedbackLR, this.effectSendR); - this.effectReturnR.chain(this._feedbackRL, this.effectSendL); - this.feedback.fan(this._feedbackLR.gain, this._feedbackRL.gain); - this._readOnly(['feedback']); - }; - Tone.extend(Tone.StereoXFeedbackEffect, Tone.FeedbackEffect); - /** - * clean up - * @returns {Tone.StereoXFeedbackEffect} this - */ - Tone.StereoXFeedbackEffect.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - this._writable(['feedback']); - this.feedback.dispose(); - this.feedback = null; - this._feedbackLR.dispose(); - this._feedbackLR = null; - this._feedbackRL.dispose(); - this._feedbackRL = null; - return this; - }; - return Tone.StereoXFeedbackEffect; - }); - Module(function (Tone) { - - /** - * @class Tone.Chorus is a stereo chorus effect with feedback composed of - * a left and right delay with a Tone.LFO applied to the delayTime of each channel. - * Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna/blob/master/tuna.js). - * Read more on the chorus effect on [SoundOnSound](http://www.soundonsound.com/sos/jun04/articles/synthsecrets.htm). - * - * @constructor - * @extends {Tone.StereoXFeedbackEffect} - * @param {Frequency|Object} [frequency] The frequency of the LFO. - * @param {Milliseconds} [delayTime] The delay of the chorus effect in ms. - * @param {NormalRange} [depth] The depth of the chorus. - * @example - * var chorus = new Tone.Chorus(4, 2.5, 0.5); - * var synth = new Tone.PolySynth(4, Tone.MonoSynth).connect(chorus); - * synth.triggerAttackRelease(["C3","E3","G3"], "8n"); - */ - Tone.Chorus = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'delayTime', - 'depth' - ], Tone.Chorus.defaults); - Tone.StereoXFeedbackEffect.call(this, options); - /** - * the depth of the chorus - * @type {number} - * @private - */ - this._depth = options.depth; - /** - * the delayTime - * @type {number} - * @private - */ - this._delayTime = options.delayTime / 1000; - /** - * the lfo which controls the delayTime - * @type {Tone.LFO} - * @private - */ - this._lfoL = new Tone.LFO({ - 'frequency': options.frequency, - 'min': 0, - 'max': 1 - }); - /** - * another LFO for the right side with a 180 degree phase diff - * @type {Tone.LFO} - * @private - */ - this._lfoR = new Tone.LFO({ - 'frequency': options.frequency, - 'min': 0, - 'max': 1, - 'phase': 180 - }); - /** - * delay for left - * @type {Tone.Delay} - * @private - */ - this._delayNodeL = new Tone.Delay(); - /** - * delay for right - * @type {Tone.Delay} - * @private - */ - this._delayNodeR = new Tone.Delay(); - /** - * The frequency of the LFO which modulates the delayTime. - * @type {Frequency} - * @signal - */ - this.frequency = this._lfoL.frequency; - //connections - this.effectSendL.chain(this._delayNodeL, this.effectReturnL); - this.effectSendR.chain(this._delayNodeR, this.effectReturnR); - //and pass through to make the detune apparent - this.effectSendL.connect(this.effectReturnL); - this.effectSendR.connect(this.effectReturnR); - //lfo setup - this._lfoL.connect(this._delayNodeL.delayTime); - this._lfoR.connect(this._delayNodeR.delayTime); - //start the lfo - this._lfoL.start(); - this._lfoR.start(); - //have one LFO frequency control the other - this._lfoL.frequency.connect(this._lfoR.frequency); - //set the initial values - this.depth = this._depth; - this.frequency.value = options.frequency; - this.type = options.type; - this._readOnly(['frequency']); - this.spread = options.spread; - }; - Tone.extend(Tone.Chorus, Tone.StereoXFeedbackEffect); - /** - * @static - * @type {Object} - */ - Tone.Chorus.defaults = { - 'frequency': 1.5, - 'delayTime': 3.5, - 'depth': 0.7, - 'feedback': 0.1, - 'type': 'sine', - 'spread': 180 - }; - /** - * The depth of the effect. A depth of 1 makes the delayTime - * modulate between 0 and 2*delayTime (centered around the delayTime). - * @memberOf Tone.Chorus# - * @type {NormalRange} - * @name depth - */ - Object.defineProperty(Tone.Chorus.prototype, 'depth', { - get: function () { - return this._depth; - }, - set: function (depth) { - this._depth = depth; - var deviation = this._delayTime * depth; - this._lfoL.min = Math.max(this._delayTime - deviation, 0); - this._lfoL.max = this._delayTime + deviation; - this._lfoR.min = Math.max(this._delayTime - deviation, 0); - this._lfoR.max = this._delayTime + deviation; - } - }); - /** - * The delayTime in milliseconds of the chorus. A larger delayTime - * will give a more pronounced effect. Nominal range a delayTime - * is between 2 and 20ms. - * @memberOf Tone.Chorus# - * @type {Milliseconds} - * @name delayTime - */ - Object.defineProperty(Tone.Chorus.prototype, 'delayTime', { - get: function () { - return this._delayTime * 1000; - }, - set: function (delayTime) { - this._delayTime = delayTime / 1000; - this.depth = this._depth; - } - }); - /** - * The oscillator type of the LFO. - * @memberOf Tone.Chorus# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.Chorus.prototype, 'type', { - get: function () { - return this._lfoL.type; - }, - set: function (type) { - this._lfoL.type = type; - this._lfoR.type = type; - } - }); - /** - * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. - * When set to 180, LFO's will be panned hard left and right respectively. - * @memberOf Tone.Chorus# - * @type {Degrees} - * @name spread - */ - Object.defineProperty(Tone.Chorus.prototype, 'spread', { - get: function () { - return this._lfoR.phase - this._lfoL.phase; //180 - }, - set: function (spread) { - this._lfoL.phase = 90 - spread / 2; - this._lfoR.phase = spread / 2 + 90; - } - }); - /** - * Clean up. - * @returns {Tone.Chorus} this - */ - Tone.Chorus.prototype.dispose = function () { - Tone.StereoXFeedbackEffect.prototype.dispose.call(this); - this._lfoL.dispose(); - this._lfoL = null; - this._lfoR.dispose(); - this._lfoR = null; - this._delayNodeL.dispose(); - this._delayNodeL = null; - this._delayNodeR.dispose(); - this._delayNodeR = null; - this._writable('frequency'); - this.frequency = null; - return this; - }; - return Tone.Chorus; - }); - Module(function (Tone) { - - /** - * @class Tone.Convolver is a wrapper around the Native Web Audio - * [ConvolverNode](http://webaudio.github.io/web-audio-api/#the-convolvernode-interface). - * Convolution is useful for reverb and filter emulation. Read more about convolution reverb on - * [Wikipedia](https://en.wikipedia.org/wiki/Convolution_reverb). - * - * @constructor - * @extends {Tone.Effect} - * @param {string|Tone.Buffer|Object} [url] The URL of the impulse response or the Tone.Buffer - * contianing the impulse response. - * @param {Function} onload The callback to invoke when the url is loaded. - * @example - * //initializing the convolver with an impulse response - * var convolver = new Tone.Convolver("./path/to/ir.wav").toMaster(); - */ - Tone.Convolver = function () { - var options = this.optionsObject(arguments, [ - 'url', - 'onload' - ], Tone.Convolver.defaults); - Tone.Effect.call(this, options); - /** - * convolver node - * @type {ConvolverNode} - * @private - */ - this._convolver = this.context.createConvolver(); - /** - * the convolution buffer - * @type {Tone.Buffer} - * @private - */ - this._buffer = new Tone.Buffer(); - if (this.isString(options.url)) { - this._buffer.load(options.url, function (buffer) { - this.buffer = buffer; - options.onload(); - }.bind(this)); - } else if (options.url) { - this.buffer = options.url; - options.onload(); - } - this.connectEffect(this._convolver); - }; - Tone.extend(Tone.Convolver, Tone.Effect); - /** - * @static - * @const - * @type {Object} - */ - Tone.Convolver.defaults = { 'onload': Tone.noOp }; - /** - * The convolver's buffer - * @memberOf Tone.Convolver# - * @type {AudioBuffer} - * @name buffer - */ - Object.defineProperty(Tone.Convolver.prototype, 'buffer', { - get: function () { - return this._buffer.get(); - }, - set: function (buffer) { - this._buffer.set(buffer); - this._convolver.buffer = this._buffer.get(); - } - }); - /** - * Load an impulse response url as an audio buffer. - * Decodes the audio asynchronously and invokes - * the callback once the audio buffer loads. - * @param {string} url The url of the buffer to load. - * filetype support depends on the - * browser. - * @param {function=} callback - * @returns {Promise} - */ - Tone.Convolver.prototype.load = function (url, callback) { - return this._buffer.load(url, function (buff) { - this.buffer = buff; - if (callback) { - callback(); - } - }.bind(this)); - }; - /** - * Clean up. - * @returns {Tone.Convolver} this - */ - Tone.Convolver.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._convolver.disconnect(); - this._convolver = null; - this._buffer.dispose(); - this._buffer = null; - return this; - }; - return Tone.Convolver; - }); - Module(function (Tone) { - - /** - * @class Tone.Distortion is a simple distortion effect using Tone.WaveShaper. - * Algorithm from [a stackoverflow answer](http://stackoverflow.com/a/22313408). - * - * @extends {Tone.Effect} - * @constructor - * @param {Number|Object} [distortion] The amount of distortion (nominal range of 0-1) - * @example - * var dist = new Tone.Distortion(0.8).toMaster(); - * var fm = new Tone.SimpleFM().connect(dist); - * //this sounds good on bass notes - * fm.triggerAttackRelease("A1", "8n"); - */ - Tone.Distortion = function () { - var options = this.optionsObject(arguments, ['distortion'], Tone.Distortion.defaults); - Tone.Effect.call(this, options); - /** - * @type {Tone.WaveShaper} - * @private - */ - this._shaper = new Tone.WaveShaper(4096); - /** - * holds the distortion amount - * @type {number} - * @private - */ - this._distortion = options.distortion; - this.connectEffect(this._shaper); - this.distortion = options.distortion; - this.oversample = options.oversample; - }; - Tone.extend(Tone.Distortion, Tone.Effect); - /** - * @static - * @const - * @type {Object} - */ - Tone.Distortion.defaults = { - 'distortion': 0.4, - 'oversample': 'none' - }; - /** - * The amount of distortion. - * @memberOf Tone.Distortion# - * @type {NormalRange} - * @name distortion - */ - Object.defineProperty(Tone.Distortion.prototype, 'distortion', { - get: function () { - return this._distortion; - }, - set: function (amount) { - this._distortion = amount; - var k = amount * 100; - var deg = Math.PI / 180; - this._shaper.setMap(function (x) { - if (Math.abs(x) < 0.001) { - //should output 0 when input is 0 - return 0; - } else { - return (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); - } - }); - } - }); - /** - * The oversampling of the effect. Can either be "none", "2x" or "4x". - * @memberOf Tone.Distortion# - * @type {string} - * @name oversample - */ - Object.defineProperty(Tone.Distortion.prototype, 'oversample', { - get: function () { - return this._shaper.oversample; - }, - set: function (oversampling) { - this._shaper.oversample = oversampling; - } - }); - /** - * Clean up. - * @returns {Tone.Distortion} this - */ - Tone.Distortion.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._shaper.dispose(); - this._shaper = null; - return this; - }; - return Tone.Distortion; - }); - Module(function (Tone) { - - /** - * @class Tone.FeedbackDelay is a DelayNode in which part of output - * signal is fed back into the delay. - * - * @constructor - * @extends {Tone.FeedbackEffect} - * @param {Time|Object} [delayTime] The delay applied to the incoming signal. - * @param {NormalRange=} feedback The amount of the effected signal which - * is fed back through the delay. - * @example - * var feedbackDelay = new Tone.FeedbackDelay("8n", 0.5).toMaster(); - * var tom = new Tone.DrumSynth({ - * "octaves" : 4, - * "pitchDecay" : 0.1 - * }).connect(feedbackDelay); - * tom.triggerAttackRelease("A2","32n"); - */ - Tone.FeedbackDelay = function () { - var options = this.optionsObject(arguments, [ - 'delayTime', - 'feedback' - ], Tone.FeedbackDelay.defaults); - Tone.FeedbackEffect.call(this, options); - /** - * the delay node - * @type {Tone.Delay} - * @private - */ - this._delayNode = new Tone.Delay(options.delayTime); - /** - * The delayTime of the DelayNode. - * @type {Time} - * @signal - */ - this.delayTime = this._delayNode.delayTime; - // connect it up - this.connectEffect(this._delayNode); - this._readOnly(['delayTime']); - }; - Tone.extend(Tone.FeedbackDelay, Tone.FeedbackEffect); - /** - * The default values. - * @const - * @static - * @type {Object} - */ - Tone.FeedbackDelay.defaults = { 'delayTime': 0.25 }; - /** - * clean up - * @returns {Tone.FeedbackDelay} this - */ - Tone.FeedbackDelay.prototype.dispose = function () { - Tone.FeedbackEffect.prototype.dispose.call(this); - this._delayNode.dispose(); - this._delayNode = null; - this._writable(['delayTime']); - this.delayTime = null; - return this; - }; - return Tone.FeedbackDelay; - }); - Module(function (Tone) { - - /** - * an array of comb filter delay values from Freeverb implementation - * @static - * @private - * @type {Array} - */ - var combFilterTunings = [ - 1557 / 44100, - 1617 / 44100, - 1491 / 44100, - 1422 / 44100, - 1277 / 44100, - 1356 / 44100, - 1188 / 44100, - 1116 / 44100 - ]; - /** - * an array of allpass filter frequency values from Freeverb implementation - * @private - * @static - * @type {Array} - */ - var allpassFilterFrequencies = [ - 225, - 556, - 441, - 341 - ]; - /** - * @class Tone.Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html). - * Read more on reverb on [SoundOnSound](http://www.soundonsound.com/sos/may00/articles/reverb.htm). - * - * @extends {Tone.Effect} - * @constructor - * @param {NormalRange|Object} [roomSize] Correlated to the decay time. - * @param {Frequency} [dampening] The cutoff frequency of a lowpass filter as part - * of the reverb. - * @example - * var freeverb = new Tone.Freeverb().toMaster(); - * freeverb.dampening.value = 1000; - * //routing synth through the reverb - * var synth = new Tone.AMSynth().connect(freeverb); - */ - Tone.Freeverb = function () { - var options = this.optionsObject(arguments, [ - 'roomSize', - 'dampening' - ], Tone.Freeverb.defaults); - Tone.StereoEffect.call(this, options); - /** - * The roomSize value between. A larger roomSize - * will result in a longer decay. - * @type {NormalRange} - * @signal - */ - this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); - /** - * The amount of dampening of the reverberant signal. - * @type {Frequency} - * @signal - */ - this.dampening = new Tone.Signal(options.dampening, Tone.Type.Frequency); - /** - * the comb filters - * @type {Array} - * @private - */ - this._combFilters = []; - /** - * the allpass filters on the left - * @type {Array} - * @private - */ - this._allpassFiltersL = []; - /** - * the allpass filters on the right - * @type {Array} - * @private - */ - this._allpassFiltersR = []; - //make the allpass filters on the right - for (var l = 0; l < allpassFilterFrequencies.length; l++) { - var allpassL = this.context.createBiquadFilter(); - allpassL.type = 'allpass'; - allpassL.frequency.value = allpassFilterFrequencies[l]; - this._allpassFiltersL.push(allpassL); - } - //make the allpass filters on the left - for (var r = 0; r < allpassFilterFrequencies.length; r++) { - var allpassR = this.context.createBiquadFilter(); - allpassR.type = 'allpass'; - allpassR.frequency.value = allpassFilterFrequencies[r]; - this._allpassFiltersR.push(allpassR); - } - //make the comb filters - for (var c = 0; c < combFilterTunings.length; c++) { - var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]); - if (c < combFilterTunings.length / 2) { - this.effectSendL.chain(lfpf, this._allpassFiltersL[0]); - } else { - this.effectSendR.chain(lfpf, this._allpassFiltersR[0]); - } - this.roomSize.connect(lfpf.resonance); - this.dampening.connect(lfpf.dampening); - this._combFilters.push(lfpf); - } - //chain the allpass filters togetehr - this.connectSeries.apply(this, this._allpassFiltersL); - this.connectSeries.apply(this, this._allpassFiltersR); - this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL); - this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR); - this._readOnly([ - 'roomSize', - 'dampening' - ]); - }; - Tone.extend(Tone.Freeverb, Tone.StereoEffect); - /** - * @static - * @type {Object} - */ - Tone.Freeverb.defaults = { - 'roomSize': 0.7, - 'dampening': 3000 - }; - /** - * Clean up. - * @returns {Tone.Freeverb} this - */ - Tone.Freeverb.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - for (var al = 0; al < this._allpassFiltersL.length; al++) { - this._allpassFiltersL[al].disconnect(); - this._allpassFiltersL[al] = null; - } - this._allpassFiltersL = null; - for (var ar = 0; ar < this._allpassFiltersR.length; ar++) { - this._allpassFiltersR[ar].disconnect(); - this._allpassFiltersR[ar] = null; - } - this._allpassFiltersR = null; - for (var cf = 0; cf < this._combFilters.length; cf++) { - this._combFilters[cf].dispose(); - this._combFilters[cf] = null; - } - this._combFilters = null; - this._writable([ - 'roomSize', - 'dampening' - ]); - this.roomSize.dispose(); - this.roomSize = null; - this.dampening.dispose(); - this.dampening = null; - return this; - }; - return Tone.Freeverb; - }); - Module(function (Tone) { - - /** - * an array of the comb filter delay time values - * @private - * @static - * @type {Array} - */ - var combFilterDelayTimes = [ - 1687 / 25000, - 1601 / 25000, - 2053 / 25000, - 2251 / 25000 - ]; - /** - * the resonances of each of the comb filters - * @private - * @static - * @type {Array} - */ - var combFilterResonances = [ - 0.773, - 0.802, - 0.753, - 0.733 - ]; - /** - * the allpass filter frequencies - * @private - * @static - * @type {Array} - */ - var allpassFilterFreqs = [ - 347, - 113, - 37 - ]; - /** - * @class Tone.JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html) - * tuned by John Chowning in 1970. - * It is made up of three allpass filters and four Tone.FeedbackCombFilter. - * - * - * @extends {Tone.Effect} - * @constructor - * @param {NormalRange|Object} [roomSize] Coorelates to the decay time. - * @example - * var reverb = new Tone.JCReverb(0.4).connect(Tone.Master); - * var delay = new Tone.FeedbackDelay(0.5); - * //connecting the synth to reverb through delay - * var synth = new Tone.DuoSynth().chain(delay, reverb); - * synth.triggerAttackRelease("A4","8n"); - */ - Tone.JCReverb = function () { - var options = this.optionsObject(arguments, ['roomSize'], Tone.JCReverb.defaults); - Tone.StereoEffect.call(this, options); - /** - * room size control values between [0,1] - * @type {NormalRange} - * @signal - */ - this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); - /** - * scale the room size - * @type {Tone.Scale} - * @private - */ - this._scaleRoomSize = new Tone.Scale(-0.733, 0.197); - /** - * a series of allpass filters - * @type {Array} - * @private - */ - this._allpassFilters = []; - /** - * parallel feedback comb filters - * @type {Array} - * @private - */ - this._feedbackCombFilters = []; - //make the allpass filters - for (var af = 0; af < allpassFilterFreqs.length; af++) { - var allpass = this.context.createBiquadFilter(); - allpass.type = 'allpass'; - allpass.frequency.value = allpassFilterFreqs[af]; - this._allpassFilters.push(allpass); - } - //and the comb filters - for (var cf = 0; cf < combFilterDelayTimes.length; cf++) { - var fbcf = new Tone.FeedbackCombFilter(combFilterDelayTimes[cf], 0.1); - this._scaleRoomSize.connect(fbcf.resonance); - fbcf.resonance.value = combFilterResonances[cf]; - this._allpassFilters[this._allpassFilters.length - 1].connect(fbcf); - if (cf < combFilterDelayTimes.length / 2) { - fbcf.connect(this.effectReturnL); - } else { - fbcf.connect(this.effectReturnR); - } - this._feedbackCombFilters.push(fbcf); - } - //chain the allpass filters together - this.roomSize.connect(this._scaleRoomSize); - this.connectSeries.apply(this, this._allpassFilters); - this.effectSendL.connect(this._allpassFilters[0]); - this.effectSendR.connect(this._allpassFilters[0]); - this._readOnly(['roomSize']); - }; - Tone.extend(Tone.JCReverb, Tone.StereoEffect); - /** - * the default values - * @static - * @const - * @type {Object} - */ - Tone.JCReverb.defaults = { 'roomSize': 0.5 }; - /** - * Clean up. - * @returns {Tone.JCReverb} this - */ - Tone.JCReverb.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - for (var apf = 0; apf < this._allpassFilters.length; apf++) { - this._allpassFilters[apf].disconnect(); - this._allpassFilters[apf] = null; - } - this._allpassFilters = null; - for (var fbcf = 0; fbcf < this._feedbackCombFilters.length; fbcf++) { - this._feedbackCombFilters[fbcf].dispose(); - this._feedbackCombFilters[fbcf] = null; - } - this._feedbackCombFilters = null; - this._writable(['roomSize']); - this.roomSize.dispose(); - this.roomSize = null; - this._scaleRoomSize.dispose(); - this._scaleRoomSize = null; - return this; - }; - return Tone.JCReverb; - }); - Module(function (Tone) { - - /** - * @class Mid/Side processing separates the the 'mid' signal - * (which comes out of both the left and the right channel) - * and the 'side' (which only comes out of the the side channels) - * and effects them separately before being recombined. - * Applies a Mid/Side seperation and recombination. - * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). - *

- * This is a base-class for Mid/Side Effects. - * - * @extends {Tone.Effect} - * @constructor - */ - Tone.MidSideEffect = function () { - Tone.Effect.apply(this, arguments); - /** - * The mid/side split - * @type {Tone.MidSideSplit} - * @private - */ - this._midSideSplit = new Tone.MidSideSplit(); - /** - * The mid/side merge - * @type {Tone.MidSideMerge} - * @private - */ - this._midSideMerge = new Tone.MidSideMerge(); - /** - * The mid send. Connect to mid processing - * @type {Tone.Expr} - * @private - */ - this.midSend = this._midSideSplit.mid; - /** - * The side send. Connect to side processing - * @type {Tone.Expr} - * @private - */ - this.sideSend = this._midSideSplit.side; - /** - * The mid return connection - * @type {GainNode} - * @private - */ - this.midReturn = this._midSideMerge.mid; - /** - * The side return connection - * @type {GainNode} - * @private - */ - this.sideReturn = this._midSideMerge.side; - //the connections - this.effectSend.connect(this._midSideSplit); - this._midSideMerge.connect(this.effectReturn); - }; - Tone.extend(Tone.MidSideEffect, Tone.Effect); - /** - * Clean up. - * @returns {Tone.MidSideEffect} this - */ - Tone.MidSideEffect.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._midSideSplit.dispose(); - this._midSideSplit = null; - this._midSideMerge.dispose(); - this._midSideMerge = null; - this.midSend = null; - this.sideSend = null; - this.midReturn = null; - this.sideReturn = null; - return this; - }; - return Tone.MidSideEffect; - }); - Module(function (Tone) { - - /** - * @class Tone.Phaser is a phaser effect. Phasers work by changing the phase - * of different frequency components of an incoming signal. Read more on - * [Wikipedia](https://en.wikipedia.org/wiki/Phaser_(effect)). - * Inspiration for this phaser comes from [Tuna.js](https://github.com/Dinahmoe/tuna/). - * - * @extends {Tone.StereoEffect} - * @constructor - * @param {Frequency|Object} [frequency] The speed of the phasing. - * @param {number} [octaves] The octaves of the effect. - * @param {Frequency} [baseFrequency] The base frequency of the filters. - * @example - * var phaser = new Tone.Phaser({ - * "frequency" : 15, - * "octaves" : 5, - * "baseFrequency" : 1000 - * }).toMaster(); - * var synth = new Tone.FMSynth().connect(phaser); - * synth.triggerAttackRelease("E3", "2n"); - */ - Tone.Phaser = function () { - //set the defaults - var options = this.optionsObject(arguments, [ - 'frequency', - 'octaves', - 'baseFrequency' - ], Tone.Phaser.defaults); - Tone.StereoEffect.call(this, options); - /** - * the lfo which controls the frequency on the left side - * @type {Tone.LFO} - * @private - */ - this._lfoL = new Tone.LFO(options.frequency, 0, 1); - /** - * the lfo which controls the frequency on the right side - * @type {Tone.LFO} - * @private - */ - this._lfoR = new Tone.LFO(options.frequency, 0, 1); - this._lfoR.phase = 180; - /** - * the base modulation frequency - * @type {number} - * @private - */ - this._baseFrequency = options.baseFrequency; - /** - * the octaves of the phasing - * @type {number} - * @private - */ - this._octaves = options.octaves; - /** - * The quality factor of the filters - * @type {Positive} - * @signal - */ - this.Q = new Tone.Signal(options.Q, Tone.Type.Positive); - /** - * the array of filters for the left side - * @type {Array} - * @private - */ - this._filtersL = this._makeFilters(options.stages, this._lfoL, this.Q); - /** - * the array of filters for the left side - * @type {Array} - * @private - */ - this._filtersR = this._makeFilters(options.stages, this._lfoR, this.Q); - /** - * the frequency of the effect - * @type {Tone.Signal} - */ - this.frequency = this._lfoL.frequency; - this.frequency.value = options.frequency; - //connect them up - this.effectSendL.connect(this._filtersL[0]); - this.effectSendR.connect(this._filtersR[0]); - this._filtersL[options.stages - 1].connect(this.effectReturnL); - this._filtersR[options.stages - 1].connect(this.effectReturnR); - //control the frequency with one LFO - this._lfoL.frequency.connect(this._lfoR.frequency); - //set the options - this.baseFrequency = options.baseFrequency; - this.octaves = options.octaves; - //start the lfo - this._lfoL.start(); - this._lfoR.start(); - this._readOnly([ - 'frequency', - 'Q' - ]); - }; - Tone.extend(Tone.Phaser, Tone.StereoEffect); - /** - * defaults - * @static - * @type {object} - */ - Tone.Phaser.defaults = { - 'frequency': 0.5, - 'octaves': 3, - 'stages': 10, - 'Q': 10, - 'baseFrequency': 350 - }; - /** - * @param {number} stages - * @returns {Array} the number of filters all connected together - * @private - */ - Tone.Phaser.prototype._makeFilters = function (stages, connectToFreq, Q) { - var filters = new Array(stages); - //make all the filters - for (var i = 0; i < stages; i++) { - var filter = this.context.createBiquadFilter(); - filter.type = 'allpass'; - Q.connect(filter.Q); - connectToFreq.connect(filter.frequency); - filters[i] = filter; - } - this.connectSeries.apply(this, filters); - return filters; - }; - /** - * The number of octaves the phase goes above - * the baseFrequency - * @memberOf Tone.Phaser# - * @type {Positive} - * @name octaves - */ - Object.defineProperty(Tone.Phaser.prototype, 'octaves', { - get: function () { - return this._octaves; - }, - set: function (octaves) { - this._octaves = octaves; - var max = this._baseFrequency * Math.pow(2, octaves); - this._lfoL.max = max; - this._lfoR.max = max; - } - }); - /** - * The the base frequency of the filters. - * @memberOf Tone.Phaser# - * @type {number} - * @name baseFrequency - */ - Object.defineProperty(Tone.Phaser.prototype, 'baseFrequency', { - get: function () { - return this._baseFrequency; - }, - set: function (freq) { - this._baseFrequency = freq; - this._lfoL.min = freq; - this._lfoR.min = freq; - this.octaves = this._octaves; - } - }); - /** - * clean up - * @returns {Tone.Phaser} this - */ - Tone.Phaser.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'Q' - ]); - this.Q.dispose(); - this.Q = null; - this._lfoL.dispose(); - this._lfoL = null; - this._lfoR.dispose(); - this._lfoR = null; - for (var i = 0; i < this._filtersL.length; i++) { - this._filtersL[i].disconnect(); - this._filtersL[i] = null; - } - this._filtersL = null; - for (var j = 0; j < this._filtersR.length; j++) { - this._filtersR[j].disconnect(); - this._filtersR[j] = null; - } - this._filtersR = null; - this.frequency = null; - return this; - }; - return Tone.Phaser; - }); - Module(function (Tone) { - - /** - * @class Tone.PingPongDelay is a feedback delay effect where the echo is heard - * first in one channel and next in the opposite channel. In a stereo - * system these are the right and left channels. - * PingPongDelay in more simplified terms is two Tone.FeedbackDelays - * with independent delay values. Each delay is routed to one channel - * (left or right), and the channel triggered second will always - * trigger at the same interval after the first. - * - * @constructor - * @extends {Tone.StereoXFeedbackEffect} - * @param {Time|Object} [delayTime] The delayTime between consecutive echos. - * @param {NormalRange=} feedback The amount of the effected signal which - * is fed back through the delay. - * @example - * var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster(); - * var drum = new Tone.DrumSynth().connect(pingPong); - * drum.triggerAttackRelease("C4", "32n"); - */ - Tone.PingPongDelay = function () { - var options = this.optionsObject(arguments, [ - 'delayTime', - 'feedback' - ], Tone.PingPongDelay.defaults); - Tone.StereoXFeedbackEffect.call(this, options); - /** - * the delay node on the left side - * @type {Tone.Delay} - * @private - */ - this._leftDelay = new Tone.Delay(0, options.maxDelayTime); - /** - * the delay node on the right side - * @type {Tone.Delay} - * @private - */ - this._rightDelay = new Tone.Delay(0, options.maxDelayTime); - /** - * the predelay on the right side - * @type {Tone.Delay} - * @private - */ - this._rightPreDelay = new Tone.Delay(0, options.maxDelayTime); - /** - * the delay time signal - * @type {Time} - * @signal - */ - this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); - //connect it up - this.effectSendL.chain(this._leftDelay, this.effectReturnL); - this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR); - this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime); - //rearranged the feedback to be after the rightPreDelay - this._feedbackLR.disconnect(); - this._feedbackLR.connect(this._rightDelay); - this._readOnly(['delayTime']); - }; - Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect); - /** - * @static - * @type {Object} - */ - Tone.PingPongDelay.defaults = { - 'delayTime': 0.25, - 'maxDelayTime': 1 - }; - /** - * Clean up. - * @returns {Tone.PingPongDelay} this - */ - Tone.PingPongDelay.prototype.dispose = function () { - Tone.StereoXFeedbackEffect.prototype.dispose.call(this); - this._leftDelay.dispose(); - this._leftDelay = null; - this._rightDelay.dispose(); - this._rightDelay = null; - this._rightPreDelay.dispose(); - this._rightPreDelay = null; - this._writable(['delayTime']); - this.delayTime.dispose(); - this.delayTime = null; - return this; - }; - return Tone.PingPongDelay; - }); - Module(function (Tone) { - - /** - * @class Tone.PitchShift does near-realtime pitch shifting to the incoming signal. - * The effect is achieved by speeding up or slowing down the delayTime - * of a DelayNode using a sawtooth wave. - * Algorithm found in [this pdf](http://dsp-book.narod.ru/soundproc.pdf). - * Additional reference by [Miller Pucket](http://msp.ucsd.edu/techniques/v0.11/book-html/node115.html). - * - * @extends {Tone.FeedbackEffect} - * @param {Interval=} pitch The interval to transpose the incoming signal by. - */ - Tone.PitchShift = function () { - var options = this.optionsObject(arguments, ['pitch'], Tone.PitchShift.defaults); - Tone.FeedbackEffect.call(this, options); - /** - * The pitch signal - * @type {Tone.Signal} - * @private - */ - this._frequency = new Tone.Signal(0); - /** - * Uses two DelayNodes to cover up the jump in - * the sawtooth wave. - * @type {DelayNode} - * @private - */ - this._delayA = new Tone.Delay(0, 1); - /** - * The first LFO. - * @type {Tone.LFO} - * @private - */ - this._lfoA = new Tone.LFO({ - 'min': 0, - 'max': 0.1, - 'type': 'sawtooth' - }).connect(this._delayA.delayTime); - /** - * The second DelayNode - * @type {DelayNode} - * @private - */ - this._delayB = new Tone.Delay(0, 1); - /** - * The first LFO. - * @type {Tone.LFO} - * @private - */ - this._lfoB = new Tone.LFO({ - 'min': 0, - 'max': 0.1, - 'type': 'sawtooth', - 'phase': 180 - }).connect(this._delayB.delayTime); - /** - * Crossfade quickly between the two delay lines - * to cover up the jump in the sawtooth wave - * @type {Tone.CrossFade} - * @private - */ - this._crossFade = new Tone.CrossFade(); - /** - * LFO which alternates between the two - * delay lines to cover up the disparity in the - * sawtooth wave. - * @type {Tone.LFO} - * @private - */ - this._crossFadeLFO = new Tone.LFO({ - 'min': 0, - 'max': 1, - 'type': 'triangle', - 'phase': 90 - }).connect(this._crossFade.fade); - /** - * The delay node - * @type {Tone.Delay} - * @private - */ - this._feedbackDelay = new Tone.Delay(options.delayTime); - /** - * The amount of delay on the input signal - * @type {Time} - * @signal - */ - this.delayTime = this._feedbackDelay.delayTime; - this._readOnly('delayTime'); - /** - * Hold the current pitch - * @type {Number} - * @private - */ - this._pitch = options.pitch; - /** - * Hold the current windowSize - * @type {Number} - * @private - */ - this._windowSize = options.windowSize; - //connect the two delay lines up - this._delayA.connect(this._crossFade.a); - this._delayB.connect(this._crossFade.b); - //connect the frequency - this._frequency.fan(this._lfoA.frequency, this._lfoB.frequency, this._crossFadeLFO.frequency); - //route the input - this.effectSend.fan(this._delayA, this._delayB); - this._crossFade.chain(this._feedbackDelay, this.effectReturn); - //start the LFOs at the same time - var now = this.now(); - this._lfoA.start(now); - this._lfoB.start(now); - this._crossFadeLFO.start(now); - //set the initial value - this.windowSize = this._windowSize; - }; - Tone.extend(Tone.PitchShift, Tone.FeedbackEffect); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.PitchShift.defaults = { - 'pitch': 0, - 'windowSize': 0.1, - 'delayTime': 0, - 'feedback': 0 - }; - /** - * Repitch the incoming signal by some interval (measured - * in semi-tones). - * @memberOf Tone.PitchShift# - * @type {Interval} - * @name pitch - * @example - * pitchShift.pitch = -12; //down one octave - * pitchShift.pitch = 7; //up a fifth - */ - Object.defineProperty(Tone.PitchShift.prototype, 'pitch', { - get: function () { - return this._pitch; - }, - set: function (interval) { - this._pitch = interval; - var factor = 0; - if (interval < 0) { - this._lfoA.min = 0; - this._lfoA.max = this._windowSize; - this._lfoB.min = 0; - this._lfoB.max = this._windowSize; - factor = this.intervalToFrequencyRatio(interval - 1) + 1; - } else { - this._lfoA.min = this._windowSize; - this._lfoA.max = 0; - this._lfoB.min = this._windowSize; - this._lfoB.max = 0; - factor = this.intervalToFrequencyRatio(interval) - 1; - } - this._frequency.value = factor * (1.2 / this._windowSize); - } - }); - /** - * The window size corresponds roughly to the sample length in a looping sampler. - * Smaller values are desirable for a less noticeable delay time of the pitch shifted - * signal, but larger values will result in smoother pitch shifting for larger intervals. - * A nominal range of 0.03 to 0.1 is recommended. - * @memberOf Tone.PitchShift# - * @type {Time} - * @name windowSize - * @example - * pitchShift.windowSize = 0.1; - */ - Object.defineProperty(Tone.PitchShift.prototype, 'windowSize', { - get: function () { - return this._windowSize; - }, - set: function (size) { - this._windowSize = this.toSeconds(size); - this.pitch = this._pitch; - } - }); - /** - * Clean up. - * @return {Tone.PitchShift} this - */ - Tone.PitchShift.prototype.dispose = function () { - Tone.FeedbackEffect.prototype.dispose.call(this); - this._frequency.dispose(); - this._frequency = null; - this._delayA.disconnect(); - this._delayA = null; - this._delayB.disconnect(); - this._delayB = null; - this._lfoA.dispose(); - this._lfoA = null; - this._lfoB.dispose(); - this._lfoB = null; - this._crossFade.dispose(); - this._crossFade = null; - this._crossFadeLFO.dispose(); - this._crossFadeLFO = null; - this._writable('delayTime'); - this._feedbackDelay.dispose(); - this._feedbackDelay = null; - this.delayTime = null; - return this; - }; - return Tone.PitchShift; - }); - Module(function (Tone) { - - /** - * @class Base class for stereo feedback effects where the effectReturn - * is fed back into the same channel. - * - * @constructor - * @extends {Tone.FeedbackEffect} - */ - Tone.StereoFeedbackEffect = function () { - var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); - Tone.StereoEffect.call(this, options); - /** - * controls the amount of feedback - * @type {NormalRange} - * @signal - */ - this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); - /** - * the left side feeback - * @type {Tone.Gain} - * @private - */ - this._feedbackL = new Tone.Gain(); - /** - * the right side feeback - * @type {Tone.Gain} - * @private - */ - this._feedbackR = new Tone.Gain(); - //connect it up - this.effectReturnL.chain(this._feedbackL, this.effectSendL); - this.effectReturnR.chain(this._feedbackR, this.effectSendR); - this.feedback.fan(this._feedbackL.gain, this._feedbackR.gain); - this._readOnly(['feedback']); - }; - Tone.extend(Tone.StereoFeedbackEffect, Tone.FeedbackEffect); - /** - * clean up - * @returns {Tone.StereoFeedbackEffect} this - */ - Tone.StereoFeedbackEffect.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - this._writable(['feedback']); - this.feedback.dispose(); - this.feedback = null; - this._feedbackL.dispose(); - this._feedbackL = null; - this._feedbackR.dispose(); - this._feedbackR = null; - return this; - }; - return Tone.StereoFeedbackEffect; - }); - Module(function (Tone) { - - /** - * @class Applies a width factor to the mid/side seperation. - * 0 is all mid and 1 is all side. - * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). - *

- * - * Mid *= 2*(1-width)
- * Side *= 2*width - *
- * - * @extends {Tone.MidSideEffect} - * @constructor - * @param {NormalRange|Object} [width] The stereo width. A width of 0 is mono and 1 is stereo. 0.5 is no change. - */ - Tone.StereoWidener = function () { - var options = this.optionsObject(arguments, ['width'], Tone.StereoWidener.defaults); - Tone.MidSideEffect.call(this, options); - /** - * The width control. 0 = 100% mid. 1 = 100% side. 0.5 = no change. - * @type {NormalRange} - * @signal - */ - this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); - /** - * Mid multiplier - * @type {Tone.Expr} - * @private - */ - this._midMult = new Tone.Expr('$0 * ($1 * (1 - $2))'); - /** - * Side multiplier - * @type {Tone.Expr} - * @private - */ - this._sideMult = new Tone.Expr('$0 * ($1 * $2)'); - /** - * constant output of 2 - * @type {Tone} - * @private - */ - this._two = new Tone.Signal(2); - //the mid chain - this._two.connect(this._midMult, 0, 1); - this.width.connect(this._midMult, 0, 2); - //the side chain - this._two.connect(this._sideMult, 0, 1); - this.width.connect(this._sideMult, 0, 2); - //connect it to the effect send/return - this.midSend.chain(this._midMult, this.midReturn); - this.sideSend.chain(this._sideMult, this.sideReturn); - this._readOnly(['width']); - }; - Tone.extend(Tone.StereoWidener, Tone.MidSideEffect); - /** - * the default values - * @static - * @type {Object} - */ - Tone.StereoWidener.defaults = { 'width': 0.5 }; - /** - * Clean up. - * @returns {Tone.StereoWidener} this - */ - Tone.StereoWidener.prototype.dispose = function () { - Tone.MidSideEffect.prototype.dispose.call(this); - this._writable(['width']); - this.width.dispose(); - this.width = null; - this._midMult.dispose(); - this._midMult = null; - this._sideMult.dispose(); - this._sideMult = null; - this._two.dispose(); - this._two = null; - return this; - }; - return Tone.StereoWidener; - }); - Module(function (Tone) { - - /** - * @class Tone.Tremolo modulates the amplitude of an incoming signal using a Tone.LFO. - * The type, frequency, and depth of the LFO is controllable. - * - * @extends {Tone.StereoEffect} - * @constructor - * @param {Frequency} [frequency] The rate of the effect. - * @param {NormalRange} [depth] The depth of the effect. - * @example - * //create a tremolo and start it's LFO - * var tremolo = new Tone.Tremolo(9, 0.75).toMaster().start(); - * //route an oscillator through the tremolo and start it - * var oscillator = new Tone.Oscillator().connect(tremolo).start(); - */ - Tone.Tremolo = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'depth' - ], Tone.Tremolo.defaults); - Tone.StereoEffect.call(this, options); - /** - * The tremelo LFO in the left channel - * @type {Tone.LFO} - * @private - */ - this._lfoL = new Tone.LFO({ - 'phase': options.spread, - 'min': 1, - 'max': 0 - }); - /** - * The tremelo LFO in the left channel - * @type {Tone.LFO} - * @private - */ - this._lfoR = new Tone.LFO({ - 'phase': options.spread, - 'min': 1, - 'max': 0 - }); - /** - * Where the gain is multiplied - * @type {Tone.Gain} - * @private - */ - this._amplitudeL = new Tone.Gain(); - /** - * Where the gain is multiplied - * @type {Tone.Gain} - * @private - */ - this._amplitudeR = new Tone.Gain(); - /** - * The frequency of the tremolo. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The depth of the effect. A depth of 0, has no effect - * on the amplitude, and a depth of 1 makes the amplitude - * modulate fully between 0 and 1. - * @type {NormalRange} - * @signal - */ - this.depth = new Tone.Signal(options.depth, Tone.Type.NormalRange); - this._readOnly([ - 'frequency', - 'depth' - ]); - this.effectSendL.chain(this._amplitudeL, this.effectReturnL); - this.effectSendR.chain(this._amplitudeR, this.effectReturnR); - this._lfoL.connect(this._amplitudeL.gain); - this._lfoR.connect(this._amplitudeR.gain); - this.frequency.fan(this._lfoL.frequency, this._lfoR.frequency); - this.depth.fan(this._lfoR.amplitude, this._lfoL.amplitude); - this.type = options.type; - this.spread = options.spread; - }; - Tone.extend(Tone.Tremolo, Tone.StereoEffect); - /** - * @static - * @const - * @type {Object} - */ - Tone.Tremolo.defaults = { - 'frequency': 10, - 'type': 'sine', - 'depth': 0.5, - 'spread': 180 - }; - /** - * Start the tremolo. - * @param {Time} [time=now] When the tremolo begins. - * @returns {Tone.Tremolo} this - */ - Tone.Tremolo.prototype.start = function (time) { - this._lfoL.start(time); - this._lfoR.start(time); - return this; - }; - /** - * Stop the tremolo. - * @param {Time} [time=now] When the tremolo stops. - * @returns {Tone.Tremolo} this - */ - Tone.Tremolo.prototype.stop = function (time) { - this._lfoL.stop(time); - this._lfoR.stop(time); - return this; - }; - /** - * Sync the effect to the transport. - * @param {Time} [delay=0] Delay time before starting the effect after the - * Transport has started. - * @returns {Tone.AutoFilter} this - */ - Tone.Tremolo.prototype.sync = function (delay) { - this._lfoL.sync(delay); - this._lfoR.sync(delay); - return this; - }; - /** - * Unsync the filter from the transport - * @returns {Tone.Tremolo} this - */ - Tone.Tremolo.prototype.unsync = function () { - this._lfoL.unsync(); - this._lfoR.unsync(); - return this; - }; - /** - * The Tremolo's oscillator type. - * @memberOf Tone.Tremolo# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.Tremolo.prototype, 'type', { - get: function () { - return this._lfoL.type; - }, - set: function (type) { - this._lfoL.type = type; - this._lfoR.type = type; - } - }); - /** - * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. - * When set to 180, LFO's will be panned hard left and right respectively. - * @memberOf Tone.Tremolo# - * @type {Degrees} - * @name spread - */ - Object.defineProperty(Tone.Tremolo.prototype, 'spread', { - get: function () { - return this._lfoR.phase - this._lfoL.phase; //180 - }, - set: function (spread) { - this._lfoL.phase = 90 - spread / 2; - this._lfoR.phase = spread / 2 + 90; - } - }); - /** - * clean up - * @returns {Tone.Tremolo} this - */ - Tone.Tremolo.prototype.dispose = function () { - Tone.StereoEffect.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'depth' - ]); - this._lfoL.dispose(); - this._lfoL = null; - this._lfoR.dispose(); - this._lfoR = null; - this._amplitudeL.dispose(); - this._amplitudeL = null; - this._amplitudeR.dispose(); - this._amplitudeR = null; - this.frequency = null; - this.depth = null; - return this; - }; - return Tone.Tremolo; - }); - Module(function (Tone) { - - /** - * @class A Vibrato effect composed of a Tone.Delay and a Tone.LFO. The LFO - * modulates the delayTime of the delay, causing the pitch to rise - * and fall. - * @extends {Tone.Effect} - * @param {Frequency} frequency The frequency of the vibrato. - * @param {NormalRange} depth The amount the pitch is modulated. - */ - Tone.Vibrato = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'depth' - ], Tone.Vibrato.defaults); - Tone.Effect.call(this, options); - /** - * The delay node used for the vibrato effect - * @type {Tone.Delay} - * @private - */ - this._delayNode = new Tone.Delay(0, options.maxDelay); - /** - * The LFO used to control the vibrato - * @type {Tone.LFO} - * @private - */ - this._lfo = new Tone.LFO({ - 'type': options.type, - 'min': 0, - 'max': options.maxDelay, - 'frequency': options.frequency, - 'phase': -90 //offse the phase so the resting position is in the center - }).start().connect(this._delayNode.delayTime); - /** - * The frequency of the vibrato - * @type {Frequency} - * @signal - */ - this.frequency = this._lfo.frequency; - /** - * The depth of the vibrato. - * @type {NormalRange} - * @signal - */ - this.depth = this._lfo.amplitude; - this.depth.value = options.depth; - this._readOnly([ - 'frequency', - 'depth' - ]); - this.effectSend.chain(this._delayNode, this.effectReturn); - }; - Tone.extend(Tone.Vibrato, Tone.Effect); - /** - * The defaults - * @type {Object} - * @const - */ - Tone.Vibrato.defaults = { - 'maxDelay': 0.005, - 'frequency': 5, - 'depth': 0.1, - 'type': 'sine' - }; - /** - * Type of oscillator attached to the Vibrato. - * @memberOf Tone.Vibrato# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.Vibrato.prototype, 'type', { - get: function () { - return this._lfo.type; - }, - set: function (type) { - this._lfo.type = type; - } - }); - /** - * Clean up. - * @returns {Tone.Vibrato} this - */ - Tone.Vibrato.prototype.dispose = function () { - Tone.Effect.prototype.dispose.call(this); - this._delayNode.dispose(); - this._delayNode = null; - this._lfo.dispose(); - this._lfo = null; - this._writable([ - 'frequency', - 'depth' - ]); - this.frequency = null; - this.depth = null; - }; - return Tone.Vibrato; - }); - Module(function (Tone) { - - /** - * @class Tone.Event abstracts away Tone.Transport.schedule and provides a schedulable - * callback for a single or repeatable events along the timeline. - * - * @extends {Tone} - * @param {function} callback The callback to invoke at the time. - * @param {*} value The value or values which should be passed to - * the callback function on invocation. - * @example - * var chord = new Tone.Event(function(time, chord){ - * //the chord as well as the exact time of the event - * //are passed in as arguments to the callback function - * }, ["D4", "E4", "F4"]); - * //start the chord at the beginning of the transport timeline - * chord.start(); - * //loop it every measure for 8 measures - * chord.loop = 8; - * chord.loopEnd = "1m"; - */ - Tone.Event = function () { - var options = this.optionsObject(arguments, [ - 'callback', - 'value' - ], Tone.Event.defaults); - /** - * Loop value - * @type {Boolean|Positive} - * @private - */ - this._loop = options.loop; - /** - * The callback to invoke. - * @type {Function} - */ - this.callback = options.callback; - /** - * The value which is passed to the - * callback function. - * @type {*} - * @private - */ - this.value = options.value; - /** - * When the note is scheduled to start. - * @type {Number} - * @private - */ - this._loopStart = this.toTicks(options.loopStart); - /** - * When the note is scheduled to start. - * @type {Number} - * @private - */ - this._loopEnd = this.toTicks(options.loopEnd); - /** - * Tracks the scheduled events - * @type {Tone.TimelineState} - * @private - */ - this._state = new Tone.TimelineState(Tone.State.Stopped); - /** - * The playback speed of the note. A speed of 1 - * is no change. - * @private - * @type {Positive} - */ - this._playbackRate = 1; - /** - * A delay time from when the event is scheduled to start - * @type {Ticks} - * @private - */ - this._startOffset = 0; - /** - * The probability that the callback will be invoked - * at the scheduled time. - * @type {NormalRange} - * @example - * //the callback will be invoked 50% of the time - * event.probability = 0.5; - */ - this.probability = options.probability; - /** - * If set to true, will apply small (+/-0.02 seconds) random variation - * to the callback time. If the value is given as a time, it will randomize - * by that amount. - * @example - * event.humanize = true; - * @type {Boolean|Time} - */ - this.humanize = options.humanize; - /** - * If mute is true, the callback won't be - * invoked. - * @type {Boolean} - */ - this.mute = options.mute; - //set the initial values - this.playbackRate = options.playbackRate; - }; - Tone.extend(Tone.Event); - /** - * The default values - * @type {Object} - * @const - */ - Tone.Event.defaults = { - 'callback': Tone.noOp, - 'loop': false, - 'loopEnd': '1m', - 'loopStart': 0, - 'playbackRate': 1, - 'value': null, - 'probability': 1, - 'mute': false, - 'humanize': false - }; - /** - * Reschedule all of the events along the timeline - * with the updated values. - * @param {Time} after Only reschedules events after the given time. - * @return {Tone.Event} this - * @private - */ - Tone.Event.prototype._rescheduleEvents = function (after) { - //if no argument is given, schedules all of the events - after = this.defaultArg(after, -1); - this._state.forEachFrom(after, function (event) { - var duration; - if (event.state === Tone.State.Started) { - if (!this.isUndef(event.id)) { - Tone.Transport.clear(event.id); - } - var startTick = event.time + Math.round(this.startOffset / this._playbackRate); - if (this._loop) { - duration = Infinity; - if (this.isNumber(this._loop)) { - duration = this._loop * this._getLoopDuration(); - } - var nextEvent = this._state.getAfter(startTick); - if (nextEvent !== null) { - duration = Math.min(duration, nextEvent.time - startTick); - } - if (duration !== Infinity) { - //schedule a stop since it's finite duration - this._state.setStateAtTime(Tone.State.Stopped, startTick + duration + 1); - duration = Tone.Time(duration, 'i'); - } - var interval = Tone.Time(this._getLoopDuration(), 'i'); - event.id = Tone.Transport.scheduleRepeat(this._tick.bind(this), interval, Tone.TransportTime(startTick, 'i'), duration); - } else { - event.id = Tone.Transport.schedule(this._tick.bind(this), startTick + 'i'); - } - } - }.bind(this)); - return this; - }; - /** - * Returns the playback state of the note, either "started" or "stopped". - * @type {String} - * @readOnly - * @memberOf Tone.Event# - * @name state - */ - Object.defineProperty(Tone.Event.prototype, 'state', { - get: function () { - return this._state.getValueAtTime(Tone.Transport.ticks); - } - }); - /** - * The start from the scheduled start time - * @type {Ticks} - * @memberOf Tone.Event# - * @name startOffset - * @private - */ - Object.defineProperty(Tone.Event.prototype, 'startOffset', { - get: function () { - return this._startOffset; - }, - set: function (offset) { - this._startOffset = offset; - } - }); - /** - * Start the note at the given time. - * @param {TimelinePosition} time When the note should start. - * @return {Tone.Event} this - */ - Tone.Event.prototype.start = function (time) { - time = this.toTicks(time); - if (this._state.getValueAtTime(time) === Tone.State.Stopped) { - this._state.add({ - 'state': Tone.State.Started, - 'time': time, - 'id': undefined - }); - this._rescheduleEvents(time); - } - return this; - }; - /** - * Stop the Event at the given time. - * @param {TimelinePosition} time When the note should stop. - * @return {Tone.Event} this - */ - Tone.Event.prototype.stop = function (time) { - this.cancel(time); - time = this.toTicks(time); - if (this._state.getValueAtTime(time) === Tone.State.Started) { - this._state.setStateAtTime(Tone.State.Stopped, time); - var previousEvent = this._state.getBefore(time); - var reschedulTime = time; - if (previousEvent !== null) { - reschedulTime = previousEvent.time; - } - this._rescheduleEvents(reschedulTime); - } - return this; - }; - /** - * Cancel all scheduled events greater than or equal to the given time - * @param {TimelinePosition} [time=0] The time after which events will be cancel. - * @return {Tone.Event} this - */ - Tone.Event.prototype.cancel = function (time) { - time = this.defaultArg(time, -Infinity); - time = this.toTicks(time); - this._state.forEachFrom(time, function (event) { - Tone.Transport.clear(event.id); - }); - this._state.cancel(time); - return this; - }; - /** - * The callback function invoker. Also - * checks if the Event is done playing - * @param {Number} time The time of the event in seconds - * @private - */ - Tone.Event.prototype._tick = function (time) { - if (!this.mute && this._state.getValueAtTime(Tone.Transport.ticks) === Tone.State.Started) { - if (this.probability < 1 && Math.random() > this.probability) { - return; - } - if (this.humanize) { - var variation = 0.02; - if (!this.isBoolean(this.humanize)) { - variation = this.toSeconds(this.humanize); - } - time += (Math.random() * 2 - 1) * variation; - } - this.callback(time, this.value); - } - }; - /** - * Get the duration of the loop. - * @return {Ticks} - * @private - */ - Tone.Event.prototype._getLoopDuration = function () { - return Math.round((this._loopEnd - this._loopStart) / this._playbackRate); - }; - /** - * If the note should loop or not - * between Tone.Event.loopStart and - * Tone.Event.loopEnd. An integer - * value corresponds to the number of - * loops the Event does after it starts. - * @memberOf Tone.Event# - * @type {Boolean|Positive} - * @name loop - */ - Object.defineProperty(Tone.Event.prototype, 'loop', { - get: function () { - return this._loop; - }, - set: function (loop) { - this._loop = loop; - this._rescheduleEvents(); - } - }); - /** - * The playback rate of the note. Defaults to 1. - * @memberOf Tone.Event# - * @type {Positive} - * @name playbackRate - * @example - * note.loop = true; - * //repeat the note twice as fast - * note.playbackRate = 2; - */ - Object.defineProperty(Tone.Event.prototype, 'playbackRate', { - get: function () { - return this._playbackRate; - }, - set: function (rate) { - this._playbackRate = rate; - this._rescheduleEvents(); - } - }); - /** - * The loopEnd point is the time the event will loop - * if Tone.Event.loop is true. - * @memberOf Tone.Event# - * @type {TransportTime} - * @name loopEnd - */ - Object.defineProperty(Tone.Event.prototype, 'loopEnd', { - get: function () { - return Tone.TransportTime(this._loopEnd, 'i').toNotation(); - }, - set: function (loopEnd) { - this._loopEnd = this.toTicks(loopEnd); - if (this._loop) { - this._rescheduleEvents(); - } - } - }); - /** - * The time when the loop should start. - * @memberOf Tone.Event# - * @type {TransportTime} - * @name loopStart - */ - Object.defineProperty(Tone.Event.prototype, 'loopStart', { - get: function () { - return Tone.TransportTime(this._loopStart, 'i').toNotation(); - }, - set: function (loopStart) { - this._loopStart = this.toTicks(loopStart); - if (this._loop) { - this._rescheduleEvents(); - } - } - }); - /** - * The current progress of the loop interval. - * Returns 0 if the event is not started yet or - * it is not set to loop. - * @memberOf Tone.Event# - * @type {NormalRange} - * @name progress - * @readOnly - */ - Object.defineProperty(Tone.Event.prototype, 'progress', { - get: function () { - if (this._loop) { - var ticks = Tone.Transport.ticks; - var lastEvent = this._state.get(ticks); - if (lastEvent !== null && lastEvent.state === Tone.State.Started) { - var loopDuration = this._getLoopDuration(); - var progress = (ticks - lastEvent.time) % loopDuration; - return progress / loopDuration; - } else { - return 0; - } - } else { - return 0; - } - } - }); - /** - * Clean up - * @return {Tone.Event} this - */ - Tone.Event.prototype.dispose = function () { - this.cancel(); - this._state.dispose(); - this._state = null; - this.callback = null; - this.value = null; - }; - return Tone.Event; - }); - Module(function (Tone) { - /** - * @class Tone.Loop creates a looped callback at the - * specified interval. The callback can be - * started, stopped and scheduled along - * the Transport's timeline. - * @example - * var loop = new Tone.Loop(function(time){ - * //triggered every eighth note. - * console.log(time); - * }, "8n").start(0); - * Tone.Transport.start(); - * @extends {Tone} - * @param {Function} callback The callback to invoke with the event. - * @param {Time} interval The time between successive callback calls. - */ - Tone.Loop = function () { - var options = this.optionsObject(arguments, [ - 'callback', - 'interval' - ], Tone.Loop.defaults); - /** - * The event which produces the callbacks - */ - this._event = new Tone.Event({ - 'callback': this._tick.bind(this), - 'loop': true, - 'loopEnd': options.interval, - 'playbackRate': options.playbackRate, - 'probability': options.probability - }); - /** - * The callback to invoke with the next event in the pattern - * @type {Function} - */ - this.callback = options.callback; - //set the iterations - this.iterations = options.iterations; - }; - Tone.extend(Tone.Loop); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.Loop.defaults = { - 'interval': '4n', - 'callback': Tone.noOp, - 'playbackRate': 1, - 'iterations': Infinity, - 'probability': true, - 'mute': false - }; - /** - * Start the loop at the specified time along the Transport's - * timeline. - * @param {TimelinePosition=} time When to start the Loop. - * @return {Tone.Loop} this - */ - Tone.Loop.prototype.start = function (time) { - this._event.start(time); - return this; - }; - /** - * Stop the loop at the given time. - * @param {TimelinePosition=} time When to stop the Arpeggio - * @return {Tone.Loop} this - */ - Tone.Loop.prototype.stop = function (time) { - this._event.stop(time); - return this; - }; - /** - * Cancel all scheduled events greater than or equal to the given time - * @param {TimelinePosition} [time=0] The time after which events will be cancel. - * @return {Tone.Loop} this - */ - Tone.Loop.prototype.cancel = function (time) { - this._event.cancel(time); - return this; - }; - /** - * Internal function called when the notes should be called - * @param {Number} time The time the event occurs - * @private - */ - Tone.Loop.prototype._tick = function (time) { - this.callback(time); - }; - /** - * The state of the Loop, either started or stopped. - * @memberOf Tone.Loop# - * @type {String} - * @name state - * @readOnly - */ - Object.defineProperty(Tone.Loop.prototype, 'state', { - get: function () { - return this._event.state; - } - }); - /** - * The progress of the loop as a value between 0-1. 0, when - * the loop is stopped or done iterating. - * @memberOf Tone.Loop# - * @type {NormalRange} - * @name progress - * @readOnly - */ - Object.defineProperty(Tone.Loop.prototype, 'progress', { - get: function () { - return this._event.progress; - } - }); - /** - * The time between successive callbacks. - * @example - * loop.interval = "8n"; //loop every 8n - * @memberOf Tone.Loop# - * @type {Time} - * @name interval - */ - Object.defineProperty(Tone.Loop.prototype, 'interval', { - get: function () { - return this._event.loopEnd; - }, - set: function (interval) { - this._event.loopEnd = interval; - } - }); - /** - * The playback rate of the loop. The normal playback rate is 1 (no change). - * A `playbackRate` of 2 would be twice as fast. - * @memberOf Tone.Loop# - * @type {Time} - * @name playbackRate - */ - Object.defineProperty(Tone.Loop.prototype, 'playbackRate', { - get: function () { - return this._event.playbackRate; - }, - set: function (rate) { - this._event.playbackRate = rate; - } - }); - /** - * Random variation +/-0.01s to the scheduled time. - * Or give it a time value which it will randomize by. - * @type {Boolean|Time} - * @memberOf Tone.Loop# - * @name humanize - */ - Object.defineProperty(Tone.Loop.prototype, 'humanize', { - get: function () { - return this._event.humanize; - }, - set: function (variation) { - this._event.humanize = variation; - } - }); - /** - * The probably of the callback being invoked. - * @memberOf Tone.Loop# - * @type {NormalRange} - * @name probability - */ - Object.defineProperty(Tone.Loop.prototype, 'probability', { - get: function () { - return this._event.probability; - }, - set: function (prob) { - this._event.probability = prob; - } - }); - /** - * Muting the Loop means that no callbacks are invoked. - * @memberOf Tone.Loop# - * @type {Boolean} - * @name mute - */ - Object.defineProperty(Tone.Loop.prototype, 'mute', { - get: function () { - return this._event.mute; - }, - set: function (mute) { - this._event.mute = mute; - } - }); - /** - * The number of iterations of the loop. The default - * value is Infinity (loop forever). - * @memberOf Tone.Loop# - * @type {Positive} - * @name iterations - */ - Object.defineProperty(Tone.Loop.prototype, 'iterations', { - get: function () { - if (this._event.loop === true) { - return Infinity; - } else { - return this._event.loop; - } - return this._pattern.index; - }, - set: function (iters) { - if (iters === Infinity) { - this._event.loop = true; - } else { - this._event.loop = iters; - } - } - }); - /** - * Clean up - * @return {Tone.Loop} this - */ - Tone.Loop.prototype.dispose = function () { - this._event.dispose(); - this._event = null; - this.callback = null; - }; - return Tone.Loop; - }); - Module(function (Tone) { - - /** - * @class Tone.Part is a collection Tone.Events which can be - * started/stoped and looped as a single unit. - * - * @extends {Tone.Event} - * @param {Function} callback The callback to invoke on each event - * @param {Array} events the array of events - * @example - * var part = new Tone.Part(function(time, note){ - * //the notes given as the second element in the array - * //will be passed in as the second argument - * synth.triggerAttackRelease(note, "8n", time); - * }, [[0, "C2"], ["0:2", "C3"], ["0:3:2", "G2"]]); - * @example - * //use an array of objects as long as the object has a "time" attribute - * var part = new Tone.Part(function(time, value){ - * //the value is an object which contains both the note and the velocity - * synth.triggerAttackRelease(value.note, "8n", time, value.velocity); - * }, [{"time" : 0, "note" : "C3", "velocity": 0.9}, - * {"time" : "0:2", "note" : "C4", "velocity": 0.5} - * ]).start(0); - */ - Tone.Part = function () { - var options = this.optionsObject(arguments, [ - 'callback', - 'events' - ], Tone.Part.defaults); - /** - * If the part is looping or not - * @type {Boolean|Positive} - * @private - */ - this._loop = options.loop; - /** - * When the note is scheduled to start. - * @type {Ticks} - * @private - */ - this._loopStart = this.toTicks(options.loopStart); - /** - * When the note is scheduled to start. - * @type {Ticks} - * @private - */ - this._loopEnd = this.toTicks(options.loopEnd); - /** - * The playback rate of the part - * @type {Positive} - * @private - */ - this._playbackRate = options.playbackRate; - /** - * private holder of probability value - * @type {NormalRange} - * @private - */ - this._probability = options.probability; - /** - * the amount of variation from the - * given time. - * @type {Boolean|Time} - * @private - */ - this._humanize = options.humanize; - /** - * The start offset - * @type {Ticks} - * @private - */ - this._startOffset = 0; - /** - * Keeps track of the current state - * @type {Tone.TimelineState} - * @private - */ - this._state = new Tone.TimelineState(Tone.State.Stopped); - /** - * An array of Objects. - * @type {Array} - * @private - */ - this._events = []; - /** - * The callback to invoke at all the scheduled events. - * @type {Function} - */ - this.callback = options.callback; - /** - * If mute is true, the callback won't be - * invoked. - * @type {Boolean} - */ - this.mute = options.mute; - //add the events - var events = this.defaultArg(options.events, []); - if (!this.isUndef(options.events)) { - for (var i = 0; i < events.length; i++) { - if (Array.isArray(events[i])) { - this.add(events[i][0], events[i][1]); - } else { - this.add(events[i]); - } - } - } - }; - Tone.extend(Tone.Part, Tone.Event); - /** - * The default values - * @type {Object} - * @const - */ - Tone.Part.defaults = { - 'callback': Tone.noOp, - 'loop': false, - 'loopEnd': '1m', - 'loopStart': 0, - 'playbackRate': 1, - 'probability': 1, - 'humanize': false, - 'mute': false - }; - /** - * Start the part at the given time. - * @param {TransportTime} time When to start the part. - * @param {Time=} offset The offset from the start of the part - * to begin playing at. - * @return {Tone.Part} this - */ - Tone.Part.prototype.start = function (time, offset) { - var ticks = this.toTicks(time); - if (this._state.getValueAtTime(ticks) !== Tone.State.Started) { - if (this._loop) { - offset = this.defaultArg(offset, this._loopStart); - } else { - offset = this.defaultArg(offset, 0); - } - offset = this.toTicks(offset); - this._state.add({ - 'state': Tone.State.Started, - 'time': ticks, - 'offset': offset - }); - this._forEach(function (event) { - this._startNote(event, ticks, offset); - }); - } - return this; - }; - /** - * Start the event in the given event at the correct time given - * the ticks and offset and looping. - * @param {Tone.Event} event - * @param {Ticks} ticks - * @param {Ticks} offset - * @private - */ - Tone.Part.prototype._startNote = function (event, ticks, offset) { - ticks -= offset; - if (this._loop) { - if (event.startOffset >= this._loopStart && event.startOffset < this._loopEnd) { - if (event.startOffset < offset) { - //start it on the next loop - ticks += this._getLoopDuration(); - } - event.start(Tone.TransportTime(ticks, 'i')); - } else if (event.startOffset < this._loopStart && event.startOffset >= offset) { - event.loop = false; - event.start(Tone.TransportTime(ticks, 'i')); - } - } else { - if (event.startOffset >= offset) { - event.start(Tone.TransportTime(ticks, 'i')); - } - } - }; - /** - * The start from the scheduled start time - * @type {Ticks} - * @memberOf Tone.Part# - * @name startOffset - * @private - */ - Object.defineProperty(Tone.Part.prototype, 'startOffset', { - get: function () { - return this._startOffset; - }, - set: function (offset) { - this._startOffset = offset; - this._forEach(function (event) { - event.startOffset += this._startOffset; - }); - } - }); - /** - * Stop the part at the given time. - * @param {TimelinePosition} time When to stop the part. - * @return {Tone.Part} this - */ - Tone.Part.prototype.stop = function (time) { - var ticks = this.toTicks(time); - this._state.cancel(ticks); - this._state.setStateAtTime(Tone.State.Stopped, ticks); - this._forEach(function (event) { - event.stop(time); - }); - return this; - }; - /** - * Get/Set an Event's value at the given time. - * If a value is passed in and no event exists at - * the given time, one will be created with that value. - * If two events are at the same time, the first one will - * be returned. - * @example - * part.at("1m"); //returns the part at the first measure - * - * part.at("2m", "C2"); //set the value at "2m" to C2. - * //if an event didn't exist at that time, it will be created. - * @param {TransportTime} time The time of the event to get or set. - * @param {*=} value If a value is passed in, the value of the - * event at the given time will be set to it. - * @return {Tone.Event} the event at the time - */ - Tone.Part.prototype.at = function (time, value) { - time = Tone.TransportTime(time); - var tickTime = Tone.Time(1, 'i').toSeconds(); - for (var i = 0; i < this._events.length; i++) { - var event = this._events[i]; - if (Math.abs(time.toTicks() - event.startOffset) < tickTime) { - if (!this.isUndef(value)) { - event.value = value; - } - return event; - } - } - //if there was no event at that time, create one - if (!this.isUndef(value)) { - this.add(time, value); - //return the new event - return this._events[this._events.length - 1]; - } else { - return null; - } - }; - /** - * Add a an event to the part. - * @param {Time} time The time the note should start. - * If an object is passed in, it should - * have a 'time' attribute and the rest - * of the object will be used as the 'value'. - * @param {Tone.Event|*} value - * @returns {Tone.Part} this - * @example - * part.add("1m", "C#+11"); - */ - Tone.Part.prototype.add = function (time, value) { - //extract the parameters - if (time.hasOwnProperty('time')) { - value = time; - time = value.time; - } - time = this.toTicks(time); - var event; - if (value instanceof Tone.Event) { - event = value; - event.callback = this._tick.bind(this); - } else { - event = new Tone.Event({ - 'callback': this._tick.bind(this), - 'value': value - }); - } - //the start offset - event.startOffset = time; - //initialize the values - event.set({ - 'loopEnd': this.loopEnd, - 'loopStart': this.loopStart, - 'loop': this.loop, - 'humanize': this.humanize, - 'playbackRate': this.playbackRate, - 'probability': this.probability - }); - this._events.push(event); - //start the note if it should be played right now - this._restartEvent(event); - return this; - }; - /** - * Restart the given event - * @param {Tone.Event} event - * @private - */ - Tone.Part.prototype._restartEvent = function (event) { - this._state.forEach(function (stateEvent) { - if (stateEvent.state === Tone.State.Started) { - this._startNote(event, stateEvent.time, stateEvent.offset); - } else { - //stop the note - event.stop(Tone.TransportTime(stateEvent.time, 'i')); - } - }.bind(this)); - }; - /** - * Remove an event from the part. Will recursively iterate - * into nested parts to find the event. - * @param {Time} time The time of the event - * @param {*} value Optionally select only a specific event value - * @return {Tone.Part} this - */ - Tone.Part.prototype.remove = function (time, value) { - //extract the parameters - if (time.hasOwnProperty('time')) { - value = time; - time = value.time; - } - time = this.toTicks(time); - for (var i = this._events.length - 1; i >= 0; i--) { - var event = this._events[i]; - if (event instanceof Tone.Part) { - event.remove(time, value); - } else { - if (event.startOffset === time) { - if (this.isUndef(value) || !this.isUndef(value) && event.value === value) { - this._events.splice(i, 1); - event.dispose(); - } - } - } - } - return this; - }; - /** - * Remove all of the notes from the group. - * @return {Tone.Part} this - */ - Tone.Part.prototype.removeAll = function () { - this._forEach(function (event) { - event.dispose(); - }); - this._events = []; - return this; - }; - /** - * Cancel scheduled state change events: i.e. "start" and "stop". - * @param {TimelinePosition} after The time after which to cancel the scheduled events. - * @return {Tone.Part} this - */ - Tone.Part.prototype.cancel = function (after) { - after = this.toTicks(after); - this._forEach(function (event) { - event.cancel(after); - }); - this._state.cancel(after); - return this; - }; - /** - * Iterate over all of the events - * @param {Function} callback - * @param {Object} ctx The context - * @private - */ - Tone.Part.prototype._forEach = function (callback, ctx) { - ctx = this.defaultArg(ctx, this); - for (var i = this._events.length - 1; i >= 0; i--) { - var e = this._events[i]; - if (e instanceof Tone.Part) { - e._forEach(callback, ctx); - } else { - callback.call(ctx, e); - } - } - return this; - }; - /** - * Set the attribute of all of the events - * @param {String} attr the attribute to set - * @param {*} value The value to set it to - * @private - */ - Tone.Part.prototype._setAll = function (attr, value) { - this._forEach(function (event) { - event[attr] = value; - }); - }; - /** - * Internal tick method - * @param {Number} time The time of the event in seconds - * @private - */ - Tone.Part.prototype._tick = function (time, value) { - if (!this.mute) { - this.callback(time, value); - } - }; - /** - * Determine if the event should be currently looping - * given the loop boundries of this Part. - * @param {Tone.Event} event The event to test - * @private - */ - Tone.Part.prototype._testLoopBoundries = function (event) { - if (event.startOffset < this._loopStart || event.startOffset >= this._loopEnd) { - event.cancel(0); - } else { - //reschedule it if it's stopped - if (event.state === Tone.State.Stopped) { - this._restartEvent(event); - } - } - }; - /** - * The probability of the notes being triggered. - * @memberOf Tone.Part# - * @type {NormalRange} - * @name probability - */ - Object.defineProperty(Tone.Part.prototype, 'probability', { - get: function () { - return this._probability; - }, - set: function (prob) { - this._probability = prob; - this._setAll('probability', prob); - } - }); - /** - * If set to true, will apply small random variation - * to the callback time. If the value is given as a time, it will randomize - * by that amount. - * @example - * event.humanize = true; - * @type {Boolean|Time} - * @name humanize - */ - Object.defineProperty(Tone.Part.prototype, 'humanize', { - get: function () { - return this._humanize; - }, - set: function (variation) { - this._humanize = variation; - this._setAll('humanize', variation); - } - }); - /** - * If the part should loop or not - * between Tone.Part.loopStart and - * Tone.Part.loopEnd. An integer - * value corresponds to the number of - * loops the Part does after it starts. - * @memberOf Tone.Part# - * @type {Boolean|Positive} - * @name loop - * @example - * //loop the part 8 times - * part.loop = 8; - */ - Object.defineProperty(Tone.Part.prototype, 'loop', { - get: function () { - return this._loop; - }, - set: function (loop) { - this._loop = loop; - this._forEach(function (event) { - event._loopStart = this._loopStart; - event._loopEnd = this._loopEnd; - event.loop = loop; - this._testLoopBoundries(event); - }); - } - }); - /** - * The loopEnd point determines when it will - * loop if Tone.Part.loop is true. - * @memberOf Tone.Part# - * @type {TransportTime} - * @name loopEnd - */ - Object.defineProperty(Tone.Part.prototype, 'loopEnd', { - get: function () { - return Tone.TransportTime(this._loopEnd, 'i').toNotation(); - }, - set: function (loopEnd) { - this._loopEnd = this.toTicks(loopEnd); - if (this._loop) { - this._forEach(function (event) { - event.loopEnd = loopEnd; - this._testLoopBoundries(event); - }); - } - } - }); - /** - * The loopStart point determines when it will - * loop if Tone.Part.loop is true. - * @memberOf Tone.Part# - * @type {TransportTime} - * @name loopStart - */ - Object.defineProperty(Tone.Part.prototype, 'loopStart', { - get: function () { - return Tone.TransportTime(this._loopStart, 'i').toNotation(); - }, - set: function (loopStart) { - this._loopStart = this.toTicks(loopStart); - if (this._loop) { - this._forEach(function (event) { - event.loopStart = this.loopStart; - this._testLoopBoundries(event); - }); - } - } - }); - /** - * The playback rate of the part - * @memberOf Tone.Part# - * @type {Positive} - * @name playbackRate - */ - Object.defineProperty(Tone.Part.prototype, 'playbackRate', { - get: function () { - return this._playbackRate; - }, - set: function (rate) { - this._playbackRate = rate; - this._setAll('playbackRate', rate); - } - }); - /** - * The number of scheduled notes in the part. - * @memberOf Tone.Part# - * @type {Positive} - * @name length - * @readOnly - */ - Object.defineProperty(Tone.Part.prototype, 'length', { - get: function () { - return this._events.length; - } - }); - /** - * Clean up - * @return {Tone.Part} this - */ - Tone.Part.prototype.dispose = function () { - this.removeAll(); - this._state.dispose(); - this._state = null; - this.callback = null; - this._events = null; - return this; - }; - return Tone.Part; - }); - Module(function (Tone) { - /** - * @class Tone.Pattern arpeggiates between the given notes - * in a number of patterns. See Tone.CtrlPattern for - * a full list of patterns. - * @example - * var pattern = new Tone.Pattern(function(time, note){ - * //the order of the notes passed in depends on the pattern - * }, ["C2", "D4", "E5", "A6"], "upDown"); - * @extends {Tone.Loop} - * @param {Function} callback The callback to invoke with the - * event. - * @param {Array} values The values to arpeggiate over. - */ - Tone.Pattern = function () { - var options = this.optionsObject(arguments, [ - 'callback', - 'values', - 'pattern' - ], Tone.Pattern.defaults); - Tone.Loop.call(this, options); - /** - * The pattern manager - * @type {Tone.CtrlPattern} - * @private - */ - this._pattern = new Tone.CtrlPattern({ - 'values': options.values, - 'type': options.pattern, - 'index': options.index - }); - }; - Tone.extend(Tone.Pattern, Tone.Loop); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.Pattern.defaults = { - 'pattern': Tone.CtrlPattern.Type.Up, - 'values': [] - }; - /** - * Internal function called when the notes should be called - * @param {Number} time The time the event occurs - * @private - */ - Tone.Pattern.prototype._tick = function (time) { - this.callback(time, this._pattern.value); - this._pattern.next(); - }; - /** - * The current index in the values array. - * @memberOf Tone.Pattern# - * @type {Positive} - * @name index - */ - Object.defineProperty(Tone.Pattern.prototype, 'index', { - get: function () { - return this._pattern.index; - }, - set: function (i) { - this._pattern.index = i; - } - }); - /** - * The array of events. - * @memberOf Tone.Pattern# - * @type {Array} - * @name values - */ - Object.defineProperty(Tone.Pattern.prototype, 'values', { - get: function () { - return this._pattern.values; - }, - set: function (vals) { - this._pattern.values = vals; - } - }); - /** - * The current value of the pattern. - * @memberOf Tone.Pattern# - * @type {*} - * @name value - * @readOnly - */ - Object.defineProperty(Tone.Pattern.prototype, 'value', { - get: function () { - return this._pattern.value; - } - }); - /** - * The pattern type. See Tone.CtrlPattern for the full list of patterns. - * @memberOf Tone.Pattern# - * @type {String} - * @name pattern - */ - Object.defineProperty(Tone.Pattern.prototype, 'pattern', { - get: function () { - return this._pattern.type; - }, - set: function (pattern) { - this._pattern.type = pattern; - } - }); - /** - * Clean up - * @return {Tone.Pattern} this - */ - Tone.Pattern.prototype.dispose = function () { - Tone.Loop.prototype.dispose.call(this); - this._pattern.dispose(); - this._pattern = null; - }; - return Tone.Pattern; - }); - Module(function (Tone) { - - /** - * @class A sequence is an alternate notation of a part. Instead - * of passing in an array of [time, event] pairs, pass - * in an array of events which will be spaced at the - * given subdivision. Sub-arrays will subdivide that beat - * by the number of items are in the array. - * Sequence notation inspiration from [Tidal](http://yaxu.org/tidal/) - * @param {Function} callback The callback to invoke with every note - * @param {Array} events The sequence - * @param {Time} subdivision The subdivision between which events are placed. - * @extends {Tone.Part} - * @example - * var seq = new Tone.Sequence(function(time, note){ - * console.log(note); - * //straight quater notes - * }, ["C4", "E4", "G4", "A4"], "4n"); - * @example - * var seq = new Tone.Sequence(function(time, note){ - * console.log(note); - * //subdivisions are given as subarrays - * }, ["C4", ["E4", "D4", "E4"], "G4", ["A4", "G4"]]); - */ - Tone.Sequence = function () { - var options = this.optionsObject(arguments, [ - 'callback', - 'events', - 'subdivision' - ], Tone.Sequence.defaults); - //remove the events - var events = options.events; - delete options.events; - Tone.Part.call(this, options); - /** - * The subdivison of each note - * @type {Ticks} - * @private - */ - this._subdivision = this.toTicks(options.subdivision); - //if no time was passed in, the loop end is the end of the cycle - if (this.isUndef(options.loopEnd) && !this.isUndef(events)) { - this._loopEnd = events.length * this._subdivision; - } - //defaults to looping - this._loop = true; - //add all of the events - if (!this.isUndef(events)) { - for (var i = 0; i < events.length; i++) { - this.add(i, events[i]); - } - } - }; - Tone.extend(Tone.Sequence, Tone.Part); - /** - * The default values. - * @type {Object} - */ - Tone.Sequence.defaults = { 'subdivision': '4n' }; - /** - * The subdivision of the sequence. This can only be - * set in the constructor. The subdivision is the - * interval between successive steps. - * @type {Time} - * @memberOf Tone.Sequence# - * @name subdivision - * @readOnly - */ - Object.defineProperty(Tone.Sequence.prototype, 'subdivision', { - get: function () { - return Tone.Time(this._subdivision, 'i').toNotation(); - } - }); - /** - * Get/Set an index of the sequence. If the index contains a subarray, - * a Tone.Sequence representing that sub-array will be returned. - * @example - * var sequence = new Tone.Sequence(playNote, ["E4", "C4", "F#4", ["A4", "Bb3"]]) - * sequence.at(0)// => returns "E4" - * //set a value - * sequence.at(0, "G3"); - * //get a nested sequence - * sequence.at(3).at(1)// => returns "Bb3" - * @param {Positive} index The index to get or set - * @param {*} value Optionally pass in the value to set at the given index. - */ - Tone.Sequence.prototype.at = function (index, value) { - //if the value is an array, - if (this.isArray(value)) { - //remove the current event at that index - this.remove(index); - } - //call the parent's method - return Tone.Part.prototype.at.call(this, this._indexTime(index), value); - }; - /** - * Add an event at an index, if there's already something - * at that index, overwrite it. If `value` is an array, - * it will be parsed as a subsequence. - * @param {Number} index The index to add the event to - * @param {*} value The value to add at that index - * @returns {Tone.Sequence} this - */ - Tone.Sequence.prototype.add = function (index, value) { - if (value === null) { - return this; - } - if (this.isArray(value)) { - //make a subsequence and add that to the sequence - var subSubdivision = Math.round(this._subdivision / value.length); - value = new Tone.Sequence(this._tick.bind(this), value, Tone.Time(subSubdivision, 'i')); - } - Tone.Part.prototype.add.call(this, this._indexTime(index), value); - return this; - }; - /** - * Remove a value from the sequence by index - * @param {Number} index The index of the event to remove - * @returns {Tone.Sequence} this - */ - Tone.Sequence.prototype.remove = function (index, value) { - Tone.Part.prototype.remove.call(this, this._indexTime(index), value); - return this; - }; - /** - * Get the time of the index given the Sequence's subdivision - * @param {Number} index - * @return {Time} The time of that index - * @private - */ - Tone.Sequence.prototype._indexTime = function (index) { - if (index instanceof Tone.TransportTime) { - return index; - } else { - return Tone.TransportTime(index * this._subdivision + this.startOffset, 'i'); - } - }; - /** - * Clean up. - * @return {Tone.Sequence} this - */ - Tone.Sequence.prototype.dispose = function () { - Tone.Part.prototype.dispose.call(this); - return this; - }; - return Tone.Sequence; - }); - Module(function (Tone) { - - /** - * @class Tone.PulseOscillator is a pulse oscillator with control over pulse width, - * also known as the duty cycle. At 50% duty cycle (width = 0.5) the wave is - * a square and only odd-numbered harmonics are present. At all other widths - * even-numbered harmonics are present. Read more - * [here](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/). - * - * @constructor - * @extends {Tone.Oscillator} - * @param {Frequency} [frequency] The frequency of the oscillator - * @param {NormalRange} [width] The width of the pulse - * @example - * var pulse = new Tone.PulseOscillator("E5", 0.4).toMaster().start(); - */ - Tone.PulseOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'width' - ], Tone.Oscillator.defaults); - Tone.Source.call(this, options); - /** - * The width of the pulse. - * @type {NormalRange} - * @signal - */ - this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); - /** - * gate the width amount - * @type {Tone.Gain} - * @private - */ - this._widthGate = new Tone.Gain(); - /** - * the sawtooth oscillator - * @type {Tone.Oscillator} - * @private - */ - this._sawtooth = new Tone.Oscillator({ - frequency: options.frequency, - detune: options.detune, - type: 'sawtooth', - phase: options.phase - }); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = this._sawtooth.frequency; - /** - * The detune in cents. - * @type {Cents} - * @signal - */ - this.detune = this._sawtooth.detune; - /** - * Threshold the signal to turn it into a square - * @type {Tone.WaveShaper} - * @private - */ - this._thresh = new Tone.WaveShaper(function (val) { - if (val < 0) { - return -1; - } else { - return 1; - } - }); - //connections - this._sawtooth.chain(this._thresh, this.output); - this.width.chain(this._widthGate, this._thresh); - this._readOnly([ - 'width', - 'frequency', - 'detune' - ]); - }; - Tone.extend(Tone.PulseOscillator, Tone.Oscillator); - /** - * The default parameters. - * @static - * @const - * @type {Object} - */ - Tone.PulseOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'width': 0.2 - }; - /** - * start the oscillator - * @param {Time} time - * @private - */ - Tone.PulseOscillator.prototype._start = function (time) { - time = this.toSeconds(time); - this._sawtooth.start(time); - this._widthGate.gain.setValueAtTime(1, time); - }; - /** - * stop the oscillator - * @param {Time} time - * @private - */ - Tone.PulseOscillator.prototype._stop = function (time) { - time = this.toSeconds(time); - this._sawtooth.stop(time); - //the width is still connected to the output. - //that needs to be stopped also - this._widthGate.gain.setValueAtTime(0, time); - }; - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.PulseOscillator# - * @type {Degrees} - * @name phase - */ - Object.defineProperty(Tone.PulseOscillator.prototype, 'phase', { - get: function () { - return this._sawtooth.phase; - }, - set: function (phase) { - this._sawtooth.phase = phase; - } - }); - /** - * The type of the oscillator. Always returns "pulse". - * @readOnly - * @memberOf Tone.PulseOscillator# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.PulseOscillator.prototype, 'type', { - get: function () { - return 'pulse'; - } - }); - /** - * The partials of the waveform. Cannot set partials for this waveform type - * @memberOf Tone.PulseOscillator# - * @type {Array} - * @name partials - * @private - */ - Object.defineProperty(Tone.PulseOscillator.prototype, 'partials', { - get: function () { - return []; - } - }); - /** - * Clean up method. - * @return {Tone.PulseOscillator} this - */ - Tone.PulseOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._sawtooth.dispose(); - this._sawtooth = null; - this._writable([ - 'width', - 'frequency', - 'detune' - ]); - this.width.dispose(); - this.width = null; - this._widthGate.dispose(); - this._widthGate = null; - this._thresh.dispose(); - this._thresh = null; - this.frequency = null; - this.detune = null; - return this; - }; - return Tone.PulseOscillator; - }); - Module(function (Tone) { - - /** - * @class Tone.PWMOscillator modulates the width of a Tone.PulseOscillator - * at the modulationFrequency. This has the effect of continuously - * changing the timbre of the oscillator by altering the harmonics - * generated. - * - * @extends {Tone.Oscillator} - * @constructor - * @param {Frequency} frequency The starting frequency of the oscillator. - * @param {Frequency} modulationFrequency The modulation frequency of the width of the pulse. - * @example - * var pwm = new Tone.PWMOscillator("Ab3", 0.3).toMaster().start(); - */ - Tone.PWMOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'modulationFrequency' - ], Tone.PWMOscillator.defaults); - Tone.Source.call(this, options); - /** - * the pulse oscillator - * @type {Tone.PulseOscillator} - * @private - */ - this._pulse = new Tone.PulseOscillator(options.modulationFrequency); - //change the pulse oscillator type - this._pulse._sawtooth.type = 'sine'; - /** - * the modulator - * @type {Tone.Oscillator} - * @private - */ - this._modulator = new Tone.Oscillator({ - 'frequency': options.frequency, - 'detune': options.detune, - 'phase': options.phase - }); - /** - * Scale the oscillator so it doesn't go silent - * at the extreme values. - * @type {Tone.Multiply} - * @private - */ - this._scale = new Tone.Multiply(2); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = this._modulator.frequency; - /** - * The detune of the oscillator. - * @type {Cents} - * @signal - */ - this.detune = this._modulator.detune; - /** - * The modulation rate of the oscillator. - * @type {Frequency} - * @signal - */ - this.modulationFrequency = this._pulse.frequency; - //connections - this._modulator.chain(this._scale, this._pulse.width); - this._pulse.connect(this.output); - this._readOnly([ - 'modulationFrequency', - 'frequency', - 'detune' - ]); - }; - Tone.extend(Tone.PWMOscillator, Tone.Oscillator); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.PWMOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'modulationFrequency': 0.4 - }; - /** - * start the oscillator - * @param {Time} [time=now] - * @private - */ - Tone.PWMOscillator.prototype._start = function (time) { - time = this.toSeconds(time); - this._modulator.start(time); - this._pulse.start(time); - }; - /** - * stop the oscillator - * @param {Time} time (optional) timing parameter - * @private - */ - Tone.PWMOscillator.prototype._stop = function (time) { - time = this.toSeconds(time); - this._modulator.stop(time); - this._pulse.stop(time); - }; - /** - * The type of the oscillator. Always returns "pwm". - * @readOnly - * @memberOf Tone.PWMOscillator# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.PWMOscillator.prototype, 'type', { - get: function () { - return 'pwm'; - } - }); - /** - * The partials of the waveform. Cannot set partials for this waveform type - * @memberOf Tone.PWMOscillator# - * @type {Array} - * @name partials - * @private - */ - Object.defineProperty(Tone.PWMOscillator.prototype, 'partials', { - get: function () { - return []; - } - }); - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.PWMOscillator# - * @type {number} - * @name phase - */ - Object.defineProperty(Tone.PWMOscillator.prototype, 'phase', { - get: function () { - return this._modulator.phase; - }, - set: function (phase) { - this._modulator.phase = phase; - } - }); - /** - * Clean up. - * @return {Tone.PWMOscillator} this - */ - Tone.PWMOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._pulse.dispose(); - this._pulse = null; - this._scale.dispose(); - this._scale = null; - this._modulator.dispose(); - this._modulator = null; - this._writable([ - 'modulationFrequency', - 'frequency', - 'detune' - ]); - this.frequency = null; - this.detune = null; - this.modulationFrequency = null; - return this; - }; - return Tone.PWMOscillator; - }); - Module(function (Tone) { - - /** - * @class Tone.FMOscillator - * - * @extends {Tone.Oscillator} - * @constructor - * @param {Frequency} frequency The starting frequency of the oscillator. - * @param {String} type The type of the carrier oscillator. - * @param {String} modulationType The type of the modulator oscillator. - * @example - * //a sine oscillator frequency-modulated by a square wave - * var fmOsc = new Tone.FMOscillator("Ab3", "sine", "square").toMaster().start(); - */ - Tone.FMOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'type', - 'modulationType' - ], Tone.FMOscillator.defaults); - Tone.Source.call(this, options); - /** - * The carrier oscillator - * @type {Tone.Oscillator} - * @private - */ - this._carrier = new Tone.Oscillator(options.frequency, options.type); - /** - * The oscillator's frequency - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The detune control signal. - * @type {Cents} - * @signal - */ - this.detune = this._carrier.detune; - this.detune.value = options.detune; - /** - * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the - * ratio of the frequency of the modulating signal (mf) to the amplitude of the - * modulating signal (ma) -- as in ma/mf. - * @type {Positive} - * @signal - */ - this.modulationIndex = new Tone.Multiply(options.modulationIndex); - this.modulationIndex.units = Tone.Type.Positive; - /** - * The modulating oscillator - * @type {Tone.Oscillator} - * @private - */ - this._modulator = new Tone.Oscillator(options.frequency, options.modulationType); - /** - * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. - * A harmonicity of 1 gives both oscillators the same frequency. - * Harmonicity = 2 means a change of an octave. - * @type {Positive} - * @signal - * @example - * //pitch the modulator an octave below carrier - * synth.harmonicity.value = 0.5; - */ - this.harmonicity = new Tone.Multiply(options.harmonicity); - this.harmonicity.units = Tone.Type.Positive; - /** - * the node where the modulation happens - * @type {Tone.Gain} - * @private - */ - this._modulationNode = new Tone.Gain(0); - //connections - this.frequency.connect(this._carrier.frequency); - this.frequency.chain(this.harmonicity, this._modulator.frequency); - this.frequency.chain(this.modulationIndex, this._modulationNode); - this._modulator.connect(this._modulationNode.gain); - this._modulationNode.connect(this._carrier.frequency); - this._carrier.connect(this.output); - this.detune.connect(this._modulator.detune); - this.phase = options.phase; - this._readOnly([ - 'modulationIndex', - 'frequency', - 'detune', - 'harmonicity' - ]); - }; - Tone.extend(Tone.FMOscillator, Tone.Oscillator); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.FMOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'modulationIndex': 2, - 'modulationType': 'square', - 'harmonicity': 1 - }; - /** - * start the oscillator - * @param {Time} [time=now] - * @private - */ - Tone.FMOscillator.prototype._start = function (time) { - time = this.toSeconds(time); - this._modulator.start(time); - this._carrier.start(time); - }; - /** - * stop the oscillator - * @param {Time} time (optional) timing parameter - * @private - */ - Tone.FMOscillator.prototype._stop = function (time) { - time = this.toSeconds(time); - this._modulator.stop(time); - this._carrier.stop(time); - }; - /** - * The type of the carrier oscillator - * @memberOf Tone.FMOscillator# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.FMOscillator.prototype, 'type', { - get: function () { - return this._carrier.type; - }, - set: function (type) { - this._carrier.type = type; - } - }); - /** - * The type of the modulator oscillator - * @memberOf Tone.FMOscillator# - * @type {String} - * @name modulationType - */ - Object.defineProperty(Tone.FMOscillator.prototype, 'modulationType', { - get: function () { - return this._modulator.type; - }, - set: function (type) { - this._modulator.type = type; - } - }); - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.FMOscillator# - * @type {number} - * @name phase - */ - Object.defineProperty(Tone.FMOscillator.prototype, 'phase', { - get: function () { - return this._carrier.phase; - }, - set: function (phase) { - this._carrier.phase = phase; - this._modulator.phase = phase; - } - }); - /** - * The partials of the carrier waveform. A partial represents - * the amplitude at a harmonic. The first harmonic is the - * fundamental frequency, the second is the octave and so on - * following the harmonic series. - * Setting this value will automatically set the type to "custom". - * The value is an empty array when the type is not "custom". - * @memberOf Tone.FMOscillator# - * @type {Array} - * @name partials - * @example - * osc.partials = [1, 0.2, 0.01]; - */ - Object.defineProperty(Tone.FMOscillator.prototype, 'partials', { - get: function () { - return this._carrier.partials; - }, - set: function (partials) { - this._carrier.partials = partials; - } - }); - /** - * Clean up. - * @return {Tone.FMOscillator} this - */ - Tone.FMOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._writable([ - 'modulationIndex', - 'frequency', - 'detune', - 'harmonicity' - ]); - this.frequency.dispose(); - this.frequency = null; - this.detune = null; - this.harmonicity.dispose(); - this.harmonicity = null; - this._carrier.dispose(); - this._carrier = null; - this._modulator.dispose(); - this._modulator = null; - this._modulationNode.dispose(); - this._modulationNode = null; - this.modulationIndex.dispose(); - this.modulationIndex = null; - return this; - }; - return Tone.FMOscillator; - }); - Module(function (Tone) { - - /** - * @class Tone.AMOscillator - * - * @extends {Tone.Oscillator} - * @constructor - * @param {Frequency} frequency The starting frequency of the oscillator. - * @param {String} type The type of the carrier oscillator. - * @param {String} modulationType The type of the modulator oscillator. - * @example - * //a sine oscillator frequency-modulated by a square wave - * var fmOsc = new Tone.AMOscillator("Ab3", "sine", "square").toMaster().start(); - */ - Tone.AMOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'type', - 'modulationType' - ], Tone.AMOscillator.defaults); - Tone.Source.call(this, options); - /** - * The carrier oscillator - * @type {Tone.Oscillator} - * @private - */ - this._carrier = new Tone.Oscillator(options.frequency, options.type); - /** - * The oscillator's frequency - * @type {Frequency} - * @signal - */ - this.frequency = this._carrier.frequency; - /** - * The detune control signal. - * @type {Cents} - * @signal - */ - this.detune = this._carrier.detune; - this.detune.value = options.detune; - /** - * The modulating oscillator - * @type {Tone.Oscillator} - * @private - */ - this._modulator = new Tone.Oscillator(options.frequency, options.modulationType); - /** - * convert the -1,1 output to 0,1 - * @type {Tone.AudioToGain} - * @private - */ - this._modulationScale = new Tone.AudioToGain(); - /** - * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. - * A harmonicity of 1 gives both oscillators the same frequency. - * Harmonicity = 2 means a change of an octave. - * @type {Positive} - * @signal - * @example - * //pitch the modulator an octave below carrier - * synth.harmonicity.value = 0.5; - */ - this.harmonicity = new Tone.Multiply(options.harmonicity); - this.harmonicity.units = Tone.Type.Positive; - /** - * the node where the modulation happens - * @type {Tone.Gain} - * @private - */ - this._modulationNode = new Tone.Gain(0); - //connections - this.frequency.chain(this.harmonicity, this._modulator.frequency); - this.detune.connect(this._modulator.detune); - this._modulator.chain(this._modulationScale, this._modulationNode.gain); - this._carrier.chain(this._modulationNode, this.output); - this.phase = options.phase; - this._readOnly([ - 'frequency', - 'detune', - 'harmonicity' - ]); - }; - Tone.extend(Tone.AMOscillator, Tone.Oscillator); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.AMOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'modulationType': 'square', - 'harmonicity': 1 - }; - /** - * start the oscillator - * @param {Time} [time=now] - * @private - */ - Tone.AMOscillator.prototype._start = function (time) { - time = this.toSeconds(time); - this._modulator.start(time); - this._carrier.start(time); - }; - /** - * stop the oscillator - * @param {Time} time (optional) timing parameter - * @private - */ - Tone.AMOscillator.prototype._stop = function (time) { - time = this.toSeconds(time); - this._modulator.stop(time); - this._carrier.stop(time); - }; - /** - * The type of the carrier oscillator - * @memberOf Tone.AMOscillator# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.AMOscillator.prototype, 'type', { - get: function () { - return this._carrier.type; - }, - set: function (type) { - this._carrier.type = type; - } - }); - /** - * The type of the modulator oscillator - * @memberOf Tone.AMOscillator# - * @type {string} - * @name modulationType - */ - Object.defineProperty(Tone.AMOscillator.prototype, 'modulationType', { - get: function () { - return this._modulator.type; - }, - set: function (type) { - this._modulator.type = type; - } - }); - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.AMOscillator# - * @type {number} - * @name phase - */ - Object.defineProperty(Tone.AMOscillator.prototype, 'phase', { - get: function () { - return this._carrier.phase; - }, - set: function (phase) { - this._carrier.phase = phase; - this._modulator.phase = phase; - } - }); - /** - * The partials of the carrier waveform. A partial represents - * the amplitude at a harmonic. The first harmonic is the - * fundamental frequency, the second is the octave and so on - * following the harmonic series. - * Setting this value will automatically set the type to "custom". - * The value is an empty array when the type is not "custom". - * @memberOf Tone.AMOscillator# - * @type {Array} - * @name partials - * @example - * osc.partials = [1, 0.2, 0.01]; - */ - Object.defineProperty(Tone.AMOscillator.prototype, 'partials', { - get: function () { - return this._carrier.partials; - }, - set: function (partials) { - this._carrier.partials = partials; - } - }); - /** - * Clean up. - * @return {Tone.AMOscillator} this - */ - Tone.AMOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'detune', - 'harmonicity' - ]); - this.frequency = null; - this.detune = null; - this.harmonicity.dispose(); - this.harmonicity = null; - this._carrier.dispose(); - this._carrier = null; - this._modulator.dispose(); - this._modulator = null; - this._modulationNode.dispose(); - this._modulationNode = null; - this._modulationScale.dispose(); - this._modulationScale = null; - return this; - }; - return Tone.AMOscillator; - }); - Module(function (Tone) { - - /** - * @class Tone.FatOscillator - * - * @extends {Tone.Oscillator} - * @constructor - * @param {Frequency} frequency The starting frequency of the oscillator. - * @param {String} type The type of the carrier oscillator. - * @param {String} modulationType The type of the modulator oscillator. - * @example - * //a sine oscillator frequency-modulated by a square wave - * var fmOsc = new Tone.FatOscillator("Ab3", "sine", "square").toMaster().start(); - */ - Tone.FatOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'type', - 'spread' - ], Tone.FatOscillator.defaults); - Tone.Source.call(this, options); - /** - * The oscillator's frequency - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The detune control signal. - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - /** - * The array of oscillators - * @type {Array} - * @private - */ - this._oscillators = []; - /** - * The total spread of the oscillators - * @type {Cents} - * @private - */ - this._spread = options.spread; - /** - * The type of the oscillator - * @type {String} - * @private - */ - this._type = options.type; - /** - * The phase of the oscillators - * @type {Degrees} - * @private - */ - this._phase = options.phase; - /** - * The partials array - * @type {Array} - * @private - */ - this._partials = this.defaultArg(options.partials, []); - //set the count initially - this.count = options.count; - this._readOnly([ - 'frequency', - 'detune' - ]); - }; - Tone.extend(Tone.FatOscillator, Tone.Oscillator); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.FatOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'phase': 0, - 'spread': 20, - 'count': 3, - 'type': 'sawtooth' - }; - /** - * start the oscillator - * @param {Time} [time=now] - * @private - */ - Tone.FatOscillator.prototype._start = function (time) { - time = this.toSeconds(time); - this._forEach(function (osc) { - osc.start(time); - }); - }; - /** - * stop the oscillator - * @param {Time} time (optional) timing parameter - * @private - */ - Tone.FatOscillator.prototype._stop = function (time) { - time = this.toSeconds(time); - this._forEach(function (osc) { - osc.stop(time); - }); - }; - /** - * Iterate over all of the oscillators - * @param {Function} iterator The iterator function - * @private - */ - Tone.FatOscillator.prototype._forEach = function (iterator) { - for (var i = 0; i < this._oscillators.length; i++) { - iterator.call(this, this._oscillators[i], i); - } - }; - /** - * The type of the carrier oscillator - * @memberOf Tone.FatOscillator# - * @type {string} - * @name type - */ - Object.defineProperty(Tone.FatOscillator.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - this._type = type; - this._forEach(function (osc) { - osc.type = type; - }); - } - }); - /** - * The detune spread between the oscillators. If "count" is - * set to 3 oscillators and the "spread" is set to 40, - * the three oscillators would be detuned like this: [-20, 0, 20] - * for a total detune spread of 40 cents. - * @memberOf Tone.FatOscillator# - * @type {Cents} - * @name spread - */ - Object.defineProperty(Tone.FatOscillator.prototype, 'spread', { - get: function () { - return this._spread; - }, - set: function (spread) { - this._spread = spread; - if (this._oscillators.length > 1) { - var start = -spread / 2; - var step = spread / (this._oscillators.length - 1); - this._forEach(function (osc, i) { - osc.detune.value = start + step * i; - }); - } - } - }); - /** - * The number of detuned oscillators - * @memberOf Tone.FatOscillator# - * @type {Number} - * @name count - */ - Object.defineProperty(Tone.FatOscillator.prototype, 'count', { - get: function () { - return this._oscillators.length; - }, - set: function (count) { - count = Math.max(count, 1); - if (this._oscillators.length !== count) { - // var partials = this.partials; - // var type = this.type; - //dispose the previous oscillators - this._forEach(function (osc) { - osc.dispose(); - }); - this._oscillators = []; - for (var i = 0; i < count; i++) { - var osc = new Tone.Oscillator(); - if (this.type === Tone.Oscillator.Type.Custom) { - osc.partials = this._partials; - } else { - osc.type = this._type; - } - osc.phase = this._phase; - osc.volume.value = -6 - count; - this.frequency.connect(osc.frequency); - this.detune.connect(osc.detune); - osc.connect(this.output); - this._oscillators[i] = osc; - } - //set the spread - this.spread = this._spread; - if (this.state === Tone.State.Started) { - this._forEach(function (osc) { - osc.start(); - }); - } - } - } - }); - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.FatOscillator# - * @type {Number} - * @name phase - */ - Object.defineProperty(Tone.FatOscillator.prototype, 'phase', { - get: function () { - return this._phase; - }, - set: function (phase) { - this._phase = phase; - this._forEach(function (osc) { - osc.phase = phase; - }); - } - }); - /** - * The partials of the carrier waveform. A partial represents - * the amplitude at a harmonic. The first harmonic is the - * fundamental frequency, the second is the octave and so on - * following the harmonic series. - * Setting this value will automatically set the type to "custom". - * The value is an empty array when the type is not "custom". - * @memberOf Tone.FatOscillator# - * @type {Array} - * @name partials - * @example - * osc.partials = [1, 0.2, 0.01]; - */ - Object.defineProperty(Tone.FatOscillator.prototype, 'partials', { - get: function () { - return this._partials; - }, - set: function (partials) { - this._partials = partials; - this._type = Tone.Oscillator.Type.Custom; - this._forEach(function (osc) { - osc.partials = partials; - }); - } - }); - /** - * Clean up. - * @return {Tone.FatOscillator} this - */ - Tone.FatOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'detune' - ]); - this.frequency.dispose(); - this.frequency = null; - this.detune.dispose(); - this.detune = null; - this._forEach(function (osc) { - osc.dispose(); - }); - this._oscillators = null; - this._partials = null; - return this; - }; - return Tone.FatOscillator; - }); - Module(function (Tone) { - - /** - * @class Tone.OmniOscillator aggregates Tone.Oscillator, Tone.PulseOscillator, - * Tone.PWMOscillator, Tone.FMOscillator, Tone.AMOscillator, and Tone.FatOscillator - * into one class. The oscillator class can be changed by setting the `type`. - * `omniOsc.type = "pwm"` will set it to the Tone.PWMOscillator. Prefixing - * any of the basic types ("sine", "square4", etc.) with "fm", "am", or "fat" - * will use the FMOscillator, AMOscillator or FatOscillator respectively. - * For example: `omniOsc.type = "fatsawtooth"` will create set the oscillator - * to a FatOscillator of type "sawtooth". - * - * @extends {Tone.Oscillator} - * @constructor - * @param {Frequency} frequency The initial frequency of the oscillator. - * @param {String} type The type of the oscillator. - * @example - * var omniOsc = new Tone.OmniOscillator("C#4", "pwm"); - */ - Tone.OmniOscillator = function () { - var options = this.optionsObject(arguments, [ - 'frequency', - 'type' - ], Tone.OmniOscillator.defaults); - Tone.Source.call(this, options); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The detune control - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - /** - * the type of the oscillator source - * @type {String} - * @private - */ - this._sourceType = undefined; - /** - * the oscillator - * @type {Tone.Oscillator} - * @private - */ - this._oscillator = null; - //set the oscillator - this.type = options.type; - this._readOnly([ - 'frequency', - 'detune' - ]); - //set the options - this.set(options); - }; - Tone.extend(Tone.OmniOscillator, Tone.Oscillator); - /** - * default values - * @static - * @type {Object} - * @const - */ - Tone.OmniOscillator.defaults = { - 'frequency': 440, - 'detune': 0, - 'type': 'sine', - 'phase': 0 - }; - /** - * @enum {String} - * @private - */ - var OmniOscType = { - Pulse: 'PulseOscillator', - PWM: 'PWMOscillator', - Osc: 'Oscillator', - FM: 'FMOscillator', - AM: 'AMOscillator', - Fat: 'FatOscillator' - }; - /** - * start the oscillator - * @param {Time} [time=now] the time to start the oscillator - * @private - */ - Tone.OmniOscillator.prototype._start = function (time) { - this._oscillator.start(time); - }; - /** - * start the oscillator - * @param {Time} [time=now] the time to start the oscillator - * @private - */ - Tone.OmniOscillator.prototype._stop = function (time) { - this._oscillator.stop(time); - }; - /** - * The type of the oscillator. Can be any of the basic types: sine, square, triangle, sawtooth. Or - * prefix the basic types with "fm", "am", or "fat" to use the FMOscillator, AMOscillator or FatOscillator - * types. The oscillator could also be set to "pwm" or "pulse". All of the parameters of the - * oscillator's class are accessible when the oscillator is set to that type, but throws an error - * when it's not. - * - * @memberOf Tone.OmniOscillator# - * @type {String} - * @name type - * @example - * omniOsc.type = "pwm"; - * //modulationFrequency is parameter which is available - * //only when the type is "pwm". - * omniOsc.modulationFrequency.value = 0.5; - * @example - * //an square wave frequency modulated by a sawtooth - * omniOsc.type = "fmsquare"; - * omniOsc.modulationType = "sawtooth"; - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'type', { - get: function () { - var prefix = ''; - if (this._sourceType === OmniOscType.FM) { - prefix = 'fm'; - } else if (this._sourceType === OmniOscType.AM) { - prefix = 'am'; - } else if (this._sourceType === OmniOscType.Fat) { - prefix = 'fat'; - } - return prefix + this._oscillator.type; - }, - set: function (type) { - if (type.substr(0, 2) === 'fm') { - this._createNewOscillator(OmniOscType.FM); - this._oscillator.type = type.substr(2); - } else if (type.substr(0, 2) === 'am') { - this._createNewOscillator(OmniOscType.AM); - this._oscillator.type = type.substr(2); - } else if (type.substr(0, 3) === 'fat') { - this._createNewOscillator(OmniOscType.Fat); - this._oscillator.type = type.substr(3); - } else if (type === 'pwm') { - this._createNewOscillator(OmniOscType.PWM); - } else if (type === 'pulse') { - this._createNewOscillator(OmniOscType.Pulse); - } else { - this._createNewOscillator(OmniOscType.Osc); - this._oscillator.type = type; - } - } - }); - /** - * The partials of the waveform. A partial represents - * the amplitude at a harmonic. The first harmonic is the - * fundamental frequency, the second is the octave and so on - * following the harmonic series. - * Setting this value will automatically set the type to "custom". - * The value is an empty array when the type is not "custom". - * This is not available on "pwm" and "pulse" oscillator types. - * @memberOf Tone.OmniOscillator# - * @type {Array} - * @name partials - * @example - * osc.partials = [1, 0.2, 0.01]; - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'partials', { - get: function () { - return this._oscillator.partials; - }, - set: function (partials) { - this._oscillator.partials = partials; - } - }); - /** - * Set a member/attribute of the oscillator. - * @param {Object|String} params - * @param {number=} value - * @param {Time=} rampTime - * @returns {Tone.OmniOscillator} this - */ - Tone.OmniOscillator.prototype.set = function (params, value) { - //make sure the type is set first - if (params === 'type') { - this.type = value; - } else if (this.isObject(params) && params.hasOwnProperty('type')) { - this.type = params.type; - } - //then set the rest - Tone.prototype.set.apply(this, arguments); - return this; - }; - /** - * connect the oscillator to the frequency and detune signals - * @private - */ - Tone.OmniOscillator.prototype._createNewOscillator = function (oscType) { - if (oscType !== this._sourceType) { - this._sourceType = oscType; - var OscillatorConstructor = Tone[oscType]; - //short delay to avoid clicks on the change - var now = this.now() + this.blockTime; - if (this._oscillator !== null) { - var oldOsc = this._oscillator; - oldOsc.stop(now); - //dispose the old one - setTimeout(function () { - oldOsc.dispose(); - oldOsc = null; - }, this.blockTime * 1000); - } - this._oscillator = new OscillatorConstructor(); - this.frequency.connect(this._oscillator.frequency); - this.detune.connect(this._oscillator.detune); - this._oscillator.connect(this.output); - if (this.state === Tone.State.Started) { - this._oscillator.start(now); - } - } - }; - /** - * The phase of the oscillator in degrees. - * @memberOf Tone.OmniOscillator# - * @type {Degrees} - * @name phase - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'phase', { - get: function () { - return this._oscillator.phase; - }, - set: function (phase) { - this._oscillator.phase = phase; - } - }); - /** - * The width of the oscillator (only if the oscillator is set to "pulse") - * @memberOf Tone.OmniOscillator# - * @type {NormalRange} - * @signal - * @name width - * @example - * var omniOsc = new Tone.OmniOscillator(440, "pulse"); - * //can access the width attribute only if type === "pulse" - * omniOsc.width.value = 0.2; - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'width', { - get: function () { - if (this._sourceType === OmniOscType.Pulse) { - return this._oscillator.width; - } - } - }); - /** - * The number of detuned oscillators - * @memberOf Tone.OmniOscillator# - * @type {Number} - * @name count - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'count', { - get: function () { - if (this._sourceType === OmniOscType.Fat) { - return this._oscillator.count; - } - }, - set: function (count) { - if (this._sourceType === OmniOscType.Fat) { - this._oscillator.count = count; - } - } - }); - /** - * The detune spread between the oscillators. If "count" is - * set to 3 oscillators and the "spread" is set to 40, - * the three oscillators would be detuned like this: [-20, 0, 20] - * for a total detune spread of 40 cents. See Tone.FatOscillator - * for more info. - * @memberOf Tone.OmniOscillator# - * @type {Cents} - * @name spread - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'spread', { - get: function () { - if (this._sourceType === OmniOscType.Fat) { - return this._oscillator.spread; - } - }, - set: function (spread) { - if (this._sourceType === OmniOscType.Fat) { - this._oscillator.spread = spread; - } - } - }); - /** - * The type of the modulator oscillator. Only if the oscillator - * is set to "am" or "fm" types. see. Tone.AMOscillator or Tone.FMOscillator - * for more info. - * @memberOf Tone.OmniOscillator# - * @type {String} - * @name modulationType - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationType', { - get: function () { - if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { - return this._oscillator.modulationType; - } - }, - set: function (mType) { - if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { - this._oscillator.modulationType = mType; - } - } - }); - /** - * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the - * ratio of the frequency of the modulating signal (mf) to the amplitude of the - * modulating signal (ma) -- as in ma/mf. - * See Tone.FMOscillator for more info. - * @type {Positive} - * @signal - * @name modulationIndex - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationIndex', { - get: function () { - if (this._sourceType === OmniOscType.FM) { - return this._oscillator.modulationIndex; - } - } - }); - /** - * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. - * A harmonicity of 1 gives both oscillators the same frequency. - * Harmonicity = 2 means a change of an octave. See Tone.AMOscillator or Tone.FMOscillator - * for more info. - * @memberOf Tone.OmniOscillator# - * @signal - * @type {Positive} - * @name harmonicity - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'harmonicity', { - get: function () { - if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { - return this._oscillator.harmonicity; - } - } - }); - /** - * The modulationFrequency Signal of the oscillator - * (only if the oscillator type is set to pwm). See - * Tone.PWMOscillator for more info. - * @memberOf Tone.OmniOscillator# - * @type {Frequency} - * @signal - * @name modulationFrequency - * @example - * var omniOsc = new Tone.OmniOscillator(440, "pwm"); - * //can access the modulationFrequency attribute only if type === "pwm" - * omniOsc.modulationFrequency.value = 0.2; - */ - Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationFrequency', { - get: function () { - if (this._sourceType === OmniOscType.PWM) { - return this._oscillator.modulationFrequency; - } - } - }); - /** - * Clean up. - * @return {Tone.OmniOscillator} this - */ - Tone.OmniOscillator.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'detune' - ]); - this.detune.dispose(); - this.detune = null; - this.frequency.dispose(); - this.frequency = null; - this._oscillator.dispose(); - this._oscillator = null; - this._sourceType = null; - return this; - }; - return Tone.OmniOscillator; - }); - Module(function (Tone) { - - /** - * @class Base-class for all instruments - * - * @constructor - * @extends {Tone} - */ - Tone.Instrument = function (options) { - //get the defaults - options = this.defaultArg(options, Tone.Instrument.defaults); - /** - * The output and volume triming node - * @type {Tone.Volume} - * @private - */ - this._volume = this.output = new Tone.Volume(options.volume); - /** - * The volume of the output in decibels. - * @type {Decibels} - * @signal - * @example - * source.volume.value = -6; - */ - this.volume = this._volume.volume; - this._readOnly('volume'); - }; - Tone.extend(Tone.Instrument); - /** - * the default attributes - * @type {object} - */ - Tone.Instrument.defaults = { - /** the volume of the output in decibels */ - 'volume': 0 - }; - /** - * @abstract - * @param {string|number} note the note to trigger - * @param {Time} [time=now] the time to trigger the ntoe - * @param {number} [velocity=1] the velocity to trigger the note - */ - Tone.Instrument.prototype.triggerAttack = Tone.noOp; - /** - * @abstract - * @param {Time} [time=now] when to trigger the release - */ - Tone.Instrument.prototype.triggerRelease = Tone.noOp; - /** - * Trigger the attack and then the release after the duration. - * @param {Frequency} note The note to trigger. - * @param {Time} duration How long the note should be held for before - * triggering the release. This value must be greater than 0. - * @param {Time} [time=now] When the note should be triggered. - * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. - * @returns {Tone.Instrument} this - * @example - * //trigger "C4" for the duration of an 8th note - * synth.triggerAttackRelease("C4", "8n"); - */ - Tone.Instrument.prototype.triggerAttackRelease = function (note, duration, time, velocity) { - if (this.isUndef(time)) { - time = this.now() + this.blockTime; - } else { - time = this.toSeconds(time); - } - duration = this.toSeconds(duration); - this.triggerAttack(note, time, velocity); - this.triggerRelease(time + duration); - return this; - }; - /** - * clean up - * @returns {Tone.Instrument} this - */ - Tone.Instrument.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._volume.dispose(); - this._volume = null; - this._writable(['volume']); - this.volume = null; - return this; - }; - return Tone.Instrument; - }); - Module(function (Tone) { - - /** - * @class This is an abstract base class for other monophonic instruments to - * extend. IMPORTANT: It does not make any sound on its own and - * shouldn't be directly instantiated. - * - * @constructor - * @abstract - * @extends {Tone.Instrument} - */ - Tone.Monophonic = function (options) { - //get the defaults - options = this.defaultArg(options, Tone.Monophonic.defaults); - Tone.Instrument.call(this, options); - /** - * The glide time between notes. - * @type {Time} - */ - this.portamento = options.portamento; - }; - Tone.extend(Tone.Monophonic, Tone.Instrument); - /** - * @static - * @const - * @type {Object} - */ - Tone.Monophonic.defaults = { 'portamento': 0 }; - /** - * Trigger the attack of the note optionally with a given velocity. - * - * - * @param {Frequency} note The note to trigger. - * @param {Time} [time=now] When the note should start. - * @param {number} [velocity=1] velocity The velocity scaler - * determines how "loud" the note - * will be triggered. - * @returns {Tone.Monophonic} this - * @example - * synth.triggerAttack("C4"); - * @example - * //trigger the note a half second from now at half velocity - * synth.triggerAttack("C4", "+0.5", 0.5); - */ - Tone.Monophonic.prototype.triggerAttack = function (note, time, velocity) { - if (this.isUndef(time)) { - time = this.now() + this.blockTime; - } else { - time = this.toSeconds(time); - } - this._triggerEnvelopeAttack(time, velocity); - this.setNote(note, time); - return this; - }; - /** - * Trigger the release portion of the envelope - * @param {Time} [time=now] If no time is given, the release happens immediatly - * @returns {Tone.Monophonic} this - * @example - * synth.triggerRelease(); - */ - Tone.Monophonic.prototype.triggerRelease = function (time) { - if (this.isUndef(time)) { - time = this.now() + this.blockTime; - } else { - time = this.toSeconds(time); - } - this._triggerEnvelopeRelease(time); - return this; - }; - /** - * override this method with the actual method - * @abstract - * @private - */ - Tone.Monophonic.prototype._triggerEnvelopeAttack = function () { - }; - /** - * override this method with the actual method - * @abstract - * @private - */ - Tone.Monophonic.prototype._triggerEnvelopeRelease = function () { - }; - /** - * Set the note at the given time. If no time is given, the note - * will set immediately. - * @param {Frequency} note The note to change to. - * @param {Time} [time=now] The time when the note should be set. - * @returns {Tone.Monophonic} this - * @example - * //change to F#6 in one quarter note from now. - * synth.setNote("F#6", "+4n"); - * @example - * //change to Bb4 right now - * synth.setNote("Bb4"); - */ - Tone.Monophonic.prototype.setNote = function (note, time) { - time = this.toSeconds(time); - if (this.portamento > 0) { - var currentNote = this.frequency.value; - this.frequency.setValueAtTime(currentNote, time); - var portTime = this.toSeconds(this.portamento); - this.frequency.exponentialRampToValueAtTime(note, time + portTime); - } else { - this.frequency.setValueAtTime(note, time); - } - return this; - }; - return Tone.Monophonic; - }); - Module(function (Tone) { - - /** - * @class Tone.Synth is composed simply of a Tone.OmniOscillator - * routed through a Tone.AmplitudeEnvelope. - * - * - * @constructor - * @extends {Tone.Monophonic} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var synth = new Tone.Synth().toMaster(); - * synth.triggerAttackRelease("C4", "8n"); - */ - Tone.Synth = function (options) { - //get the defaults - options = this.defaultArg(options, Tone.Synth.defaults); - Tone.Monophonic.call(this, options); - /** - * The oscillator. - * @type {Tone.OmniOscillator} - */ - this.oscillator = new Tone.OmniOscillator(options.oscillator); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = this.oscillator.frequency; - /** - * The detune control. - * @type {Cents} - * @signal - */ - this.detune = this.oscillator.detune; - /** - * The amplitude envelope. - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = new Tone.AmplitudeEnvelope(options.envelope); - //connect the oscillators to the output - this.oscillator.chain(this.envelope, this.output); - //start the oscillators - this.oscillator.start(); - this._readOnly([ - 'oscillator', - 'frequency', - 'detune', - 'envelope' - ]); - }; - Tone.extend(Tone.Synth, Tone.Monophonic); - /** - * @const - * @static - * @type {Object} - */ - Tone.Synth.defaults = { - 'oscillator': { 'type': 'triangle' }, - 'envelope': { - 'attack': 0.005, - 'decay': 0.1, - 'sustain': 0.3, - 'release': 1 - } - }; - /** - * start the attack portion of the envelope - * @param {Time} [time=now] the time the attack should start - * @param {number} [velocity=1] the velocity of the note (0-1) - * @returns {Tone.Synth} this - * @private - */ - Tone.Synth.prototype._triggerEnvelopeAttack = function (time, velocity) { - //the envelopes - this.envelope.triggerAttack(time, velocity); - return this; - }; - /** - * start the release portion of the envelope - * @param {Time} [time=now] the time the release should start - * @returns {Tone.Synth} this - * @private - */ - Tone.Synth.prototype._triggerEnvelopeRelease = function (time) { - this.envelope.triggerRelease(time); - return this; - }; - /** - * clean up - * @returns {Tone.Synth} this - */ - Tone.Synth.prototype.dispose = function () { - Tone.Monophonic.prototype.dispose.call(this); - this._writable([ - 'oscillator', - 'frequency', - 'detune', - 'envelope' - ]); - this.oscillator.dispose(); - this.oscillator = null; - this.envelope.dispose(); - this.envelope = null; - this.frequency = null; - this.detune = null; - return this; - }; - return Tone.Synth; - }); - Module(function (Tone) { - - /** - * @class AMSynth uses the output of one Tone.Synth to modulate the - * amplitude of another Tone.Synth. The harmonicity (the ratio between - * the two signals) affects the timbre of the output signal greatly. - * Read more about Amplitude Modulation Synthesis on - * [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). - * - * - * @constructor - * @extends {Tone.Monophonic} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var synth = new Tone.AMSynth().toMaster(); - * synth.triggerAttackRelease("C4", "4n"); - */ - Tone.AMSynth = function (options) { - options = this.defaultArg(options, Tone.AMSynth.defaults); - Tone.Monophonic.call(this, options); - /** - * The carrier voice. - * @type {Tone.Synth} - * @private - */ - this._carrier = new Tone.Synth(); - this._carrier.volume.value = -10; - /** - * The carrier's oscillator - * @type {Tone.Oscillator} - */ - this.oscillator = this._carrier.oscillator; - /** - * The carrier's envelope - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = this._carrier.envelope.set(options.envelope); - /** - * The modulator voice. - * @type {Tone.Synth} - * @private - */ - this._modulator = new Tone.Synth(); - this._modulator.volume.value = -10; - /** - * The modulator's oscillator which is applied - * to the amplitude of the oscillator - * @type {Tone.Oscillator} - */ - this.modulation = this._modulator.oscillator.set(options.modulation); - /** - * The modulator's envelope - * @type {Tone.AmplitudeEnvelope} - */ - this.modulationEnvelope = this._modulator.envelope.set(options.modulationEnvelope); - /** - * The frequency. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(440, Tone.Type.Frequency); - /** - * The detune in cents - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - /** - * Harmonicity is the ratio between the two voices. A harmonicity of - * 1 is no change. Harmonicity = 2 means a change of an octave. - * @type {Positive} - * @signal - * @example - * //pitch voice1 an octave below voice0 - * synth.harmonicity.value = 0.5; - */ - this.harmonicity = new Tone.Multiply(options.harmonicity); - this.harmonicity.units = Tone.Type.Positive; - /** - * convert the -1,1 output to 0,1 - * @type {Tone.AudioToGain} - * @private - */ - this._modulationScale = new Tone.AudioToGain(); - /** - * the node where the modulation happens - * @type {Tone.Gain} - * @private - */ - this._modulationNode = new Tone.Gain(); - //control the two voices frequency - this.frequency.connect(this._carrier.frequency); - this.frequency.chain(this.harmonicity, this._modulator.frequency); - this.detune.fan(this._carrier.detune, this._modulator.detune); - this._modulator.chain(this._modulationScale, this._modulationNode.gain); - this._carrier.chain(this._modulationNode, this.output); - this._readOnly([ - 'frequency', - 'harmonicity', - 'oscillator', - 'envelope', - 'modulation', - 'modulationEnvelope', - 'detune' - ]); - }; - Tone.extend(Tone.AMSynth, Tone.Monophonic); - /** - * @static - * @type {Object} - */ - Tone.AMSynth.defaults = { - 'harmonicity': 3, - 'detune': 0, - 'oscillator': { 'type': 'sine' }, - 'envelope': { - 'attack': 0.01, - 'decay': 0.01, - 'sustain': 1, - 'release': 0.5 - }, - 'modulation': { 'type': 'square' }, - 'modulationEnvelope': { - 'attack': 0.5, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - } - }; - /** - * trigger the attack portion of the note - * - * @param {Time} [time=now] the time the note will occur - * @param {NormalRange} [velocity=1] the velocity of the note - * @private - * @returns {Tone.AMSynth} this - */ - Tone.AMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { - //the port glide - time = this.toSeconds(time); - //the envelopes - this.envelope.triggerAttack(time, velocity); - this.modulationEnvelope.triggerAttack(time, velocity); - return this; - }; - /** - * trigger the release portion of the note - * - * @param {Time} [time=now] the time the note will release - * @private - * @returns {Tone.AMSynth} this - */ - Tone.AMSynth.prototype._triggerEnvelopeRelease = function (time) { - this.envelope.triggerRelease(time); - this.modulationEnvelope.triggerRelease(time); - return this; - }; - /** - * clean up - * @returns {Tone.AMSynth} this - */ - Tone.AMSynth.prototype.dispose = function () { - Tone.Monophonic.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'harmonicity', - 'oscillator', - 'envelope', - 'modulation', - 'modulationEnvelope', - 'detune' - ]); - this._carrier.dispose(); - this._carrier = null; - this._modulator.dispose(); - this._modulator = null; - this.frequency.dispose(); - this.frequency = null; - this.detune.dispose(); - this.detune = null; - this.harmonicity.dispose(); - this.harmonicity = null; - this._modulationScale.dispose(); - this._modulationScale = null; - this._modulationNode.dispose(); - this._modulationNode = null; - this.oscillator = null; - this.envelope = null; - this.modulationEnvelope = null; - this.modulation = null; - return this; - }; - return Tone.AMSynth; - }); - Module(function (Tone) { - - /** - * @class Tone.MonoSynth is composed of one oscillator, one filter, and two envelopes. - * The amplitude of the Tone.Oscillator and the cutoff frequency of the - * Tone.Filter are controlled by Tone.Envelopes. - * - * - * @constructor - * @extends {Tone.Monophonic} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var synth = new Tone.MonoSynth({ - * "oscillator" : { - * "type" : "square" - * }, - * "envelope" : { - * "attack" : 0.1 - * } - * }).toMaster(); - * synth.triggerAttackRelease("C4", "8n"); - */ - Tone.MonoSynth = function (options) { - //get the defaults - options = this.defaultArg(options, Tone.MonoSynth.defaults); - Tone.Monophonic.call(this, options); - /** - * The oscillator. - * @type {Tone.OmniOscillator} - */ - this.oscillator = new Tone.OmniOscillator(options.oscillator); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = this.oscillator.frequency; - /** - * The detune control. - * @type {Cents} - * @signal - */ - this.detune = this.oscillator.detune; - /** - * The filter. - * @type {Tone.Filter} - */ - this.filter = new Tone.Filter(options.filter); - /** - * The filter envelope. - * @type {Tone.FrequencyEnvelope} - */ - this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); - /** - * The amplitude envelope. - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = new Tone.AmplitudeEnvelope(options.envelope); - //connect the oscillators to the output - this.oscillator.chain(this.filter, this.envelope, this.output); - //start the oscillators - this.oscillator.start(); - //connect the filter envelope - this.filterEnvelope.connect(this.filter.frequency); - this._readOnly([ - 'oscillator', - 'frequency', - 'detune', - 'filter', - 'filterEnvelope', - 'envelope' - ]); - }; - Tone.extend(Tone.MonoSynth, Tone.Monophonic); - /** - * @const - * @static - * @type {Object} - */ - Tone.MonoSynth.defaults = { - 'frequency': 'C4', - 'detune': 0, - 'oscillator': { 'type': 'square' }, - 'filter': { - 'Q': 6, - 'type': 'lowpass', - 'rolloff': -24 - }, - 'envelope': { - 'attack': 0.005, - 'decay': 0.1, - 'sustain': 0.9, - 'release': 1 - }, - 'filterEnvelope': { - 'attack': 0.06, - 'decay': 0.2, - 'sustain': 0.5, - 'release': 2, - 'baseFrequency': 200, - 'octaves': 7, - 'exponent': 2 - } - }; - /** - * start the attack portion of the envelope - * @param {Time} [time=now] the time the attack should start - * @param {NormalRange} [velocity=1] the velocity of the note (0-1) - * @returns {Tone.MonoSynth} this - * @private - */ - Tone.MonoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { - //the envelopes - this.envelope.triggerAttack(time, velocity); - this.filterEnvelope.triggerAttack(time); - return this; - }; - /** - * start the release portion of the envelope - * @param {Time} [time=now] the time the release should start - * @returns {Tone.MonoSynth} this - * @private - */ - Tone.MonoSynth.prototype._triggerEnvelopeRelease = function (time) { - this.envelope.triggerRelease(time); - this.filterEnvelope.triggerRelease(time); - return this; - }; - /** - * clean up - * @returns {Tone.MonoSynth} this - */ - Tone.MonoSynth.prototype.dispose = function () { - Tone.Monophonic.prototype.dispose.call(this); - this._writable([ - 'oscillator', - 'frequency', - 'detune', - 'filter', - 'filterEnvelope', - 'envelope' - ]); - this.oscillator.dispose(); - this.oscillator = null; - this.envelope.dispose(); - this.envelope = null; - this.filterEnvelope.dispose(); - this.filterEnvelope = null; - this.filter.dispose(); - this.filter = null; - this.frequency = null; - this.detune = null; - return this; - }; - return Tone.MonoSynth; - }); - Module(function (Tone) { - - /** - * @class Tone.DuoSynth is a monophonic synth composed of two - * MonoSynths run in parallel with control over the - * frequency ratio between the two voices and vibrato effect. - * - * - * @constructor - * @extends {Tone.Monophonic} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var duoSynth = new Tone.DuoSynth().toMaster(); - * duoSynth.triggerAttackRelease("C4", "2n"); - */ - Tone.DuoSynth = function (options) { - options = this.defaultArg(options, Tone.DuoSynth.defaults); - Tone.Monophonic.call(this, options); - /** - * the first voice - * @type {Tone.MonoSynth} - */ - this.voice0 = new Tone.MonoSynth(options.voice0); - this.voice0.volume.value = -10; - /** - * the second voice - * @type {Tone.MonoSynth} - */ - this.voice1 = new Tone.MonoSynth(options.voice1); - this.voice1.volume.value = -10; - /** - * The vibrato LFO. - * @type {Tone.LFO} - * @private - */ - this._vibrato = new Tone.LFO(options.vibratoRate, -50, 50); - this._vibrato.start(); - /** - * the vibrato frequency - * @type {Frequency} - * @signal - */ - this.vibratoRate = this._vibrato.frequency; - /** - * the vibrato gain - * @type {Tone.Gain} - * @private - */ - this._vibratoGain = new Tone.Gain(options.vibratoAmount, Tone.Type.Positive); - /** - * The amount of vibrato - * @type {Positive} - * @signal - */ - this.vibratoAmount = this._vibratoGain.gain; - /** - * the frequency control - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(440, Tone.Type.Frequency); - /** - * Harmonicity is the ratio between the two voices. A harmonicity of - * 1 is no change. Harmonicity = 2 means a change of an octave. - * @type {Positive} - * @signal - * @example - * //pitch voice1 an octave below voice0 - * duoSynth.harmonicity.value = 0.5; - */ - this.harmonicity = new Tone.Multiply(options.harmonicity); - this.harmonicity.units = Tone.Type.Positive; - //control the two voices frequency - this.frequency.connect(this.voice0.frequency); - this.frequency.chain(this.harmonicity, this.voice1.frequency); - this._vibrato.connect(this._vibratoGain); - this._vibratoGain.fan(this.voice0.detune, this.voice1.detune); - this.voice0.connect(this.output); - this.voice1.connect(this.output); - this._readOnly([ - 'voice0', - 'voice1', - 'frequency', - 'vibratoAmount', - 'vibratoRate' - ]); - }; - Tone.extend(Tone.DuoSynth, Tone.Monophonic); - /** - * @static - * @type {Object} - */ - Tone.DuoSynth.defaults = { - 'vibratoAmount': 0.5, - 'vibratoRate': 5, - 'harmonicity': 1.5, - 'voice0': { - 'volume': -10, - 'portamento': 0, - 'oscillator': { 'type': 'sine' }, - 'filterEnvelope': { - 'attack': 0.01, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - }, - 'envelope': { - 'attack': 0.01, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - } - }, - 'voice1': { - 'volume': -10, - 'portamento': 0, - 'oscillator': { 'type': 'sine' }, - 'filterEnvelope': { - 'attack': 0.01, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - }, - 'envelope': { - 'attack': 0.01, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - } - } - }; - /** - * start the attack portion of the envelopes - * - * @param {Time} [time=now] the time the attack should start - * @param {NormalRange} [velocity=1] the velocity of the note (0-1) - * @returns {Tone.DuoSynth} this - * @private - */ - Tone.DuoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { - time = this.toSeconds(time); - this.voice0.envelope.triggerAttack(time, velocity); - this.voice1.envelope.triggerAttack(time, velocity); - this.voice0.filterEnvelope.triggerAttack(time); - this.voice1.filterEnvelope.triggerAttack(time); - return this; - }; - /** - * start the release portion of the envelopes - * - * @param {Time} [time=now] the time the release should start - * @returns {Tone.DuoSynth} this - * @private - */ - Tone.DuoSynth.prototype._triggerEnvelopeRelease = function (time) { - this.voice0.triggerRelease(time); - this.voice1.triggerRelease(time); - return this; - }; - /** - * clean up - * @returns {Tone.DuoSynth} this - */ - Tone.DuoSynth.prototype.dispose = function () { - Tone.Monophonic.prototype.dispose.call(this); - this._writable([ - 'voice0', - 'voice1', - 'frequency', - 'vibratoAmount', - 'vibratoRate' - ]); - this.voice0.dispose(); - this.voice0 = null; - this.voice1.dispose(); - this.voice1 = null; - this.frequency.dispose(); - this.frequency = null; - this._vibratoGain.dispose(); - this._vibratoGain = null; - this._vibrato = null; - this.harmonicity.dispose(); - this.harmonicity = null; - this.vibratoAmount.dispose(); - this.vibratoAmount = null; - this.vibratoRate = null; - return this; - }; - return Tone.DuoSynth; - }); - Module(function (Tone) { - - /** - * @class FMSynth is composed of two Tone.Synths where one Tone.Synth modulates - * the frequency of a second Tone.Synth. A lot of spectral content - * can be explored using the modulationIndex parameter. Read more about - * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). - * - * - * @constructor - * @extends {Tone.Monophonic} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var fmSynth = new Tone.FMSynth().toMaster(); - * fmSynth.triggerAttackRelease("C5", "4n"); - */ - Tone.FMSynth = function (options) { - options = this.defaultArg(options, Tone.FMSynth.defaults); - Tone.Monophonic.call(this, options); - /** - * The carrier voice. - * @type {Tone.Synth} - * @private - */ - this._carrier = new Tone.Synth(options.carrier); - this._carrier.volume.value = -10; - /** - * The carrier's oscillator - * @type {Tone.Oscillator} - */ - this.oscillator = this._carrier.oscillator; - /** - * The carrier's envelope - * @type {Tone.Oscillator} - */ - this.envelope = this._carrier.envelope.set(options.envelope); - /** - * The modulator voice. - * @type {Tone.Synth} - * @private - */ - this._modulator = new Tone.Synth(options.modulator); - this._modulator.volume.value = -10; - /** - * The modulator's oscillator which is applied - * to the amplitude of the oscillator - * @type {Tone.Oscillator} - */ - this.modulation = this._modulator.oscillator.set(options.modulation); - /** - * The modulator's envelope - * @type {Tone.Oscillator} - */ - this.modulationEnvelope = this._modulator.envelope.set(options.modulationEnvelope); - /** - * The frequency control. - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(440, Tone.Type.Frequency); - /** - * The detune in cents - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - /** - * Harmonicity is the ratio between the two voices. A harmonicity of - * 1 is no change. Harmonicity = 2 means a change of an octave. - * @type {Positive} - * @signal - * @example - * //pitch voice1 an octave below voice0 - * synth.harmonicity.value = 0.5; - */ - this.harmonicity = new Tone.Multiply(options.harmonicity); - this.harmonicity.units = Tone.Type.Positive; - /** - * The modulation index which essentially the depth or amount of the modulation. It is the - * ratio of the frequency of the modulating signal (mf) to the amplitude of the - * modulating signal (ma) -- as in ma/mf. - * @type {Positive} - * @signal - */ - this.modulationIndex = new Tone.Multiply(options.modulationIndex); - this.modulationIndex.units = Tone.Type.Positive; - /** - * the node where the modulation happens - * @type {GainNode} - * @private - */ - this._modulationNode = new Tone.Gain(0); - //control the two voices frequency - this.frequency.connect(this._carrier.frequency); - this.frequency.chain(this.harmonicity, this._modulator.frequency); - this.frequency.chain(this.modulationIndex, this._modulationNode); - this.detune.fan(this._carrier.detune, this._modulator.detune); - this._modulator.connect(this._modulationNode.gain); - this._modulationNode.connect(this._carrier.frequency); - this._carrier.connect(this.output); - this._readOnly([ - 'frequency', - 'harmonicity', - 'modulationIndex', - 'oscillator', - 'envelope', - 'modulation', - 'modulationEnvelope', - 'detune' - ]); - }; - Tone.extend(Tone.FMSynth, Tone.Monophonic); - /** - * @static - * @type {Object} - */ - Tone.FMSynth.defaults = { - 'harmonicity': 3, - 'modulationIndex': 10, - 'detune': 0, - 'oscillator': { 'type': 'sine' }, - 'envelope': { - 'attack': 0.01, - 'decay': 0.01, - 'sustain': 1, - 'release': 0.5 - }, - 'modulation': { 'type': 'square' }, - 'modulationEnvelope': { - 'attack': 0.5, - 'decay': 0, - 'sustain': 1, - 'release': 0.5 - } - }; - /** - * trigger the attack portion of the note - * - * @param {Time} [time=now] the time the note will occur - * @param {number} [velocity=1] the velocity of the note - * @returns {Tone.FMSynth} this - * @private - */ - Tone.FMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { - time = this.toSeconds(time); - //the envelopes - this.envelope.triggerAttack(time, velocity); - this.modulationEnvelope.triggerAttack(time); - return this; - }; - /** - * trigger the release portion of the note - * - * @param {Time} [time=now] the time the note will release - * @returns {Tone.FMSynth} this - * @private - */ - Tone.FMSynth.prototype._triggerEnvelopeRelease = function (time) { - time = this.toSeconds(time); - this.envelope.triggerRelease(time); - this.modulationEnvelope.triggerRelease(time); - return this; - }; - /** - * clean up - * @returns {Tone.FMSynth} this - */ - Tone.FMSynth.prototype.dispose = function () { - Tone.Monophonic.prototype.dispose.call(this); - this._writable([ - 'frequency', - 'harmonicity', - 'modulationIndex', - 'oscillator', - 'envelope', - 'modulation', - 'modulationEnvelope', - 'detune' - ]); - this._carrier.dispose(); - this._carrier = null; - this._modulator.dispose(); - this._modulator = null; - this.frequency.dispose(); - this.frequency = null; - this.detune.dispose(); - this.detune = null; - this.modulationIndex.dispose(); - this.modulationIndex = null; - this.harmonicity.dispose(); - this.harmonicity = null; - this._modulationNode.dispose(); - this._modulationNode = null; - this.oscillator = null; - this.envelope = null; - this.modulationEnvelope = null; - this.modulation = null; - return this; - }; - return Tone.FMSynth; - }); - Module(function (Tone) { - - /** - * @class Tone.MembraneSynth makes kick and tom sounds using a single oscillator - * with an amplitude envelope and frequency ramp. A Tone.OmniOscillator - * is routed through a Tone.AmplitudeEnvelope to the output. The drum - * quality of the sound comes from the frequency envelope applied - * during during Tone.MembraneSynth.triggerAttack(note). The frequency - * envelope starts at note * .octaves and ramps to - * note over the duration of .pitchDecay. - * - * @constructor - * @extends {Tone.Instrument} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var synth = new Tone.MembraneSynth().toMaster(); - * synth.triggerAttackRelease("C2", "8n"); - */ - Tone.MembraneSynth = function (options) { - options = this.defaultArg(options, Tone.MembraneSynth.defaults); - Tone.Instrument.call(this, options); - /** - * The oscillator. - * @type {Tone.OmniOscillator} - */ - this.oscillator = new Tone.OmniOscillator(options.oscillator).start(); - /** - * The amplitude envelope. - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = new Tone.AmplitudeEnvelope(options.envelope); - /** - * The number of octaves the pitch envelope ramps. - * @type {Positive} - */ - this.octaves = options.octaves; - /** - * The amount of time the frequency envelope takes. - * @type {Time} - */ - this.pitchDecay = options.pitchDecay; - this.oscillator.chain(this.envelope, this.output); - this._readOnly([ - 'oscillator', - 'envelope' - ]); - }; - Tone.extend(Tone.MembraneSynth, Tone.Instrument); - /** - * @static - * @type {Object} - */ - Tone.MembraneSynth.defaults = { - 'pitchDecay': 0.05, - 'octaves': 10, - 'oscillator': { 'type': 'sine' }, - 'envelope': { - 'attack': 0.001, - 'decay': 0.4, - 'sustain': 0.01, - 'release': 1.4, - 'attackCurve': 'exponential' - } - }; - /** - * Trigger the note at the given time with the given velocity. - * - * @param {Frequency} note the note - * @param {Time} [time=now] the time, if not given is now - * @param {number} [velocity=1] velocity defaults to 1 - * @returns {Tone.MembraneSynth} this - * @example - * kick.triggerAttack(60); - */ - Tone.MembraneSynth.prototype.triggerAttack = function (note, time, velocity) { - time = this.toSeconds(time); - note = this.toFrequency(note); - var maxNote = note * this.octaves; - this.oscillator.frequency.setValueAtTime(maxNote, time); - this.oscillator.frequency.exponentialRampToValueAtTime(note, time + this.toSeconds(this.pitchDecay)); - this.envelope.triggerAttack(time, velocity); - return this; - }; - /** - * Trigger the release portion of the note. - * - * @param {Time} [time=now] the time the note will release - * @returns {Tone.MembraneSynth} this - */ - Tone.MembraneSynth.prototype.triggerRelease = function (time) { - this.envelope.triggerRelease(time); - return this; - }; - /** - * Clean up. - * @returns {Tone.MembraneSynth} this - */ - Tone.MembraneSynth.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - this._writable([ - 'oscillator', - 'envelope' - ]); - this.oscillator.dispose(); - this.oscillator = null; - this.envelope.dispose(); - this.envelope = null; - return this; - }; - return Tone.MembraneSynth; - }); - Module(function (Tone) { - /** - * Inharmonic ratio of frequencies based on the Roland TR-808 - * Taken from https://ccrma.stanford.edu/papers/tr-808-cymbal-physically-informed-circuit-bendable-digital-model - * @private - * @static - * @type {Array} - */ - var inharmRatios = [ - 1, - 1.483, - 1.932, - 2.546, - 2.63, - 3.897 - ]; - /** - * @class A highly inharmonic and spectrally complex source with a highpass filter - * and amplitude envelope which is good for making metalophone sounds. Based - * on CymbalSynth by [@polyrhythmatic](https://github.com/polyrhythmatic). - * Inspiration from [Sound on Sound](http://www.soundonsound.com/sos/jul02/articles/synthsecrets0702.asp). - * - * @constructor - * @extends {Tone.Instrument} - * @param {Object} [options] The options availble for the synth - * see defaults below - */ - Tone.MetalSynth = function (options) { - options = this.defaultArg(options, Tone.MetalSynth.defaults); - Tone.Instrument.call(this, options); - /** - * The frequency of the cymbal - * @type {Frequency} - * @signal - */ - this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); - /** - * The array of FMOscillators - * @type {Array} - * @private - */ - this._oscillators = []; - /** - * The frequency multipliers - * @type {Array} - * @private - */ - this._freqMultipliers = []; - /** - * The amplitude for the body - * @type {Tone.Gain} - * @private - */ - this._amplitue = new Tone.Gain(0).connect(this.output); - /** - * highpass the output - * @type {Tone.Filter} - * @private - */ - this._highpass = new Tone.Filter({ - 'type': 'highpass', - 'Q': -3.0102999566398125 - }).connect(this._amplitue); - /** - * The number of octaves the highpass - * filter frequency ramps - * @type {Number} - * @private - */ - this._octaves = options.octaves; - /** - * Scale the body envelope - * for the bandpass - * @type {Tone.Scale} - * @private - */ - this._filterFreqScaler = new Tone.Scale(options.resonance, 7000); - /** - * The envelope which is connected both to the - * amplitude and highpass filter's cutoff frequency - * @type {Tone.Envelope} - */ - this.envelope = new Tone.Envelope({ - 'attack': options.envelope.attack, - 'attackCurve': 'linear', - 'decay': options.envelope.decay, - 'sustain': 0, - 'release': options.envelope.release - }).chain(this._filterFreqScaler, this._highpass.frequency); - this.envelope.connect(this._amplitue.gain); - for (var i = 0; i < inharmRatios.length; i++) { - var osc = new Tone.FMOscillator({ - 'type': 'square', - 'modulationType': 'square', - 'harmonicity': options.harmonicity, - 'modulationIndex': options.modulationIndex - }); - osc.connect(this._highpass).start(0); - this._oscillators[i] = osc; - var mult = new Tone.Multiply(inharmRatios[i]); - this._freqMultipliers[i] = mult; - this.frequency.chain(mult, osc.frequency); - } - //set the octaves - this.octaves = options.octaves; - }; - Tone.extend(Tone.MetalSynth, Tone.Instrument); - /** - * default values - * @static - * @const - * @type {Object} - */ - Tone.MetalSynth.defaults = { - 'frequency': 200, - 'envelope': { - 'attack': 0.001, - 'decay': 1.4, - 'release': 0.2 - }, - 'harmonicity': 5.1, - 'modulationIndex': 32, - 'resonance': 4000, - 'octaves': 1.5 - }; - /** - * Trigger the attack. - * @param {Time} time When the attack should be triggered. - * @param {NormalRange=1} velocity The velocity that the envelope should be triggered at. - * @return {Tone.MetalSynth} this - */ - Tone.MetalSynth.prototype.triggerAttack = function (time, vel) { - time = this.toSeconds(time); - vel = this.defaultArg(vel, 1); - this.envelope.triggerAttack(time, vel); - return this; - }; - /** - * Trigger the release of the envelope. - * @param {Time} time When the release should be triggered. - * @return {Tone.MetalSynth} this - */ - Tone.MetalSynth.prototype.triggerRelease = function (time) { - time = this.toSeconds(time); - this.envelope.triggerRelease(time); - return this; - }; - /** - * Trigger the attack and release of the envelope after the given - * duration. - * @param {Time} duration The duration before triggering the release - * @param {Time} time When the attack should be triggered. - * @param {NormalRange=1} velocity The velocity that the envelope should be triggered at. - * @return {Tone.MetalSynth} this - */ - Tone.MetalSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { - time = this.toSeconds(time); - duration = this.toSeconds(duration); - this.triggerAttack(time, velocity); - this.triggerRelease(time + duration); - return this; - }; - /** - * The modulationIndex of the oscillators which make up the source. - * see Tone.FMOscillator.modulationIndex - * @memberOf Tone.MetalSynth# - * @type {Positive} - * @name modulationIndex - */ - Object.defineProperty(Tone.MetalSynth.prototype, 'modulationIndex', { - get: function () { - return this._oscillators[0].modulationIndex.value; - }, - set: function (val) { - for (var i = 0; i < this._oscillators.length; i++) { - this._oscillators[i].modulationIndex.value = val; - } - } - }); - /** - * The harmonicity of the oscillators which make up the source. - * see Tone.FMOscillator.harmonicity - * @memberOf Tone.MetalSynth# - * @type {Positive} - * @name harmonicity - */ - Object.defineProperty(Tone.MetalSynth.prototype, 'harmonicity', { - get: function () { - return this._oscillators[0].harmonicity.value; - }, - set: function (val) { - for (var i = 0; i < this._oscillators.length; i++) { - this._oscillators[i].harmonicity.value = val; - } - } - }); - /** - * The frequency of the highpass filter attached to the envelope - * @memberOf Tone.MetalSynth# - * @type {Frequency} - * @name resonance - */ - Object.defineProperty(Tone.MetalSynth.prototype, 'resonance', { - get: function () { - return this._filterFreqScaler.min; - }, - set: function (val) { - this._filterFreqScaler.min = val; - this.octaves = this._octaves; - } - }); - /** - * The number of octaves above the "resonance" frequency - * that the filter ramps during the attack/decay envelope - * @memberOf Tone.MetalSynth# - * @type {Number} - * @name octaves - */ - Object.defineProperty(Tone.MetalSynth.prototype, 'octaves', { - get: function () { - return this._octaves; - }, - set: function (octs) { - this._octaves = octs; - this._filterFreqScaler.max = this._filterFreqScaler.min * Math.pow(2, octs); - } - }); - /** - * Clean up - * @returns {Tone.MetalSynth} this - */ - Tone.MetalSynth.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - for (var i = 0; i < this._oscillators.length; i++) { - this._oscillators[i].dispose(); - this._freqMultipliers[i].dispose(); - } - this._oscillators = null; - this._freqMultipliers = null; - this.frequency.dispose(); - this.frequency = null; - this._filterFreqScaler.dispose(); - this._filterFreqScaler = null; - this._amplitue.dispose(); - this._amplitue = null; - this.envelope.dispose(); - this.envelope = null; - this._highpass.dispose(); - this._highpass = null; - }; - return Tone.MetalSynth; - }); - Module(function (Tone) { - /** - * BufferSource polyfill - */ - if (window.AudioBufferSourceNode && !AudioBufferSourceNode.prototype.start) { - AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; - AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; - } - /** - * @class Wrapper around the native BufferSourceNode. - * @param {AudioBuffer|Tone.Buffer} buffer The buffer to play - * @param {Function} onended The callback to invoke when the - * buffer is done playing. - */ - Tone.BufferSource = function () { - var options = this.optionsObject(arguments, [ - 'buffer', - 'onended' - ], Tone.BufferSource.defaults); - /** - * The callback to invoke after the - * buffer source is done playing. - * @type {Function} - */ - this.onended = options.onended; - /** - * The time that the buffer was started. - * @type {Number} - * @private - */ - this._startTime = -1; - /** - * The time that the buffer is scheduled to stop. - * @type {Number} - * @private - */ - this._stopTime = -1; - /** - * The gain node which envelopes the BufferSource - * @type {Tone.Gain} - * @private - */ - this._gainNode = this.output = new Tone.Gain(); - /** - * The buffer source - * @type {AudioBufferSourceNode} - * @private - */ - this._source = this.context.createBufferSource(); - this._source.connect(this._gainNode); - /** - * The playbackRate of the buffer - * @type {Positive} - * @signal - */ - this.playbackRate = new Tone.Param(this._source.playbackRate, Tone.Type.Positive); - /** - * The fadeIn time of the amplitude envelope. - * @type {Time} - */ - this.fadeIn = options.fadeIn; - /** - * The fadeOut time of the amplitude envelope. - * @type {Time} - */ - this.fadeOut = options.fadeOut; - /** - * The value that the buffer ramps to - * @type {Gain} - * @private - */ - this._gain = 1; - /** - * The onended timeout - * @type {Number} - * @private - */ - this._onendedTimeout = -1; - //set the buffer initially - if (!this.isUndef(options.buffer)) { - this.buffer = options.buffer; - } - this.loop = options.loop; - }; - Tone.extend(Tone.BufferSource); - /** - * The defaults - * @const - * @type {Object} - */ - Tone.BufferSource.defaults = { - 'onended': Tone.noOp, - 'fadeIn': 0, - 'fadeOut': 0 - }; - /** - * Returns the playback state of the source, either "started" or "stopped". - * @type {Tone.State} - * @readOnly - * @memberOf Tone.BufferSource# - * @name state - */ - Object.defineProperty(Tone.BufferSource.prototype, 'state', { - get: function () { - var now = this.now(); - if (this._startTime !== -1 && now >= this._startTime && now < this._stopTime) { - return Tone.State.Started; - } else { - return Tone.State.Stopped; - } - } - }); - /** - * Start the buffer - * @param {Time} [startTime=now] When the player should start. - * @param {Time} [offset=0] The offset from the beginning of the sample - * to start at. - * @param {Time=} duration How long the sample should play. If no duration - * is given, it will default to the full length - * of the sample (minus any offset) - * @param {Gain} [gain=1] The gain to play the buffer back at. - * @param {Time=} fadeInTime The optional fadeIn ramp time. - * @return {Tone.BufferSource} this - */ - Tone.BufferSource.prototype.start = function (time, offset, duration, gain, fadeInTime) { - if (this._startTime !== -1) { - throw new Error('Tone.BufferSource: can only be started once.'); - } - if (this.buffer) { - time = this.toSeconds(time); - //if it's a loop the default offset is the loopstart point - if (this.loop) { - offset = this.defaultArg(offset, this.loopStart); - } else { - //otherwise the default offset is 0 - offset = this.defaultArg(offset, 0); - } - offset = this.toSeconds(offset); - //the values in seconds - time = this.toSeconds(time); - this._source.start(time, offset); - gain = this.defaultArg(gain, 1); - this._gain = gain; - //the fadeIn time - if (this.isUndef(fadeInTime)) { - fadeInTime = this.toSeconds(this.fadeIn); - } else { - fadeInTime = this.toSeconds(fadeInTime); - } - if (fadeInTime > 0) { - this._gainNode.gain.setValueAtTime(0, time); - this._gainNode.gain.linearRampToValueAtTime(this._gain, time + fadeInTime); - } else { - this._gainNode.gain.setValueAtTime(gain, time); - } - this._startTime = time + fadeInTime; - if (!this.isUndef(duration)) { - duration = this.defaultArg(duration, this.buffer.duration - offset); - duration = this.toSeconds(duration); - this.stop(time + duration + fadeInTime, fadeInTime); - } - } - return this; - }; - /** - * Stop the buffer. Optionally add a ramp time to fade the - * buffer out. - * @param {Time=} time The time the buffer should stop. - * @param {Time=} fadeOutTime How long the gain should fade out for - * @return {Tone.BufferSource} this - */ - Tone.BufferSource.prototype.stop = function (time, fadeOutTime) { - if (this.buffer) { - time = this.toSeconds(time); - //the fadeOut time - if (this.isUndef(fadeOutTime)) { - fadeOutTime = this.toSeconds(this.fadeOut); - } else { - fadeOutTime = this.toSeconds(fadeOutTime); - } - this._stopTime = time + fadeOutTime; - //cancel the end curve - this._gainNode.gain.cancelScheduledValues(this._startTime + this.sampleTime); - //set a new one - if (fadeOutTime > 0) { - this._gainNode.gain.setValueAtTime(this._gain, time); - this._gainNode.gain.linearRampToValueAtTime(0, time + fadeOutTime); - time += fadeOutTime; - } else { - this._gainNode.gain.setValueAtTime(0, time); - } - // fix for safari bug and old FF - if (!this.isNumber(this._source.playbackState) || this._source.playbackState === 2) { - this._source.stop(time); - } - clearTimeout(this._onendedTimeout); - this._onendedTimeout = setTimeout(this._onended.bind(this), (this._stopTime - this.now()) * 1000); - } - return this; - }; - /** - * Internal callback when the buffer is ended. - * Invokes `onended` and disposes the node. - * @private - */ - Tone.BufferSource.prototype._onended = function () { - this.onended(this); - this.dispose(); - }; - /** - * If loop is true, the loop will start at this position. - * @memberOf Tone.BufferSource# - * @type {Time} - * @name loopStart - */ - Object.defineProperty(Tone.BufferSource.prototype, 'loopStart', { - get: function () { - return this._source.loopStart; - }, - set: function (loopStart) { - this._source.loopStart = this.toSeconds(loopStart); - } - }); - /** - * If loop is true, the loop will end at this position. - * @memberOf Tone.BufferSource# - * @type {Time} - * @name loopEnd - */ - Object.defineProperty(Tone.BufferSource.prototype, 'loopEnd', { - get: function () { - return this._source.loopEnd; - }, - set: function (loopEnd) { - this._source.loopEnd = this.toSeconds(loopEnd); - } - }); - /** - * The audio buffer belonging to the player. - * @memberOf Tone.BufferSource# - * @type {AudioBuffer} - * @name buffer - */ - Object.defineProperty(Tone.BufferSource.prototype, 'buffer', { - get: function () { - if (this._source) { - return this._source.buffer; - } else { - return null; - } - }, - set: function (buffer) { - if (buffer instanceof Tone.Buffer) { - this._source.buffer = buffer.get(); - } else { - this._source.buffer = buffer; - } - } - }); - /** - * If the buffer should loop once it's over. - * @memberOf Tone.BufferSource# - * @type {boolean} - * @name loop - */ - Object.defineProperty(Tone.BufferSource.prototype, 'loop', { - get: function () { - return this._source.loop; - }, - set: function (loop) { - this._source.loop = loop; - } - }); - /** - * Clean up. - * @return {Tone.BufferSource} this - */ - Tone.BufferSource.prototype.dispose = function () { - this.onended = null; - if (this._source) { - this._source.disconnect(); - this._source = null; - } - if (this._gainNode) { - this._gainNode.dispose(); - this._gainNode = null; - } - this._startTime = -1; - this.playbackRate = null; - this.output = null; - clearTimeout(this._onendedTimeout); - return this; - }; - return Tone.BufferSource; - }); - Module(function (Tone) { - - /** - * @class Tone.Noise is a noise generator. It uses looped noise buffers to save on performance. - * Tone.Noise supports the noise types: "pink", "white", and "brown". Read more about - * colors of noise on [Wikipedia](https://en.wikipedia.org/wiki/Colors_of_noise). - * - * @constructor - * @extends {Tone.Source} - * @param {string} type the noise type (white|pink|brown) - * @example - * //initialize the noise and start - * var noise = new Tone.Noise("pink").start(); - * - * //make an autofilter to shape the noise - * var autoFilter = new Tone.AutoFilter({ - * "frequency" : "8m", - * "min" : 800, - * "max" : 15000 - * }).connect(Tone.Master); - * - * //connect the noise - * noise.connect(autoFilter); - * //start the autofilter LFO - * autoFilter.start() - */ - Tone.Noise = function () { - var options = this.optionsObject(arguments, ['type'], Tone.Noise.defaults); - Tone.Source.call(this, options); - /** - * @private - * @type {AudioBufferSourceNode} - */ - this._source = null; - /** - * the buffer - * @private - * @type {AudioBuffer} - */ - this._type = options.type; - /** - * The playback rate of the noise. Affects - * the "frequency" of the noise. - * @type {Positive} - * @signal - */ - this._playbackRate = options.playbackRate; - }; - Tone.extend(Tone.Noise, Tone.Source); - /** - * the default parameters - * - * @static - * @const - * @type {Object} - */ - Tone.Noise.defaults = { - 'type': 'white', - 'playbackRate': 1 - }; - /** - * The type of the noise. Can be "white", "brown", or "pink". - * @memberOf Tone.Noise# - * @type {string} - * @name type - * @example - * noise.type = "white"; - */ - Object.defineProperty(Tone.Noise.prototype, 'type', { - get: function () { - return this._type; - }, - set: function (type) { - if (this._type !== type) { - if (type in _noiseBuffers) { - this._type = type; - //if it's playing, stop and restart it - if (this.state === Tone.State.Started) { - var now = this.now() + this.blockTime; - this._stop(now); - this._start(now); - } - } else { - throw new TypeError('Tone.Noise: invalid type: ' + type); - } - } - } - }); - /** - * The playback rate of the noise. Affects - * the "frequency" of the noise. - * @type {Positive} - * @signal - */ - Object.defineProperty(Tone.Noise.prototype, 'playbackRate', { - get: function () { - return this._playbackRate; - }, - set: function (rate) { - this._playbackRate = rate; - if (this._source) { - this._source.playbackRate.value = rate; - } - } - }); - /** - * internal start method - * - * @param {Time} time - * @private - */ - Tone.Noise.prototype._start = function (time) { - var buffer = _noiseBuffers[this._type]; - this._source = new Tone.BufferSource(buffer).connect(this.output); - this._source.loop = true; - this._source.playbackRate.value = this._playbackRate; - this._source.start(this.toSeconds(time), Math.random() * (buffer.duration - 0.001)); - }; - /** - * internal stop method - * - * @param {Time} time - * @private - */ - Tone.Noise.prototype._stop = function (time) { - if (this._source) { - this._source.stop(this.toSeconds(time)); - this._source = null; - } - }; - /** - * Clean up. - * @returns {Tone.Noise} this - */ - Tone.Noise.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - if (this._source !== null) { - this._source.disconnect(); - this._source = null; - } - this._buffer = null; - return this; - }; - /////////////////////////////////////////////////////////////////////////// - // THE BUFFERS - /////////////////////////////////////////////////////////////////////////// - //Noise buffer stats - var bufferLength = 44100 * 5; - var channels = 2; - /** - * the noise arrays. only generated once on init - * @static - * @private - * @type {Array} - * borrowed heavily from https://github.com/zacharydenton/noise.js - * (c) 2013 Zach Denton (MIT) - */ - var _noiseArrays = { - 'pink': function () { - var buffer = []; - for (var channelNum = 0; channelNum < channels; channelNum++) { - var channel = new Float32Array(bufferLength); - buffer[channelNum] = channel; - var b0, b1, b2, b3, b4, b5, b6; - b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; - for (var i = 0; i < bufferLength; i++) { - var white = Math.random() * 2 - 1; - b0 = 0.99886 * b0 + white * 0.0555179; - b1 = 0.99332 * b1 + white * 0.0750759; - b2 = 0.969 * b2 + white * 0.153852; - b3 = 0.8665 * b3 + white * 0.3104856; - b4 = 0.55 * b4 + white * 0.5329522; - b5 = -0.7616 * b5 - white * 0.016898; - channel[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; - channel[i] *= 0.11; - // (roughly) compensate for gain - b6 = white * 0.115926; - } - } - return buffer; - }(), - 'brown': function () { - var buffer = []; - for (var channelNum = 0; channelNum < channels; channelNum++) { - var channel = new Float32Array(bufferLength); - buffer[channelNum] = channel; - var lastOut = 0; - for (var i = 0; i < bufferLength; i++) { - var white = Math.random() * 2 - 1; - channel[i] = (lastOut + 0.02 * white) / 1.02; - lastOut = channel[i]; - channel[i] *= 3.5; // (roughly) compensate for gain - } - } - return buffer; - }(), - 'white': function () { - var buffer = []; - for (var channelNum = 0; channelNum < channels; channelNum++) { - var channel = new Float32Array(bufferLength); - buffer[channelNum] = channel; - for (var i = 0; i < bufferLength; i++) { - channel[i] = Math.random() * 2 - 1; - } - } - return buffer; - }() - }; - /** - * static noise buffers - * @static - * @private - * @type {Tone.Buffer} - */ - var _noiseBuffers = {}; - //create the Tone.Buffers - function createBuffers() { - for (var type in _noiseArrays) { - _noiseBuffers[type] = new Tone.Buffer().fromArray(_noiseArrays[type]); - } - } - createBuffers(); - Tone.Context.on('init', createBuffers); - return Tone.Noise; - }); - Module(function (Tone) { - - /** - * @class Tone.NoiseSynth is composed of a noise generator (Tone.Noise), one filter (Tone.Filter), - * and two envelopes (Tone.Envelop). One envelope controls the amplitude - * of the noise and the other is controls the cutoff frequency of the filter. - * - * - * @constructor - * @extends {Tone.Instrument} - * @param {Object} [options] the options available for the synth - * see defaults below - * @example - * var noiseSynth = new Tone.NoiseSynth().toMaster(); - * noiseSynth.triggerAttackRelease("8n"); - */ - Tone.NoiseSynth = function (options) { - //get the defaults - options = this.defaultArg(options, Tone.NoiseSynth.defaults); - Tone.Instrument.call(this, options); - /** - * The noise source. - * @type {Tone.Noise} - * @example - * noiseSynth.set("noise.type", "brown"); - */ - this.noise = new Tone.Noise(); - /** - * The amplitude envelope. - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = new Tone.AmplitudeEnvelope(options.envelope); - //connect the noise to the output - this.noise.chain(this.envelope, this.output); - //start the noise - this.noise.start(); - this._readOnly([ - 'noise', - 'envelope' - ]); - }; - Tone.extend(Tone.NoiseSynth, Tone.Instrument); - /** - * @const - * @static - * @type {Object} - */ - Tone.NoiseSynth.defaults = { - 'noise': { 'type': 'white' }, - 'envelope': { - 'attack': 0.005, - 'decay': 0.1, - 'sustain': 0 - } - }; - /** - * Start the attack portion of the envelopes. Unlike other - * instruments, Tone.NoiseSynth doesn't have a note. - * @param {Time} [time=now] the time the attack should start - * @param {number} [velocity=1] the velocity of the note (0-1) - * @returns {Tone.NoiseSynth} this - * @example - * noiseSynth.triggerAttack(); - */ - Tone.NoiseSynth.prototype.triggerAttack = function (time, velocity) { - //the envelopes - this.envelope.triggerAttack(time, velocity); - return this; - }; - /** - * Start the release portion of the envelopes. - * @param {Time} [time=now] the time the release should start - * @returns {Tone.NoiseSynth} this - */ - Tone.NoiseSynth.prototype.triggerRelease = function (time) { - this.envelope.triggerRelease(time); - return this; - }; - /** - * Trigger the attack and then the release. - * @param {Time} duration the duration of the note - * @param {Time} [time=now] the time of the attack - * @param {number} [velocity=1] the velocity - * @returns {Tone.NoiseSynth} this - */ - Tone.NoiseSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { - time = this.toSeconds(time); - duration = this.toSeconds(duration); - this.triggerAttack(time, velocity); - this.triggerRelease(time + duration); - return this; - }; - /** - * Clean up. - * @returns {Tone.NoiseSynth} this - */ - Tone.NoiseSynth.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - this._writable([ - 'noise', - 'envelope' - ]); - this.noise.dispose(); - this.noise = null; - this.envelope.dispose(); - this.envelope = null; - return this; - }; - return Tone.NoiseSynth; - }); - Module(function (Tone) { - - /** - * @class Karplus-String string synthesis. Often out of tune. - * Will change when the AudioWorkerNode is available across - * browsers. - * - * @constructor - * @extends {Tone.Instrument} - * @param {Object} [options] see the defaults - * @example - * var plucky = new Tone.PluckSynth().toMaster(); - * plucky.triggerAttack("C4"); - */ - Tone.PluckSynth = function (options) { - options = this.defaultArg(options, Tone.PluckSynth.defaults); - Tone.Instrument.call(this, options); - /** - * @type {Tone.Noise} - * @private - */ - this._noise = new Tone.Noise('pink'); - /** - * The amount of noise at the attack. - * Nominal range of [0.1, 20] - * @type {number} - */ - this.attackNoise = options.attackNoise; - /** - * the LFCF - * @type {Tone.LowpassCombFilter} - * @private - */ - this._lfcf = new Tone.LowpassCombFilter({ - 'resonance': options.resonance, - 'dampening': options.dampening - }); - /** - * The resonance control. - * @type {NormalRange} - * @signal - */ - this.resonance = this._lfcf.resonance; - /** - * The dampening control. i.e. the lowpass filter frequency of the comb filter - * @type {Frequency} - * @signal - */ - this.dampening = this._lfcf.dampening; - //connections - this._noise.connect(this._lfcf); - this._lfcf.connect(this.output); - this._readOnly([ - 'resonance', - 'dampening' - ]); - }; - Tone.extend(Tone.PluckSynth, Tone.Instrument); - /** - * @static - * @const - * @type {Object} - */ - Tone.PluckSynth.defaults = { - 'attackNoise': 1, - 'dampening': 4000, - 'resonance': 0.9 - }; - /** - * Trigger the note. - * @param {Frequency} note The note to trigger. - * @param {Time} [time=now] When the note should be triggered. - * @returns {Tone.PluckSynth} this - */ - Tone.PluckSynth.prototype.triggerAttack = function (note, time) { - note = this.toFrequency(note); - time = this.toSeconds(time); - var delayAmount = 1 / note; - this._lfcf.delayTime.setValueAtTime(delayAmount, time); - this._noise.start(time); - this._noise.stop(time + delayAmount * this.attackNoise); - return this; - }; - /** - * Clean up. - * @returns {Tone.PluckSynth} this - */ - Tone.PluckSynth.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - this._noise.dispose(); - this._lfcf.dispose(); - this._noise = null; - this._lfcf = null; - this._writable([ - 'resonance', - 'dampening' - ]); - this.dampening = null; - this.resonance = null; - return this; - }; - return Tone.PluckSynth; - }); - Module(function (Tone) { - - /** - * @class Tone.PolySynth handles voice creation and allocation for any - * instruments passed in as the second paramter. PolySynth is - * not a synthesizer by itself, it merely manages voices of - * one of the other types of synths, allowing any of the - * monophonic synthesizers to be polyphonic. - * - * @constructor - * @extends {Tone.Instrument} - * @param {number|Object} [polyphony=4] The number of voices to create - * @param {function} [voice=Tone.Synth] The constructor of the voices - * uses Tone.Synth by default. - * @example - * //a polysynth composed of 6 Voices of Synth - * var synth = new Tone.PolySynth(6, Tone.Synth).toMaster(); - * //set the attributes using the set interface - * synth.set("detune", -1200); - * //play a chord - * synth.triggerAttackRelease(["C4", "E4", "A4"], "4n"); - */ - Tone.PolySynth = function () { - Tone.Instrument.call(this); - var options = this.optionsObject(arguments, [ - 'polyphony', - 'voice' - ], Tone.PolySynth.defaults); - options = this.defaultArg(options, Tone.Instrument.defaults); - //max polyphony - options.polyphony = Math.min(Tone.PolySynth.MAX_POLYPHONY, options.polyphony); - /** - * the array of voices - * @type {Array} - */ - this.voices = new Array(options.polyphony); - /** - * The queue of voices with data about last trigger - * and the triggered note - * @private - * @type {Array} - */ - this._triggers = new Array(options.polyphony); - /** - * The detune in cents - * @type {Cents} - * @signal - */ - this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); - this._readOnly('detune'); - //create the voices - for (var i = 0; i < options.polyphony; i++) { - var v = new options.voice(arguments[2], arguments[3]); - this.voices[i] = v; - v.connect(this.output); - if (v.hasOwnProperty('detune')) { - this.detune.connect(v.detune); - } - this._triggers[i] = { - release: -1, - note: null, - voice: v - }; - } - //set the volume initially - this.volume.value = options.volume; - }; - Tone.extend(Tone.PolySynth, Tone.Instrument); - /** - * the defaults - * @const - * @static - * @type {Object} - */ - Tone.PolySynth.defaults = { - 'polyphony': 4, - 'volume': 0, - 'detune': 0, - 'voice': Tone.Synth - }; - /** - * Trigger the attack portion of the note - * @param {Frequency|Array} notes The notes to play. Accepts a single - * Frequency or an array of frequencies. - * @param {Time} [time=now] The start time of the note. - * @param {number} [velocity=1] The velocity of the note. - * @returns {Tone.PolySynth} this - * @example - * //trigger a chord immediately with a velocity of 0.2 - * poly.triggerAttack(["Ab3", "C4", "F5"], undefined, 0.2); - */ - Tone.PolySynth.prototype.triggerAttack = function (notes, time, velocity) { - if (!Array.isArray(notes)) { - notes = [notes]; - } - time = this.toSeconds(time); - for (var i = 0; i < notes.length; i++) { - var val = notes[i]; - //trigger the oldest voice - var oldest = this._triggers[0]; - var oldestIndex = 0; - for (var j = 1; j < this._triggers.length; j++) { - if (this._triggers[j].release < oldest.release) { - oldest = this._triggers[j]; - oldestIndex = j; - } - } - oldest.release = Infinity; - oldest.note = JSON.stringify(val); - oldest.voice.triggerAttack(val, time, velocity); - } - return this; - }; - /** - * Trigger the attack and release after the specified duration - * - * @param {Frequency|Array} notes The notes to play. Accepts a single - * Frequency or an array of frequencies. - * @param {Time} duration the duration of the note - * @param {Time} [time=now] if no time is given, defaults to now - * @param {number} [velocity=1] the velocity of the attack (0-1) - * @returns {Tone.PolySynth} this - * @example - * //trigger a chord for a duration of a half note - * poly.triggerAttackRelease(["Eb3", "G4", "C5"], "2n"); - * @example - * //can pass in an array of durations as well - * poly.triggerAttackRelease(["Eb3", "G4", "C5"], ["2n", "4n", "4n"]); - */ - Tone.PolySynth.prototype.triggerAttackRelease = function (notes, duration, time, velocity) { - time = this.toSeconds(time); - this.triggerAttack(notes, time, velocity); - if (this.isArray(duration) && this.isArray(notes)) { - for (var i = 0; i < notes.length; i++) { - var d = duration[Math.min(i, duration.length - 1)]; - this.triggerRelease(notes[i], time + this.toSeconds(d)); - } - } else { - this.triggerRelease(notes, time + this.toSeconds(duration)); - } - return this; - }; - /** - * Trigger the release of the note. Unlike monophonic instruments, - * a note (or array of notes) needs to be passed in as the first argument. - * @param {Frequency|Array} notes The notes to play. Accepts a single - * Frequency or an array of frequencies. - * @param {Time} [time=now] When the release will be triggered. - * @returns {Tone.PolySynth} this - * @example - * poly.triggerRelease(["Ab3", "C4", "F5"], "+2n"); - */ - Tone.PolySynth.prototype.triggerRelease = function (notes, time) { - if (!Array.isArray(notes)) { - notes = [notes]; - } - time = this.toSeconds(time); - for (var i = 0; i < notes.length; i++) { - //get the voice - var stringified = JSON.stringify(notes[i]); - for (var v = 0; v < this._triggers.length; v++) { - var desc = this._triggers[v]; - if (desc.note === stringified && desc.release > time) { - desc.voice.triggerRelease(time); - desc.release = time; - } - } - } - return this; - }; - /** - * Set a member/attribute of the voices. - * @param {Object|string} params - * @param {number=} value - * @param {Time=} rampTime - * @returns {Tone.PolySynth} this - * @example - * poly.set({ - * "filter" : { - * "type" : "highpass" - * }, - * "envelope" : { - * "attack" : 0.25 - * } - * }); - */ - Tone.PolySynth.prototype.set = function (params, value, rampTime) { - for (var i = 0; i < this.voices.length; i++) { - this.voices[i].set(params, value, rampTime); - } - return this; - }; - /** - * Get the synth's attributes. Given no arguments get - * will return all available object properties and their corresponding - * values. Pass in a single attribute to retrieve or an array - * of attributes. The attribute strings can also include a "." - * to access deeper properties. - * @param {Array=} params the parameters to get, otherwise will return - * all available. - */ - Tone.PolySynth.prototype.get = function (params) { - return this.voices[0].get(params); - }; - /** - * Trigger the release portion of all the currently active voices. - * @param {Time} [time=now] When the notes should be released. - * @return {Tone.PolySynth} this - */ - Tone.PolySynth.prototype.releaseAll = function (time) { - time = this.toSeconds(time); - for (var i = 0; i < this._triggers.length; i++) { - var desc = this._triggers[i]; - if (desc.release > time) { - desc.release = time; - desc.voice.triggerRelease(time); - } - } - return this; - }; - /** - * Clean up. - * @returns {Tone.PolySynth} this - */ - Tone.PolySynth.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - for (var i = 0; i < this.voices.length; i++) { - this.voices[i].dispose(); - this.voices[i] = null; - } - this._writable('detune'); - this.detune.dispose(); - this.detune = null; - this.voices = null; - this._triggers = null; - return this; - }; - /** - * The maximum number of notes that can be allocated - * to a polysynth. - * @type {Number} - * @static - */ - Tone.PolySynth.MAX_POLYPHONY = 20; - return Tone.PolySynth; - }); - Module(function (Tone) { - - /** - * @class Tone.Player is an audio file player with start, loop, and stop functions. - * - * @constructor - * @extends {Tone.Source} - * @param {string|AudioBuffer} url Either the AudioBuffer or the url from - * which to load the AudioBuffer - * @param {function=} onload The function to invoke when the buffer is loaded. - * Recommended to use Tone.Buffer.on('load') instead. - * @example - * var player = new Tone.Player("./path/to/sample.mp3").toMaster(); - * //play as soon as the buffer is loaded - * player.autostart = true; - */ - Tone.Player = function (url) { - var options; - if (url instanceof Tone.Buffer) { - url = url.get(); - options = Tone.Player.defaults; - } else { - options = this.optionsObject(arguments, [ - 'url', - 'onload' - ], Tone.Player.defaults); - } - Tone.Source.call(this, options); - /** - * @private - * @type {AudioBufferSourceNode} - */ - this._source = null; - /** - * If the file should play as soon - * as the buffer is loaded. - * @type {boolean} - * @example - * //will play as soon as it's loaded - * var player = new Tone.Player({ - * "url" : "./path/to/sample.mp3", - * "autostart" : true, - * }).toMaster(); - */ - this.autostart = options.autostart; - /** - * the buffer - * @private - * @type {Tone.Buffer} - */ - this._buffer = new Tone.Buffer({ - 'url': options.url, - 'onload': this._onload.bind(this, options.onload), - 'reverse': options.reverse - }); - if (url instanceof AudioBuffer) { - this._buffer.set(url); - } - /** - * if the buffer should loop once it's over - * @type {boolean} - * @private - */ - this._loop = options.loop; - /** - * if 'loop' is true, the loop will start at this position - * @type {Time} - * @private - */ - this._loopStart = options.loopStart; - /** - * if 'loop' is true, the loop will end at this position - * @type {Time} - * @private - */ - this._loopEnd = options.loopEnd; - /** - * the playback rate - * @private - * @type {number} - */ - this._playbackRate = options.playbackRate; - /** - * Enabling retrigger will allow a player to be restarted - * before the the previous 'start' is done playing. Otherwise, - * successive calls to Tone.Player.start will only start - * the sample if it had played all the way through. - * @type {boolean} - */ - this.retrigger = options.retrigger; - }; - Tone.extend(Tone.Player, Tone.Source); - /** - * the default parameters - * @static - * @const - * @type {Object} - */ - Tone.Player.defaults = { - 'onload': Tone.noOp, - 'playbackRate': 1, - 'loop': false, - 'autostart': false, - 'loopStart': 0, - 'loopEnd': 0, - 'retrigger': false, - 'reverse': false - }; - /** - * Load the audio file as an audio buffer. - * Decodes the audio asynchronously and invokes - * the callback once the audio buffer loads. - * Note: this does not need to be called if a url - * was passed in to the constructor. Only use this - * if you want to manually load a new url. - * @param {string} url The url of the buffer to load. - * Filetype support depends on the - * browser. - * @param {function=} callback The function to invoke once - * the sample is loaded. - * @returns {Promise} - */ - Tone.Player.prototype.load = function (url, callback) { - return this._buffer.load(url, this._onload.bind(this, callback)); - }; - /** - * Internal callback when the buffer is loaded. - * @private - */ - Tone.Player.prototype._onload = function (callback) { - callback = this.defaultArg(callback, Tone.noOp); - callback(this); - if (this.autostart) { - this.start(); - } - }; - /** - * Play the buffer at the given startTime. Optionally add an offset - * and/or duration which will play the buffer from a position - * within the buffer for the given duration. - * - * @param {Time} [startTime=now] When the player should start. - * @param {Time} [offset=0] The offset from the beginning of the sample - * to start at. - * @param {Time=} duration How long the sample should play. If no duration - * is given, it will default to the full length - * of the sample (minus any offset) - * @returns {Tone.Player} this - * @memberOf Tone.Player# - * @method start - * @name start - */ - /** - * Internal start method - * @private - */ - Tone.Player.prototype._start = function (startTime, offset, duration) { - if (this._buffer.loaded) { - //if it's a loop the default offset is the loopstart point - if (this._loop) { - offset = this.defaultArg(offset, this._loopStart); - } else { - //otherwise the default offset is 0 - offset = this.defaultArg(offset, 0); - } - offset = this.toSeconds(offset); - //make sure it has a positive duration - duration = this.defaultArg(duration, Math.max(this._buffer.duration - offset, 0)); - duration = this.toSeconds(duration); - //the values in seconds - startTime = this.toSeconds(startTime); - //make the source - this._source = this.context.createBufferSource(); - this._source.buffer = this._buffer.get(); - //set the looping properties - if (this._loop) { - this._source.loop = this._loop; - this._source.loopStart = this.toSeconds(this._loopStart); - this._source.loopEnd = this.toSeconds(this._loopEnd); - } else if (!this._synced) { - //if it's not looping, set the state change at the end of the sample - this._state.setStateAtTime(Tone.State.Stopped, startTime + duration); - } - //and other properties - this._source.playbackRate.value = this._playbackRate; - this._source.connect(this.output); - //start it - if (this._loop) { - //modify the offset if it's greater than the loop time - var loopEnd = this._source.loopEnd || this._buffer.duration; - var loopStart = this._source.loopStart; - var loopDuration = loopEnd - loopStart; - if (offset > loopEnd) { - //move the offset back - while (offset > loopEnd) { - offset -= loopDuration; - } - } - this._source.start(startTime, offset); - } else { - this._source.start(startTime, offset, duration); - } - } else { - throw Error('Tone.Player: tried to start Player before the buffer was loaded'); - } - return this; - }; - /** - * Stop playback. - * @private - * @param {Time} [time=now] - * @returns {Tone.Player} this - */ - Tone.Player.prototype._stop = function (time) { - if (this._source) { - this._source.stop(this.toSeconds(time)); - this._source = null; - } - return this; - }; - /** - * Seek to a specific time in the player's buffer. If the - * source is no longer playing at that time, it will stop. - * If you seek to a time that - * @param {Time} offset The time to seek to. - * @param {Time=} time The time for the seek event to occur. - * @return {Tone.Player} this - * @example - * source.start(0.2); - * source.stop(0.4); - */ - Tone.Player.prototype.seek = function (offset, time) { - time = this.toSeconds(time); - if (this._state.getValueAtTime(time) === Tone.State.Started) { - offset = this.toSeconds(offset); - // if it's currently playing, stop it - this._stop(time); - //restart it at the given time - this._start(time, offset); - } - return this; - }; - /** - * Set the loop start and end. Will only loop if loop is - * set to true. - * @param {Time} loopStart The loop end time - * @param {Time} loopEnd The loop end time - * @returns {Tone.Player} this - * @example - * //loop 0.1 seconds of the file. - * player.setLoopPoints(0.2, 0.3); - * player.loop = true; - */ - Tone.Player.prototype.setLoopPoints = function (loopStart, loopEnd) { - this.loopStart = loopStart; - this.loopEnd = loopEnd; - return this; - }; - /** - * If loop is true, the loop will start at this position. - * @memberOf Tone.Player# - * @type {Time} - * @name loopStart - */ - Object.defineProperty(Tone.Player.prototype, 'loopStart', { - get: function () { - return this._loopStart; - }, - set: function (loopStart) { - this._loopStart = loopStart; - if (this._source) { - this._source.loopStart = this.toSeconds(loopStart); - } - } - }); - /** - * If loop is true, the loop will end at this position. - * @memberOf Tone.Player# - * @type {Time} - * @name loopEnd - */ - Object.defineProperty(Tone.Player.prototype, 'loopEnd', { - get: function () { - return this._loopEnd; - }, - set: function (loopEnd) { - this._loopEnd = loopEnd; - if (this._source) { - this._source.loopEnd = this.toSeconds(loopEnd); - } - } - }); - /** - * The audio buffer belonging to the player. - * @memberOf Tone.Player# - * @type {Tone.Buffer} - * @name buffer - */ - Object.defineProperty(Tone.Player.prototype, 'buffer', { - get: function () { - return this._buffer; - }, - set: function (buffer) { - this._buffer.set(buffer); - } - }); - /** - * If the buffer should loop once it's over. - * @memberOf Tone.Player# - * @type {boolean} - * @name loop - */ - Object.defineProperty(Tone.Player.prototype, 'loop', { - get: function () { - return this._loop; - }, - set: function (loop) { - this._loop = loop; - if (this._source) { - this._source.loop = loop; - } - } - }); - /** - * The playback speed. 1 is normal speed. This is not a signal because - * Safari and iOS currently don't support playbackRate as a signal. - * @memberOf Tone.Player# - * @type {number} - * @name playbackRate - */ - Object.defineProperty(Tone.Player.prototype, 'playbackRate', { - get: function () { - return this._playbackRate; - }, - set: function (rate) { - this._playbackRate = rate; - if (this._source) { - this._source.playbackRate.value = rate; - } - } - }); - /** - * The direction the buffer should play in - * @memberOf Tone.Player# - * @type {boolean} - * @name reverse - */ - Object.defineProperty(Tone.Player.prototype, 'reverse', { - get: function () { - return this._buffer.reverse; - }, - set: function (rev) { - this._buffer.reverse = rev; - } - }); - /** - * Dispose and disconnect. - * @return {Tone.Player} this - */ - Tone.Player.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - if (this._source !== null) { - this._source.disconnect(); - this._source = null; - } - this._buffer.dispose(); - this._buffer = null; - return this; - }; - return Tone.Player; - }); - Module(function (Tone) { - - /** - * @class Sampler wraps Tone.Player in an AmplitudeEnvelope. - * - * @constructor - * @extends {Tone.Instrument} - * @param {String} url the url of the audio file - * @param {Function=} onload The callback to invoke when the sample is loaded. - * @example - * var sampler = new Sampler("./audio/casio/A1.mp3", function(){ - * //repitch the sample down a half step - * sampler.triggerAttack(-1); - * }).toMaster(); - */ - Tone.Sampler = function () { - var options = this.optionsObject(arguments, [ - 'url', - 'onload' - ], Tone.Sampler.defaults); - Tone.Instrument.call(this, options); - /** - * The sample player. - * @type {Tone.Player} - */ - this.player = new Tone.Player(options.url, options.onload); - this.player.retrigger = true; - /** - * The amplitude envelope. - * @type {Tone.AmplitudeEnvelope} - */ - this.envelope = new Tone.AmplitudeEnvelope(options.envelope); - this.player.chain(this.envelope, this.output); - this._readOnly([ - 'player', - 'envelope' - ]); - this.loop = options.loop; - this.reverse = options.reverse; - }; - Tone.extend(Tone.Sampler, Tone.Instrument); - /** - * the default parameters - * @static - */ - Tone.Sampler.defaults = { - 'onload': Tone.noOp, - 'loop': false, - 'reverse': false, - 'envelope': { - 'attack': 0.001, - 'decay': 0, - 'sustain': 1, - 'release': 0.1 - } - }; - /** - * Trigger the start of the sample. - * @param {Interval} [pitch=0] The amount the sample should - * be repitched. - * @param {Time} [time=now] The time when the sample should start - * @param {NormalRange} [velocity=1] The velocity of the note - * @returns {Tone.Sampler} this - * @example - * sampler.triggerAttack(0, "+0.1", 0.5); - */ - Tone.Sampler.prototype.triggerAttack = function (pitch, time, velocity) { - time = this.toSeconds(time); - pitch = this.defaultArg(pitch, 0); - this.player.playbackRate = this.intervalToFrequencyRatio(pitch); - this.player.start(time); - this.envelope.triggerAttack(time, velocity); - return this; - }; - /** - * Start the release portion of the sample. Will stop the sample once the - * envelope has fully released. - * - * @param {Time} [time=now] The time when the note should release - * @returns {Tone.Sampler} this - * @example - * sampler.triggerRelease(); - */ - Tone.Sampler.prototype.triggerRelease = function (time) { - time = this.toSeconds(time); - this.envelope.triggerRelease(time); - this.player.stop(this.toSeconds(this.envelope.release) + time); - return this; - }; - /** - * Trigger the attack and then the release after the duration. - * @param {Interval} interval The interval in half-steps that the - * sample should be pitch shifted. - * @param {Time} duration How long the note should be held for before - * triggering the release. - * @param {Time} [time=now] When the note should be triggered. - * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. - * @returns {Tone.Sampler} this - * @example - * //trigger the unpitched note for the duration of an 8th note - * synth.triggerAttackRelease(0, "8n"); - * @memberOf Tone.Sampler# - * @name triggerAttackRelease - * @method triggerAttackRelease - */ - /** - * If the output sample should loop or not. - * @memberOf Tone.Sampler# - * @type {number|string} - * @name loop - */ - Object.defineProperty(Tone.Sampler.prototype, 'loop', { - get: function () { - return this.player.loop; - }, - set: function (loop) { - this.player.loop = loop; - } - }); - /** - * The direction the buffer should play in - * @memberOf Tone.Sampler# - * @type {boolean} - * @name reverse - */ - Object.defineProperty(Tone.Sampler.prototype, 'reverse', { - get: function () { - return this.player.reverse; - }, - set: function (rev) { - this.player.reverse = rev; - } - }); - /** - * The buffer to play. - * @memberOf Tone.Sampler# - * @type {Tone.Buffer} - * @name buffer - */ - Object.defineProperty(Tone.Sampler.prototype, 'buffer', { - get: function () { - return this.player.buffer; - }, - set: function (buff) { - this.player.buffer = buff; - } - }); - /** - * Clean up. - * @returns {Tone.Sampler} this - */ - Tone.Sampler.prototype.dispose = function () { - Tone.Instrument.prototype.dispose.call(this); - this._writable([ - 'player', - 'envelope' - ]); - this.player.dispose(); - this.player = null; - this.envelope.dispose(); - this.envelope = null; - return this; - }; - return Tone.Sampler; - }); - Module(function (Tone) { - - /** - * @class Maps a NormalRange [0, 1] to an AudioRange [-1, 1]. - * See also Tone.AudioToGain. - * - * @extends {Tone.SignalBase} - * @constructor - * @example - * var g2a = new Tone.GainToAudio(); - */ - Tone.GainToAudio = function () { - /** - * @type {WaveShaperNode} - * @private - */ - this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { - return Math.abs(x) * 2 - 1; - }); - }; - Tone.extend(Tone.GainToAudio, Tone.SignalBase); - /** - * clean up - * @returns {Tone.GainToAudio} this - */ - Tone.GainToAudio.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._norm.dispose(); - this._norm = null; - return this; - }; - return Tone.GainToAudio; - }); - Module(function (Tone) { - - /** - * @class Normalize takes an input min and max and maps it linearly to NormalRange [0,1] - * - * @extends {Tone.SignalBase} - * @constructor - * @param {number} inputMin the min input value - * @param {number} inputMax the max input value - * @example - * var norm = new Tone.Normalize(2, 4); - * var sig = new Tone.Signal(3).connect(norm); - * //output of norm is 0.5. - */ - Tone.Normalize = function (inputMin, inputMax) { - /** - * the min input value - * @type {number} - * @private - */ - this._inputMin = this.defaultArg(inputMin, 0); - /** - * the max input value - * @type {number} - * @private - */ - this._inputMax = this.defaultArg(inputMax, 1); - /** - * subtract the min from the input - * @type {Tone.Add} - * @private - */ - this._sub = this.input = new Tone.Add(0); - /** - * divide by the difference between the input and output - * @type {Tone.Multiply} - * @private - */ - this._div = this.output = new Tone.Multiply(1); - this._sub.connect(this._div); - this._setRange(); - }; - Tone.extend(Tone.Normalize, Tone.SignalBase); - /** - * The minimum value the input signal will reach. - * @memberOf Tone.Normalize# - * @type {number} - * @name min - */ - Object.defineProperty(Tone.Normalize.prototype, 'min', { - get: function () { - return this._inputMin; - }, - set: function (min) { - this._inputMin = min; - this._setRange(); - } - }); - /** - * The maximum value the input signal will reach. - * @memberOf Tone.Normalize# - * @type {number} - * @name max - */ - Object.defineProperty(Tone.Normalize.prototype, 'max', { - get: function () { - return this._inputMax; - }, - set: function (max) { - this._inputMax = max; - this._setRange(); - } - }); - /** - * set the values - * @private - */ - Tone.Normalize.prototype._setRange = function () { - this._sub.value = -this._inputMin; - this._div.value = 1 / (this._inputMax - this._inputMin); - }; - /** - * clean up - * @returns {Tone.Normalize} this - */ - Tone.Normalize.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._sub.dispose(); - this._sub = null; - this._div.dispose(); - this._div = null; - return this; - }; - return Tone.Normalize; - }); - Module(function (Tone) { - /** - * @class Tone.MultiPlayer is well suited for one-shots, multi-sampled instruments - * or any time you need to play a bunch of audio buffers. - * @param {Object|Array|Tone.Buffers} buffers The buffers which are available - * to the MultiPlayer - * @param {Function} onload The callback to invoke when all of the buffers are loaded. - * @extends {Tone} - * @example - * var multiPlayer = new MultiPlayer({ - * "kick" : "path/to/kick.mp3", - * "snare" : "path/to/snare.mp3", - * }, function(){ - * multiPlayer.start("kick"); - * }); - * @example - * //can also store the values in an array - * var multiPlayer = new MultiPlayer(["path/to/kick.mp3", "path/to/snare.mp3"], - * function(){ - * //if an array is passed in, the samples are referenced to by index - * multiPlayer.start(1); - * }); - */ - Tone.MultiPlayer = function () { - var options = this.optionsObject(arguments, [ - 'urls', - 'onload' - ], Tone.MultiPlayer.defaults); - if (options.urls instanceof Tone.Buffers) { - /** - * All the buffers belonging to the player. - * @type {Tone.Buffers} - */ - this.buffers = options.urls; - } else { - this.buffers = new Tone.Buffers(options.urls, options.onload); - } - /** - * Keeps track of the currently playing sources. - * @type {Object} - * @private - */ - this._activeSources = {}; - /** - * The fade in envelope which is applied - * to the beginning of the BufferSource - * @type {Time} - */ - this.fadeIn = options.fadeIn; - /** - * The fade out envelope which is applied - * to the end of the BufferSource - * @type {Time} - */ - this.fadeOut = options.fadeOut; - /** - * The output volume node - * @type {Tone.Volume} - * @private - */ - this._volume = this.output = new Tone.Volume(options.volume); - /** - * The volume of the output in decibels. - * @type {Decibels} - * @signal - * @example - * source.volume.value = -6; - */ - this.volume = this._volume.volume; - this._readOnly('volume'); - //make the output explicitly stereo - this._volume.output.output.channelCount = 2; - this._volume.output.output.channelCountMode = 'explicit'; - //mute initially - this.mute = options.mute; - }; - Tone.extend(Tone.MultiPlayer, Tone.Source); - /** - * The defaults - * @type {Object} - */ - Tone.MultiPlayer.defaults = { - 'onload': Tone.noOp, - 'fadeIn': 0, - 'fadeOut': 0 - }; - /** - * Make the source from the buffername - * @param {String} bufferName - * @return {Tone.BufferSource} - * @private - */ - Tone.MultiPlayer.prototype._makeSource = function (bufferName) { - var buffer; - if (this.isString(bufferName) || this.isNumber(bufferName)) { - buffer = this.buffers.get(bufferName).get(); - } else if (bufferName instanceof Tone.Buffer) { - buffer = bufferName.get(); - } else if (bufferName instanceof AudioBuffer) { - buffer = bufferName; - } - var source = new Tone.BufferSource(buffer).connect(this.output); - if (!this._activeSources.hasOwnProperty(bufferName)) { - this._activeSources[bufferName] = []; - } - this._activeSources[bufferName].push(source); - return source; - }; - /** - * Start a buffer by name. The `start` method allows a number of options - * to be passed in such as offset, interval, and gain. This is good for multi-sampled - * instruments and sound sprites where samples are repitched played back at different velocities. - * @param {String} bufferName The name of the buffer to start. - * @param {Time} time When to start the buffer. - * @param {Time} [offset=0] The offset into the buffer to play from. - * @param {Time=} duration How long to play the buffer for. - * @param {Interval} [pitch=0] The interval to repitch the buffer. - * @param {Gain} [gain=1] The gain to play the sample at. - * @return {Tone.MultiPlayer} this - */ - Tone.MultiPlayer.prototype.start = function (bufferName, time, offset, duration, pitch, gain) { - time = this.toSeconds(time); - var source = this._makeSource(bufferName); - source.start(time, offset, duration, this.defaultArg(gain, 1), this.fadeIn); - if (duration) { - source.stop(time + this.toSeconds(duration), this.fadeOut); - } - pitch = this.defaultArg(pitch, 0); - source.playbackRate.value = this.intervalToFrequencyRatio(pitch); - return this; - }; - /** - * Start a looping buffer by name. Similar to `start`, but the buffer - * is looped instead of played straight through. Can still be stopped with `stop`. - * @param {String} bufferName The name of the buffer to start. - * @param {Time} time When to start the buffer. - * @param {Time} [offset=0] The offset into the buffer to play from. - * @param {Time=} loopStart The start of the loop. - * @param {Time=} loopEnd The end of the loop. - * @param {Interval} [pitch=0] The interval to repitch the buffer. - * @param {Gain} [gain=1] The gain to play the sample at. - * @return {Tone.MultiPlayer} this - */ - Tone.MultiPlayer.prototype.startLoop = function (bufferName, time, offset, loopStart, loopEnd, pitch, gain) { - time = this.toSeconds(time); - var source = this._makeSource(bufferName); - source.loop = true; - source.loopStart = this.toSeconds(this.defaultArg(loopStart, 0)); - source.loopEnd = this.toSeconds(this.defaultArg(loopEnd, 0)); - source.start(time, offset, undefined, this.defaultArg(gain, 1), this.fadeIn); - pitch = this.defaultArg(pitch, 0); - source.playbackRate.value = this.intervalToFrequencyRatio(pitch); - return this; - }; - /** - * Stop the first played instance of the buffer name. - * @param {String} bufferName The buffer to stop. - * @param {Time=} time When to stop the buffer - * @return {Tone.MultiPlayer} this - */ - Tone.MultiPlayer.prototype.stop = function (bufferName, time) { - if (this._activeSources[bufferName] && this._activeSources[bufferName].length) { - time = this.toSeconds(time); - this._activeSources[bufferName].shift().stop(time, this.fadeOut); - } else { - throw new Error('Tone.MultiPlayer: cannot stop a buffer that hasn\'t been started or is already stopped'); - } - return this; - }; - /** - * Stop all currently playing buffers at the given time. - * @param {Time=} time When to stop the buffers. - * @return {Tone.MultiPlayer} this - */ - Tone.MultiPlayer.prototype.stopAll = function (time) { - time = this.toSeconds(time); - for (var bufferName in this._activeSources) { - var sources = this._activeSources[bufferName]; - for (var i = 0; i < sources.length; i++) { - sources[i].stop(time); - } - } - return this; - }; - /** - * Add another buffer to the available buffers. - * @param {String} name The name to that the buffer is refered - * to in start/stop methods. - * @param {String|Tone.Buffer} url The url of the buffer to load - * or the buffer. - * @param {Function} callback The function to invoke after the buffer is loaded. - */ - Tone.MultiPlayer.prototype.add = function (name, url, callback) { - this.buffers.add(name, url, callback); - return this; - }; - /** - * Returns the playback state of the source. "started" - * if there are any buffers playing. "stopped" otherwise. - * @type {Tone.State} - * @readOnly - * @memberOf Tone.MultiPlayer# - * @name state - */ - Object.defineProperty(Tone.MultiPlayer.prototype, 'state', { - get: function () { - return this._activeSources.length > 0 ? Tone.State.Started : Tone.State.Stopped; - } - }); - /** - * Mute the output. - * @memberOf Tone.MultiPlayer# - * @type {boolean} - * @name mute - * @example - * //mute the output - * source.mute = true; - */ - Object.defineProperty(Tone.MultiPlayer.prototype, 'mute', { - get: function () { - return this._volume.mute; - }, - set: function (mute) { - this._volume.mute = mute; - } - }); - /** - * Clean up. - * @return {Tone.MultiPlayer} this - */ - Tone.MultiPlayer.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this._volume.dispose(); - this._volume = null; - this._writable('volume'); - this.volume = null; - for (var bufferName in this._activeSources) { - this._activeSources[bufferName].forEach(function (source) { - source.dispose(); - }); - } - this.buffers.dispose(); - this.buffers = null; - this._activeSources = null; - return this; - }; - return Tone.MultiPlayer; - }); - Module(function (Tone) { - /** - * @class Tone.GrainPlayer implements [granular synthesis](https://en.wikipedia.org/wiki/Granular_synthesis). - * Granular Synthesis enables you to adjust pitch and playback rate independently. The grainSize is the - * amount of time each small chunk of audio is played for and the overlap is the - * amount of crossfading transition time between successive grains. - * @extends {Tone} - * @param {String|Tone.Buffer} url The url to load, or the Tone.Buffer to play. - * @param {Function=} callback The callback to invoke after the url is loaded. - */ - Tone.GrainPlayer = function () { - var options = this.optionsObject(arguments, [ - 'url', - 'onload' - ], Tone.GrainPlayer.defaults); - Tone.Source.call(this); - /** - * The audio buffer belonging to the player. - * @type {Tone.Buffer} - */ - this.buffer = new Tone.Buffer(options.url, options.onload); - /** - * Plays the buffer with a small envelope - * @type {Tone.MultiPlayer} - * @private - */ - this._player = new Tone.MultiPlayer().connect(this.output); - /** - * Create a repeating tick to schedule - * the grains. - * @type {Tone.Clock} - * @private - */ - this._clock = new Tone.Clock(this._tick.bind(this), 1); - /** - * @type {Number} - * @private - */ - this._loopStart = 0; - /** - * @type {Number} - * @private - */ - this._loopEnd = 0; - /** - * @type {Number} - * @private - */ - this._playbackRate = options.playbackRate; - /** - * @type {Number} - * @private - */ - this._grainSize = options.grainSize; - /** - * @private - * @type {Number} - */ - this._overlap = options.overlap; - /** - * Adjust the pitch independently of the playbackRate. - * @type {Cents} - */ - this.detune = options.detune; - /** - * The amount of time randomly added - * or subtracted from the grain's offset - * @type {Time} - */ - this.drift = options.drift; - //setup - this.overlap = options.overlap; - this.loop = options.loop; - this.playbackRate = options.playbackRate; - this.grainSize = options.grainSize; - this.loopStart = options.loopStart; - this.loopEnd = options.loopEnd; - this.reverse = options.reverse; - }; - Tone.extend(Tone.GrainPlayer, Tone.Source); - /** - * the default parameters - * @static - * @const - * @type {Object} - */ - Tone.GrainPlayer.defaults = { - 'onload': Tone.noOp, - 'overlap': 0.1, - 'grainSize': 0.2, - 'drift': 0, - 'playbackRate': 1, - 'detune': 0, - 'loop': false, - 'loopStart': 0, - 'loopEnd': 0, - 'reverse': false - }; - /** - * Play the buffer at the given startTime. Optionally add an offset - * and/or duration which will play the buffer from a position - * within the buffer for the given duration. - * - * @param {Time} [startTime=now] When the player should start. - * @param {Time} [offset=0] The offset from the beginning of the sample - * to start at. - * @param {Time=} duration How long the sample should play. If no duration - * is given, it will default to the full length - * of the sample (minus any offset) - * @returns {Tone.GrainPlayer} this - * @memberOf Tone.GrainPlayer# - * @method start - * @name start - */ - /** - * Internal start method - * @param {Time} time - * @param {Time} offset - * @private - */ - Tone.GrainPlayer.prototype._start = function (time, offset, duration) { - offset = this.defaultArg(offset, 0); - offset = this.toSeconds(offset); - time = this.toSeconds(time); - this._offset = offset; - this._clock.start(time); - //unmute the player - this._player.volume.setValueAtTime(0, time); - if (duration) { - this._stop(time + this.toSeconds(duration)); - } - }; - /** - * Internal start method - * @param {Time} time - * @private - */ - Tone.GrainPlayer.prototype._stop = function (time) { - this._clock.stop(time); - //mute the player - this._player.volume.cancelScheduledValues(time); - this._player.volume.setValueAtTime(-Infinity, time); - }; - /** - * Invoked on each clock tick. scheduled a new - * grain at this time. - * @param {Time} time - * @private - */ - Tone.GrainPlayer.prototype._tick = function (time) { - var bufferDuration = this.buffer.duration; - if (this.loop && this._loopEnd > 0) { - bufferDuration = this._loopEnd; - } - var drift = (Math.random() * 2 - 1) * this.drift; - var offset = this._offset - this._overlap + drift; - var detune = this.detune / 100; - //keep the offset within the limits of the buffer - offset = Math.max(offset, 0); - offset = Math.min(offset, bufferDuration); - var originalFadeIn = this._player.fadeIn; - if (this.loop && this._offset > bufferDuration) { - //play the end - var endSegmentDuration = this._offset - bufferDuration; - this._player.start(this.buffer, time, offset, endSegmentDuration + this._overlap, detune); - //and play the beginning - offset = this._offset % bufferDuration; - this._offset = this._loopStart; - this._player.fadeIn = 0; - this._player.start(this.buffer, time + endSegmentDuration, this._offset, offset + this._overlap, detune); - } else if (this._offset > bufferDuration) { - //set the state to stopped. - this.stop(time); - } else { - if (offset === 0) { - this._player.fadeIn = 0; - } - this._player.start(this.buffer, time, offset, this.grainSize + this._overlap, detune); - } - this._player.fadeIn = originalFadeIn; - //increment the offset - var duration = this._clock._nextTick - time; - this._offset += duration * this._playbackRate; - }; - /** - * Jump to a specific time and play it. - * @param {Time} offset The offset to jump to. - * @param {Time=} time When to make the jump. - * @return {[type]} [description] - */ - Tone.GrainPlayer.prototype.scrub = function (offset, time) { - this._offset = this.toSeconds(offset); - this._tick(this.toSeconds(time)); - return this; - }; - /** - * The playback rate of the sample - * @memberOf Tone.GrainPlayer# - * @type {Positive} - * @name playbackRate - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'playbackRate', { - get: function () { - return this._playbackRate; - }, - set: function (rate) { - this._playbackRate = rate; - this.grainSize = this._grainSize; - } - }); - /** - * The loop start time. - * @memberOf Tone.GrainPlayer# - * @type {Time} - * @name loopStart - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'loopStart', { - get: function () { - return this._loopStart; - }, - set: function (time) { - this._loopStart = this.toSeconds(time); - } - }); - /** - * The loop end time. - * @memberOf Tone.GrainPlayer# - * @type {Time} - * @name loopEnd - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'loopEnd', { - get: function () { - return this._loopEnd; - }, - set: function (time) { - this._loopEnd = this.toSeconds(time); - } - }); - /** - * The direction the buffer should play in - * @memberOf Tone.GrainPlayer# - * @type {boolean} - * @name reverse - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'reverse', { - get: function () { - return this.buffer.reverse; - }, - set: function (rev) { - this.buffer.reverse = rev; - } - }); - /** - * The size of each chunk of audio that the - * buffer is chopped into and played back at. - * @memberOf Tone.GrainPlayer# - * @type {Time} - * @name grainSize - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'grainSize', { - get: function () { - return this._grainSize; - }, - set: function (size) { - this._grainSize = this.toSeconds(size); - this._clock.frequency.value = this._playbackRate / this._grainSize; - } - }); - /** - * This is the duration of the cross-fade between - * sucessive grains. - * @memberOf Tone.GrainPlayer# - * @type {Time} - * @name overlap - */ - Object.defineProperty(Tone.GrainPlayer.prototype, 'overlap', { - get: function () { - return this._overlap; - }, - set: function (time) { - time = this.toSeconds(time); - this._overlap = time; - if (this._overlap < 0) { - this._player.fadeIn = 0.01; - this._player.fadeOut = 0.01; - } else { - this._player.fadeIn = time; - this._player.fadeOut = time; - } - } - }); - /** - * Clean up - * @return {Tone.GrainPlayer} this - */ - Tone.GrainPlayer.prototype.dispose = function () { - Tone.Source.prototype.dispose.call(this); - this.buffer.dispose(); - this.buffer = null; - this._player.dispose(); - this._player = null; - this._clock.dispose(); - this._clock = null; - return this; - }; - return Tone.GrainPlayer; - }); - Module(function (Tone) { - - /** - * @class Tone.UserMedia uses MediaDevices.getUserMedia to open up - * and external microphone or audio input. Check - * [MediaDevices API Support](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) - * to see which browsers are supported. Access to an external input - * is limited to secure (HTTPS) connections. - * - * @constructor - * @extends {Tone} - * @param {Decibels=} volume The level of the input - * @example - * //list the inputs and open the third one - * var motu = new Tone.UserMedia(); - * - * //opening the input asks the user to activate their mic - * motu.open().then(function(){ - * //opening is activates the microphone - * //starting lets audio through - * motu.start(10); - * }); - */ - Tone.UserMedia = function () { - var options = this.optionsObject(arguments, ['volume'], Tone.UserMedia.defaults); - /** - * The MediaStreamNode - * @type {MediaStreamAudioSourceNode} - * @private - */ - this._mediaStream = null; - /** - * The media stream created by getUserMedia. - * @type {LocalMediaStream} - * @private - */ - this._stream = null; - /** - * The open device - * @type {MediaDeviceInfo} - * @private - */ - this._device = null; - /** - * The output volume node - * @type {Tone.Volume} - * @private - */ - this._volume = this.output = new Tone.Volume(options.volume); - /** - * The volume of the output in decibels. - * @type {Decibels} - * @signal - * @example - * input.volume.value = -6; - */ - this.volume = this._volume.volume; - this._readOnly('volume'); - this.mute = options.mute; - }; - Tone.extend(Tone.UserMedia); - /** - * the default parameters - * @type {Object} - */ - Tone.UserMedia.defaults = { - 'volume': 0, - 'mute': false - }; - /** - * Open the media stream. If a string is passed in, it is assumed - * to be the label or id of the stream, if a number is passed in, - * it is the input number of the stream. - * @param {String|Number} [labelOrId="default"] The label or id of the audio input media device. - * With no argument, the default stream is opened. - * @return {Promise} The promise is resolved when the stream is open. - */ - Tone.UserMedia.prototype.open = function (labelOrId) { - labelOrId = this.defaultArg(labelOrId, 'default'); - return this.enumerateDevices().then(function (devices) { - var device; - if (this.isNumber(labelOrId)) { - device = devices[labelOrId]; - } else { - device = devices.find(function (device) { - return device.label === labelOrId || device.deviceId === labelOrId; - }); - if (!device) { - //otherwise just take the first one - device = devices[0]; - } - } - //didn't find a matching device - if (!device) { - throw new Error('Tone.UserMedia: no matching audio inputs.'); - } - this._device = device; - //do getUserMedia - var constraints = { - audio: { - 'deviceId': device.deviceId, - 'echoCancellation': false, - 'sampleRate': this.context.sampleRate - } - }; - return navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { - //start a new source only if the previous one is closed - if (!this._stream) { - this._stream = stream; - //Wrap a MediaStreamSourceNode around the live input stream. - this._mediaStream = this.context.createMediaStreamSource(stream); - //Connect the MediaStreamSourceNode to a gate gain node - this._mediaStream.connect(this.output); - } - return this; - }.bind(this)); - }.bind(this)); - }; - /** - * Close the media stream - * @return {Tone.UserMedia} this - */ - Tone.UserMedia.prototype.close = function () { - if (this._stream) { - this._stream.getAudioTracks().forEach(function (track) { - track.stop(); - }); - this._stream = null; - //remove the old media stream - this._mediaStream.disconnect(); - this._mediaStream = null; - } - this._device = null; - return this; - }; - /** - * Returns a promise which resolves with the list of audio input devices available. - * @return {Promise} The promise that is resolved with the devices - * @example - * extInput.enumerateDevices().then(function(devices){ - * console.log(devices) - * }) - */ - Tone.UserMedia.prototype.enumerateDevices = function () { - return navigator.mediaDevices.enumerateDevices().then(function (devices) { - return devices.filter(function (device) { - return device.kind === 'audioinput'; - }); - }); - }; - /** - * Returns the playback state of the source, "started" when the microphone is open - * and "stopped" when the mic is closed. - * @type {Tone.State} - * @readOnly - * @memberOf Tone.UserMedia# - * @name state - */ - Object.defineProperty(Tone.UserMedia.prototype, 'state', { - get: function () { - return this._stream && this._stream.active ? Tone.State.Started : Tone.State.Stopped; - } - }); - /** - * Returns an identifier for the represented device that is - * persisted across sessions. It is un-guessable by other applications and - * unique to the origin of the calling application. It is reset when the - * user clears cookies (for Private Browsing, a different identifier is - * used that is not persisted across sessions). Returns undefined when the - * device is not open. - * @type {String} - * @readOnly - * @memberOf Tone.UserMedia# - * @name deviceId - */ - Object.defineProperty(Tone.UserMedia.prototype, 'deviceId', { - get: function () { - if (this._device) { - return this._device.deviceId; - } - } - }); - /** - * Returns a group identifier. Two devices have the - * same group identifier if they belong to the same physical device. - * Returns undefined when the device is not open. - * @type {String} - * @readOnly - * @memberOf Tone.UserMedia# - * @name groupId - */ - Object.defineProperty(Tone.UserMedia.prototype, 'groupId', { - get: function () { - if (this._device) { - return this._device.groupId; - } - } - }); - /** - * Returns a label describing this device (for example "Built-in Microphone"). - * Returns undefined when the device is not open or label is not available - * because of permissions. - * @type {String} - * @readOnly - * @memberOf Tone.UserMedia# - * @name groupId - */ - Object.defineProperty(Tone.UserMedia.prototype, 'label', { - get: function () { - if (this._device) { - return this._device.label; - } - } - }); - /** - * Mute the output. - * @memberOf Tone.UserMedia# - * @type {boolean} - * @name mute - * @example - * //mute the output - * userMedia.mute = true; - */ - Object.defineProperty(Tone.UserMedia.prototype, 'mute', { - get: function () { - return this._volume.mute; - }, - set: function (mute) { - this._volume.mute = mute; - } - }); - /** - * Clean up. - * @return {Tone.UserMedia} this - */ - Tone.UserMedia.prototype.dispose = function () { - Tone.prototype.dispose.call(this); - this.close(); - this._writable('volume'); - this._volume.dispose(); - this._volume = null; - this.volume = null; - return this; - }; - /** - * If getUserMedia is supported by the browser. - * @type {Boolean} - * @memberOf Tone.UserMedia# - * @name supported - * @static - * @readOnly - */ - Object.defineProperty(Tone.UserMedia, 'supported', { - get: function () { - return !Tone.prototype.isUndef(navigator.mediaDevices) && Tone.prototype.isFunction(navigator.mediaDevices.getUserMedia); - } - }); - return Tone.UserMedia; - }); - - return Tone; -})); - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.requestAudioContext = exports.intervalInRange = exports.roundInterval = exports.clamp = exports.lerp = exports.browser = exports.mod = exports.choice = undefined; - -var _tone = __webpack_require__(1); - -var _tone2 = _interopRequireDefault(_tone); - -var _startAudioContext = __webpack_require__(14); - -var _startAudioContext2 = _interopRequireDefault(_startAudioContext); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Utilities - * @module lib/util.js; - */ - -var isIphone = navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i); -var isIpad = navigator.userAgent.match(/iPad/i); -var isAndroid = navigator.userAgent.match(/Android/i); -var isMobile = isIphone || isIpad || isAndroid; -var isDesktop = !isMobile; - -document.body.classList.add(isMobile ? "mobile" : "desktop"); - -var browser = { isIphone: isIphone, isIpad: isIpad, isMobile: isMobile, isDesktop: isDesktop }; - -function choice(a) { - return a[Math.floor(Math.random() * a.length)]; -} -function mod(n, m) { - return n - m * Math.floor(n / m); -} -function roundInterval(interval) { - return Math.round(interval * 10000000); -} -var intervalInRange = function intervalInRange(interval, root) { - return 20 < interval * root && interval * root < 15000; -}; -var lerp = function lerp(n, a, b) { - return (b - a) * n + a; -}; -var clamp = function clamp(n) { - var a = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var b = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; - return n < a ? a : n < b ? n : b; -}; - -function requestAudioContext(fn) { - if (window.location.protocol !== "https:") { - var container = document.createElement("div"); - var button = document.createElement("div"); - button.innerHTML = "Tap to start - please unmute your phone"; - Object.assign(container.style, { - display: "block", - position: "absolute", - width: "100%", - height: "100%", - zIndex: "10000", - top: "0px", - left: "0px", - backgroundColor: "rgba(0, 0, 0, 0.8)" - }); - Object.assign(button.style, { - display: "block", - position: "absolute", - left: "50%", - top: "50%", - padding: "20px", - backgroundColor: "#7F33ED", - color: "white", - fontFamily: "monospace", - borderRadius: "3px", - transform: "translate3D(-50%,-50%,0)", - textAlign: "center", - lineHeight: "1.5", - width: "150px" - }); - container.appendChild(button); - document.body.appendChild(container); - _startAudioContext2.default.setContext(_tone2.default.context); - _startAudioContext2.default.on(button); - _startAudioContext2.default.onStarted(function (_) { - container.remove(); - fn(); - }); - } else { - fn(); - } -} - -exports.choice = choice; -exports.mod = mod; -exports.browser = browser; -exports.lerp = lerp; -exports.clamp = clamp; -exports.roundInterval = roundInterval; -exports.intervalInRange = intervalInRange; -exports.requestAudioContext = requestAudioContext; - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/** -* FUNCTION: isArray( value ) -* Validates if a value is an array. -* -* @param {*} value - value to be validated -* @returns {Boolean} boolean indicating whether value is an array -*/ -function isArray( value ) { - return Object.prototype.toString.call( value ) === '[object Array]'; -} // end FUNCTION isArray() - -// EXPORTS // - -module.exports = Array.isArray || isArray; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -/** - * Iquizeles color generator - * @module lib/color.js; - */ - -var palettes = [[[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.0, 0.33, 0.67]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.0, 0.1, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.3, 0.2, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 0.5], [0.8, 0.9, 0.3]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 0.7, 0.4], [0.0, 0.15, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [2.0, 1.0, 0.0], [0.5, 0.2, 0.25]], [[0.8, 0.5, 0.4], [0.2, 0.4, 0.2], [2.0, 1.0, 1.0], [0.0, 0.25, 0.25]]]; - -var palette = palettes[0]; - -function channel(t, a, b, c, d, add, mul) { - return a + b * Math.cos(2 * Math.PI * (c * t + d)) * mul + add; -} - -function color(t, add, mul) { - var a = void 0, - b = void 0, - c = void 0, - d = void 0; - var rgb = []; - for (var i = 0; i < 3; i++) { - a = palette[0][i]; - b = palette[1][i]; - c = palette[2][i]; - d = palette[3][i]; - rgb[i] = Math.round(channel(-t, a, b, c, d, add, mul) * 255); - } - return "rgb(" + rgb + ")"; -} - -exports.default = color; - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _tone = __webpack_require__(1); - -var _tone2 = _interopRequireDefault(_tone); - -var _util = __webpack_require__(2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Kalimba - * @module lib/kalimba.js; - */ - -var player_count = 4; - -var samples = [{ root: 219.5, fn: "samples/380737__cabled-mess__sansula-01-a-raw.wav" }, { root: 260.9, fn: "samples/380736__cabled-mess__sansula-02-c-raw.wav" }, { root: 330.2, fn: "samples/380735__cabled-mess__sansula-03-e-raw.wav" }]; + List.prototype.toString = function toString () { + return this.__toString('List [', ']'); + }; -function load(_ref) { - var output = _ref.output; + // @pragma Access - samples.forEach(function (sample) { - sample.players = []; - sample.index = -1; - for (var i = 0; i < player_count; i++) { - var fn = sample.fn; - if (window.location.href.match(/asdf.us/)) { - fn = "//asdf.us/kalimba/" + fn.replace("wav", "mp3"); - } - var player = new _tone2.default.Player({ - url: fn, - retrigger: true, - playbackRate: 1 - }); - player.name = fn; - var gain = new _tone2.default.Gain(1.6); - player.connect(gain); - gain.connect(output); - sample.players.push(player); + List.prototype.get = function get (index, notSetValue) { + index = wrapIndex(this, index); + if (index >= 0 && index < this.size) { + index += this._origin; + var node = listNodeFor(this, index); + return node && node.array[index & MASK]; } - }); - console.log("+ Voices:", samples.reduce(function (count, sample) { - return count + sample.players.length; - }, 0)); -} - -function play(interval, root) { - var sample = (0, _util.choice)(samples); - sample.index = (sample.index + 1) % sample.players.length; - - var player = sample.players[sample.index]; - player.playbackRate = interval * root / sample.root; - player.start(); -} - -function pause() { - // no-op -} - -exports.default = { load: load, play: play, pause: pause }; - -// for help tuning the kalimba samples -// function keydown(e) { -// // console.log(e.keyCode) -// if (e.metaKey && last) { -// let step = e.shiftKey ? (e.ctrlKey ? 0.01 : 0.1) : 1; -// switch (e.keyCode) { -// case 38: // up -// e.preventDefault(); -// samples[0].root -= step; -// play(last); -// break; -// case 40: // down -// e.preventDefault(); -// samples[0].root += step; -// play(last); -// break; -// } -// console.log(samples[0].root); -// } -// } -// window.addEventListener("keydown", keydown, true); - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -/** - * Keyboard helper - * @module lib/keys.js; - */ - -var keys = {}; -var key_numbers = {}; -var letters = "zxcvbnmasdfghjklqwertyuiop"; -var numbers = "1234567890"; - -var callback = function callback() {}; - -letters.toUpperCase().split("").map(function (k, i) { - keys[k.charCodeAt(0)] = i; -}); - -numbers.split("").map(function (k, i) { - keys[k.charCodeAt(0)] = i + letters.length; - key_numbers[k.charCodeAt(0)] = true; -}); - -window.addEventListener("keydown", keydown, true); -function keydown(e) { - if (e.altKey || e.ctrlKey || e.metaKey) { - e.stopPropagation(); - return; - } - if (document.activeElement instanceof HTMLInputElement && e.keyCode in key_numbers) { - e.stopPropagation(); - return; - } - if (!(e.keyCode in keys)) return; - var index = keys[e.keyCode]; - if (e.shiftKey) index += letters.length; - callback(index); -} - -function listen(fn) { - callback = fn; -} - -exports.default = { listen: listen }; - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - + return notSetValue; + }; -Object.defineProperty(exports, "__esModule", { - value: true -}); + // @pragma Modification -var _webmidi = __webpack_require__(30); + List.prototype.set = function set (index, value) { + return updateList(this, index, value); + }; -function enable(play) { - _webmidi.WebMidi.enable().then(onEnabled).catch(function (error) { - return console.error(error); - }); + List.prototype.remove = function remove (index) { + return !this.has(index) + ? this + : index === 0 + ? this.shift() + : index === this.size - 1 + ? this.pop() + : this.splice(index, 1); + }; - // Function triggered when WEBMIDI.js is ready - function onEnabled() { - // Display available MIDI input devices - if (_webmidi.WebMidi.inputs.length < 1) { - console.log("No device detected."); - return; - } else { - _webmidi.WebMidi.inputs.forEach(function (device, index) { - document.body.innerHTML += index + ": " + device.name + "
"; - }); - var mySynth = _webmidi.WebMidi.inputs[0]; - // const mySynth = WebMidi.getInputByName("TYPE NAME HERE!") + List.prototype.insert = function insert (index, value) { + return this.splice(index, 0, value); + }; - mySynth.channels[1].addListener("noteon", function (event) { - console.log(event.note); - }); + List.prototype.clear = function clear () { + if (this.size === 0) { + return this; } - } -} /** - * MIDI - * @module midi.js; - */ - -exports.default = { enable: enable }; - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _tone = __webpack_require__(1); - -var _tone2 = _interopRequireDefault(_tone); - -var _util = __webpack_require__(2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sine wave organ - * @module lib/organ.js; - */ - -var root = 440; + if (this.__ownerID) { + this.size = this._origin = this._capacity = 0; + this._level = SHIFT; + this._root = this._tail = this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyList(); + }; -var oscillators = {}; -var output = void 0; -var lastPlayed = void 0; + List.prototype.push = function push (/*...values*/) { + var values = arguments; + var oldSize = this.size; + return this.withMutations(function (list) { + setListBounds(list, 0, oldSize + values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(oldSize + ii, values[ii]); + } + }); + }; -function load(out) { - output = out; -} -function isPlaying(interval) { - var rounded = (0, _util.roundInterval)(interval); - var osc = oscillators[rounded]; - return osc && osc.playing; -} -function play(interval) { - if (!output) { - return; - } - var rounded = (0, _util.roundInterval)(interval); - var osc = oscillators[rounded] = oscillators[rounded] || {}; - if (!osc.el) { - osc.interval = interval; - osc.el = new _tone2.default.Oscillator(interval * root, "sine"); - osc.el.connect(output); - } - osc.el.start(); - osc.playing = true; - lastPlayed = osc; - return osc; -} + List.prototype.pop = function pop () { + return setListBounds(this, 0, -1); + }; -function pause(interval) { - var rounded = (0, _util.roundInterval)(interval); - if (!oscillators[rounded]) return; - var osc = oscillators[rounded] = oscillators[rounded] || {}; - if (osc.el) { - osc.el.stop(); - } - osc.playing = false; - return osc; -} + List.prototype.unshift = function unshift (/*...values*/) { + var values = arguments; + return this.withMutations(function (list) { + setListBounds(list, -values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(ii, values[ii]); + } + }); + }; -function setRoot(newRoot) { - root = newRoot; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + List.prototype.shift = function shift () { + return setListBounds(this, 1); + }; - try { - for (var _iterator = Object.values(oscillators)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var osc = _step.value; + List.prototype.shuffle = function shuffle (random) { + if ( random === void 0 ) random = Math.random; - osc.el.frequency.value = osc.interval * newRoot; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } -} -function stop() { - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; + return this.withMutations(function (mutable) { + // implementation of the Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle + var current = mutable.size; + var destination; + var tmp; - try { - for (var _iterator2 = Object.values(oscillators)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var osc = _step2.value; + while (current) { + destination = Math.floor(random() * current--); - osc.el.stop(); - osc.el.disconnect(); - osc.playing = false; - delete osc.el; - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); + tmp = mutable.get(destination); + mutable.set(destination, mutable.get(current)); + mutable.set(current, tmp); } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; + }); + }; + + // @pragma Composition + + List.prototype.concat = function concat (/*...collections*/) { + var arguments$1 = arguments; + + var seqs = []; + for (var i = 0; i < arguments.length; i++) { + var argument = arguments$1[i]; + var seq = IndexedCollection( + typeof argument !== 'string' && hasIterator(argument) + ? argument + : [argument] + ); + if (seq.size !== 0) { + seqs.push(seq); } } - } - - oscillators = {}; -} + if (seqs.length === 0) { + return this; + } + if (this.size === 0 && !this.__ownerID && seqs.length === 1) { + return this.constructor(seqs[0]); + } + return this.withMutations(function (list) { + seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); }); + }); + }; -exports.default = { load: load, isPlaying: isPlaying, play: play, pause: pause, stop: stop, setRoot: setRoot }; + List.prototype.setSize = function setSize (size) { + return setListBounds(this, 0, size); + }; -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { + List.prototype.map = function map (mapper, context) { + var this$1$1 = this; -"use strict"; + return this.withMutations(function (list) { + for (var i = 0; i < this$1$1.size; i++) { + list.set(i, mapper.call(context, list.get(i), i, this$1$1)); + } + }); + }; + // @pragma Iteration -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getOutput = getOutput; + List.prototype.slice = function slice (begin, end) { + var size = this.size; + if (wholeSlice(begin, end, size)) { + return this; + } + return setListBounds( + this, + resolveBegin(begin, size), + resolveEnd(end, size) + ); + }; -var _tone = __webpack_require__(1); + List.prototype.__iterator = function __iterator (type, reverse) { + var index = reverse ? this.size : 0; + var values = iterateList(this, reverse); + return new Iterator(function () { + var value = values(); + return value === DONE + ? iteratorDone() + : iteratorValue(type, reverse ? --index : index++, value); + }); + }; -var _tone2 = _interopRequireDefault(_tone); + List.prototype.__iterate = function __iterate (fn, reverse) { + var index = reverse ? this.size : 0; + var values = iterateList(this, reverse); + var value; + while ((value = values()) !== DONE) { + if (fn(value, reverse ? --index : index++, this) === false) { + break; + } + } + return index; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + List.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + if (this.size === 0) { + return emptyList(); + } + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeList( + this._origin, + this._capacity, + this._level, + this._root, + this._tail, + ownerID, + this.__hash + ); + }; -var output = null; /** - * Common output stage - * @module lib/output.js; - */ + return List; +}(IndexedCollection)); -function getOutput() { - if (!output) output = makeOutput(); - return output; -} +List.isList = isList; -function makeOutput() { - var compressor = new _tone2.default.Compressor(-30, 3); - var gain = new _tone2.default.Gain(0.3); - compressor.connect(gain); - gain.toMaster(); +var ListPrototype = List.prototype; +ListPrototype[IS_LIST_SYMBOL] = true; +ListPrototype[DELETE] = ListPrototype.remove; +ListPrototype.merge = ListPrototype.concat; +ListPrototype.setIn = setIn; +ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn; +ListPrototype.update = update; +ListPrototype.updateIn = updateIn; +ListPrototype.mergeIn = mergeIn; +ListPrototype.mergeDeepIn = mergeDeepIn; +ListPrototype.withMutations = withMutations; +ListPrototype.wasAltered = wasAltered; +ListPrototype.asImmutable = asImmutable; +ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable; +ListPrototype['@@transducer/step'] = function (result, arr) { + return result.push(arr); +}; +ListPrototype['@@transducer/result'] = function (obj) { + return obj.asImmutable(); +}; - return compressor; -} +var VNode = function VNode(array, ownerID) { + this.array = array; + this.ownerID = ownerID; +}; -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { +// TODO: seems like these methods are very similar -"use strict"; +VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) { + if ( + (index & ((1 << (level + SHIFT)) - 1)) === 0 || + this.array.length === 0 + ) { + return this; + } + var originIndex = (index >>> level) & MASK; + if (originIndex >= this.array.length) { + return new VNode([], ownerID); + } + var removingFirst = originIndex === 0; + var newChild; + if (level > 0) { + var oldChild = this.array[originIndex]; + newChild = + oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); + if (newChild === oldChild && removingFirst) { + return this; + } + } + if (removingFirst && !newChild) { + return this; + } + var editable = editableVNode(this, ownerID); + if (!removingFirst) { + for (var ii = 0; ii < originIndex; ii++) { + editable.array[ii] = undefined; + } + } + if (newChild) { + editable.array[originIndex] = newChild; + } + return editable; +}; +VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) { + if ( + index === (level ? 1 << (level + SHIFT) : SIZE) || + this.array.length === 0 + ) { + return this; + } + var sizeIndex = ((index - 1) >>> level) & MASK; + if (sizeIndex >= this.array.length) { + return this; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.load = load; -exports.dragOver = dragOver; -exports.drop = drop; -exports.loadSampleFromFile = loadSampleFromFile; + var newChild; + if (level > 0) { + var oldChild = this.array[sizeIndex]; + newChild = + oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); + if (newChild === oldChild && sizeIndex === this.array.length - 1) { + return this; + } + } -var _tone = __webpack_require__(1); + var editable = editableVNode(this, ownerID); + editable.array.splice(sizeIndex + 1); + if (newChild) { + editable.array[sizeIndex] = newChild; + } + return editable; +}; -var _tone2 = _interopRequireDefault(_tone); +var DONE = {}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function iterateList(list, reverse) { + var left = list._origin; + var right = list._capacity; + var tailPos = getTailOffset(right); + var tail = list._tail; -function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** - * Sampler - * @module lib/sampler.js; - */ + return iterateNodeOrLeaf(list._root, list._level, 0); -var root = 440; + function iterateNodeOrLeaf(node, level, offset) { + return level === 0 + ? iterateLeaf(node, offset) + : iterateNode(node, level, offset); + } -var output = void 0; -var ready = void 0; -var current = ""; -var samples = {}; + function iterateLeaf(node, offset) { + var array = offset === tailPos ? tail && tail.array : node && node.array; + var from = offset > left ? 0 : left - offset; + var to = right - offset; + if (to > SIZE) { + to = SIZE; + } + return function () { + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + return array && array[idx]; + }; + } -var player_count = 12; + function iterateNode(node, level, offset) { + var values; + var array = node && node.array; + var from = offset > left ? 0 : (left - offset) >> level; + var to = ((right - offset) >> level) + 1; + if (to > SIZE) { + to = SIZE; + } + return function () { + while (true) { + if (values) { + var value = values(); + if (value !== DONE) { + return value; + } + values = null; + } + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + values = iterateNodeOrLeaf( + array && array[idx], + level - SHIFT, + offset + (idx << level) + ); + } + }; + } +} -function load(out, readyCallback) { - output = out; - ready = readyCallback; - document.body.addEventListener("dragover", dragOver); - document.body.addEventListener("drop", drop); +function makeList(origin, capacity, level, root, tail, ownerID, hash) { + var list = Object.create(ListPrototype); + list.size = capacity - origin; + list._origin = origin; + list._capacity = capacity; + list._level = level; + list._root = root; + list._tail = tail; + list.__ownerID = ownerID; + list.__hash = hash; + list.__altered = false; + return list; } -/** - * Drag and drop - */ -function dragOver(event) { - event.preventDefault(); +function emptyList() { + return makeList(0, 0, SHIFT); } -function drop(event) { - event.preventDefault(); - var files = event.dataTransfer.items ? [].concat(_toConsumableArray(event.dataTransfer.items)).filter(function (item) { - return item.kind === "file"; - }).map(function (item) { - return item.getAsFile(); - }) : [].concat(_toConsumableArray(event.dataTransfer.files)); - var file = files[0]; - var reader = new FileReader(); +function updateList(list, index, value) { + index = wrapIndex(list, index); - reader.addEventListener("load", function () { - return loadSampleFromFile(file, reader.result); - }, false); + if (index !== index) { + return list; + } - if (file) { - reader.readAsDataURL(file); + if (index >= list.size || index < 0) { + return list.withMutations(function (list) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + index < 0 + ? setListBounds(list, index).set(0, value) + : setListBounds(list, 0, index + 1).set(index, value); + }); } -} -function loadSampleFromFile(file, url) { - var name = file.name; + index += list._origin; - current = name; + var newTail = list._tail; + var newRoot = list._root; + var didAlter = MakeRef(); + if (index >= getTailOffset(list._capacity)) { + newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); + } else { + newRoot = updateVNode( + newRoot, + list.__ownerID, + list._level, + index, + value, + didAlter + ); + } - var sample = samples[name] = samples[name] || {}; - sample.root = 440; - sample.players = []; - sample.index = -1; - for (var i = 0; i < player_count; i++) { - var player = new _tone2.default.Player({ - url: url, - retrigger: true, - playbackRate: 1 - }); - player.name = name; - player.connect(output); - sample.players.push(player); + if (!didAlter.value) { + return list; } - console.log("+ Sampler:", name, "(" + sample.players.length + " voices)"); - ready(); -} -/** - * Player - */ -var last = [1, 440]; + if (list.__ownerID) { + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(list._origin, list._capacity, list._level, newRoot, newTail); +} -function stop() { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; +function updateVNode(node, ownerID, level, index, value, didAlter) { + var idx = (index >>> level) & MASK; + var nodeHas = node && idx < node.array.length; + if (!nodeHas && value === undefined) { + return node; + } - try { - for (var _iterator = Object.values(samples)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var sample = _step.value; + var newNode; - sample.players.forEach(function (player) { - return player.stop(); - }); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } + if (level > 0) { + var lowerNode = node && node.array[idx]; + var newLowerNode = updateVNode( + lowerNode, + ownerID, + level - SHIFT, + index, + value, + didAlter + ); + if (newLowerNode === lowerNode) { + return node; } + newNode = editableVNode(node, ownerID); + newNode.array[idx] = newLowerNode; + return newNode; } -} -function play(interval, root) { - last = [interval, root]; - var sample = samples[current]; - sample.index = (sample.index + 1) % sample.players.length; - var player = sample.players[sample.index]; - player.playbackRate = interval * root / sample.root; - player.start(); -} -function pause() { - // no-op -} + if (nodeHas && node.array[idx] === value) { + return node; + } -exports.default = { load: load, play: play, pause: pause, stop: stop }; + if (didAlter) { + SetRef(didAlter); + } -// for help tuning + newNode = editableVNode(node, ownerID); + if (value === undefined && idx === newNode.array.length - 1) { + newNode.array.pop(); + } else { + newNode.array[idx] = value; + } + return newNode; +} -function keydown(e) { - // console.log(e.keyCode) - if (e.metaKey && last && current) { - var sample = samples[current]; - var step = e.shiftKey ? e.ctrlKey ? 0.1 : 1 : 10; - switch (e.keyCode) { - case 38: - // up - e.preventDefault(); - sample.root -= step; - stop(); - play(last[0], last[1]); - break; - case 40: - // down - e.preventDefault(); - sample.root += step; - stop(); - play(last[0], last[1]); - break; - } +function editableVNode(node, ownerID) { + if (ownerID && node && ownerID === node.ownerID) { + return node; } + return new VNode(node ? node.array.slice() : [], ownerID); } -window.addEventListener("keydown", keydown, true); -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { +function listNodeFor(list, rawIndex) { + if (rawIndex >= getTailOffset(list._capacity)) { + return list._tail; + } + if (rawIndex < 1 << (list._level + SHIFT)) { + var node = list._root; + var level = list._level; + while (node && level > 0) { + node = node.array[(rawIndex >>> level) & MASK]; + level -= SHIFT; + } + return node; + } +} -"use strict"; +function setListBounds(list, begin, end) { + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin |= 0; + } + if (end !== undefined) { + end |= 0; + } + var owner = list.__ownerID || new OwnerID(); + var oldOrigin = list._origin; + var oldCapacity = list._capacity; + var newOrigin = oldOrigin + begin; + var newCapacity = + end === undefined + ? oldCapacity + : end < 0 + ? oldCapacity + end + : oldOrigin + end; + if (newOrigin === oldOrigin && newCapacity === oldCapacity) { + return list; + } + // If it's going to end after it starts, it's empty. + if (newOrigin >= newCapacity) { + return list.clear(); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.scales = undefined; + var newLevel = list._level; + var newRoot = list._root; -__webpack_require__(635); + // New origin might need creating a higher root. + var offsetShift = 0; + while (newOrigin + offsetShift < 0) { + newRoot = new VNode( + newRoot && newRoot.array.length ? [undefined, newRoot] : [], + owner + ); + newLevel += SHIFT; + offsetShift += 1 << newLevel; + } + if (offsetShift) { + newOrigin += offsetShift; + oldOrigin += offsetShift; + newCapacity += offsetShift; + oldCapacity += offsetShift; + } -__webpack_require__(636); + var oldTailOffset = getTailOffset(oldCapacity); + var newTailOffset = getTailOffset(newCapacity); -var _index = __webpack_require__(19); + // New size might need creating a higher root. + while (newTailOffset >= 1 << (newLevel + SHIFT)) { + newRoot = new VNode( + newRoot && newRoot.array.length ? [newRoot] : [], + owner + ); + newLevel += SHIFT; + } -var a = void 0, - b = void 0; /** - * Scales - * @module client/lib/scales.js; - */ + // Locate or create the new tail. + var oldTail = list._tail; + var newTail = + newTailOffset < oldTailOffset + ? listNodeFor(list, newCapacity - 1) + : newTailOffset > oldTailOffset + ? new VNode([], owner) + : oldTail; -var scales = exports.scales = [{ name: "natural", get: function get(i, j) { - return [i + 1, j + 1]; - } }, { name: "undertone", get: function get(i, j) { - return [i + 1, i + j + 2]; - } }, { name: "overtone", get: function get(i, j) { - return [i + j + 2, j + 1]; - } }, { - name: "primes", - reset: function reset(x, y, w, h) { - a = (0, _index.Prime)().skip(x).take(w).toJS(); - b = (0, _index.Prime)().skip(y).take(h).toJS(); - }, - get: function get(ii, jj, i, j) { - return [a[i], b[j]]; - } -}, { - name: "arithmetic", - reset: function reset(x, y, w, h) { - a = (0, _index.Arithmetic)(x + 1, x + 1).take(w).toJS(); - b = (0, _index.Arithmetic)(y + 1, y + 1).take(h).toJS(); - console.log(a); - }, - get: function get(ii, jj, i, j) { - return [a[i], b[j]]; - } -}, -// { -// name: "triangle", -// reset: (x, y, w, h) => { -// a = Triangle().skip(x).take(w).toJS(); -// b = Triangle().skip(y).take(h).toJS(); -// }, -// get: (ii, jj, i, j) => [a[i], b[j]], -// }, -{ - name: "collatz", - reset: function reset(x, y, w, h) { - a = (0, _index.Collatz)(x + 1).take(w).toJS(); - b = (0, _index.Collatz)(y + 1).take(h).toJS(); - }, - get: function get(ii, jj, i, j) { - return [a[i], b[j]]; + // Merge Tail into tree. + if ( + oldTail && + newTailOffset > oldTailOffset && + newOrigin < oldCapacity && + oldTail.array.length + ) { + newRoot = editableVNode(newRoot, owner); + var node = newRoot; + for (var level = newLevel; level > SHIFT; level -= SHIFT) { + var idx = (oldTailOffset >>> level) & MASK; + node = node.array[idx] = editableVNode(node.array[idx], owner); + } + node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } -}, { - name: "pythagorean", - get: function get(i, j) { - return i < j ? [Math.pow(3, i + 1), Math.pow(2, j + Math.ceil(Math.max(0, i * 1.0 / 2)))] : [Math.pow(2, i + Math.ceil(Math.max(0, j * 1.2 / 2))), Math.pow(3, j)]; + + // If the size has been reduced, there's a chance the tail needs to be trimmed. + if (newCapacity < oldCapacity) { + newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } -}]; -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { + // If the new origin is within the tail, then we do not need a root. + if (newOrigin >= newTailOffset) { + newOrigin -= newTailOffset; + newCapacity -= newTailOffset; + newLevel = SHIFT; + newRoot = null; + newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); -"use strict"; + // Otherwise, if the root has been trimmed, garbage collect. + } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { + offsetShift = 0; + // Identify the new top root node of the subtree of the old root. + while (newRoot) { + var beginIndex = (newOrigin >>> newLevel) & MASK; + if ((beginIndex !== newTailOffset >>> newLevel) & MASK) { + break; + } + if (beginIndex) { + offsetShift += (1 << newLevel) * beginIndex; + } + newLevel -= SHIFT; + newRoot = newRoot.array[beginIndex]; + } -// MODULES // + // Trim the new sides of the new root. + if (newRoot && newOrigin > oldOrigin) { + newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); + } + if (newRoot && newTailOffset < oldTailOffset) { + newRoot = newRoot.removeAfter( + owner, + newLevel, + newTailOffset - offsetShift + ); + } + if (offsetShift) { + newOrigin -= offsetShift; + newCapacity -= offsetShift; + } + } -var isArray = __webpack_require__( 3 ), - isIntegerArray = __webpack_require__( 27 ), - isFunction = __webpack_require__( 26 ); + if (list.__ownerID) { + list.size = newCapacity - newOrigin; + list._origin = newOrigin; + list._capacity = newCapacity; + list._level = newLevel; + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); +} +function getTailOffset(size) { + return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT; +} -// VARIABLES // +var OrderedMap = /*@__PURE__*/(function (Map) { + function OrderedMap(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptyOrderedMap() + : isOrderedMap(value) + ? value + : emptyOrderedMap().withMutations(function (map) { + var iter = KeyedCollection(value); + assertNotInfinite(iter.size); + iter.forEach(function (v, k) { return map.set(k, v); }); + }); + } -var MAXINT = Math.pow( 2, 31 ) - 1; + if ( Map ) OrderedMap.__proto__ = Map; + OrderedMap.prototype = Object.create( Map && Map.prototype ); + OrderedMap.prototype.constructor = OrderedMap; + OrderedMap.of = function of (/*...values*/) { + return this(arguments); + }; -// FUNCTIONS // + OrderedMap.prototype.toString = function toString () { + return this.__toString('OrderedMap {', '}'); + }; -/** -* FUNCTION: gcd( a, b ) -* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm. -* -* @param {Number} a - integer -* @param {Number} b - integer -* @returns {Number} greatest common divisor -*/ -function gcd( a, b ) { - var k = 1, - t; - // Simple cases: - if ( a === 0 ) { - return b; - } - if ( b === 0 ) { - return a; - } - // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... - while ( a%2 === 0 && b%2 === 0 ) { - a = a / 2; // right shift - b = b / 2; // right shift - k = k * 2; // left shift - } - // Reduce `a` to an odd number... - while ( a%2 === 0 ) { - a = a / 2; // right shift - } - // Henceforth, `a` is always odd... - while ( b ) { - // Remove all factors of 2 in `b`, as they are not common... - while ( b%2 === 0 ) { - b = b / 2; // right shift - } - // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... - if ( a > b ) { - t = b; - b = a; - a = t; - } - b = b - a; // b=0 iff b=a - } - // Restore common factors of 2... - return k * a; -} // end FUNCTION gcd() + // @pragma Access -/** -* FUNCTION: bitwise( a, b ) -* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm and bitwise operations. -* -* @param {Number} a - safe integer -* @param {Number} b - safe integer -* @returns {Number} greatest common divisor -*/ -function bitwise( a, b ) { - var k = 0, - t; - // Simple cases: - if ( a === 0 ) { - return b; - } - if ( b === 0 ) { - return a; - } - // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... - while ( (a & 1) === 0 && (b & 1) === 0 ) { - a >>>= 1; // right shift - b >>>= 1; // right shift - k++; - } - // Reduce `a` to an odd number... - while ( (a & 1) === 0 ) { - a >>>= 1; // right shift - } - // Henceforth, `a` is always odd... - while ( b ) { - // Remove all factors of 2 in `b`, as they are not common... - while ( (b & 1) === 0 ) { - b >>>= 1; // right shift - } - // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... - if ( a > b ) { - t = b; - b = a; - a = t; - } - b = b - a; // b=0 iff b=a - } - // Restore common factors of 2... - return a << k; -} // end FUNCTION bitwise() + OrderedMap.prototype.get = function get (k, notSetValue) { + var index = this._map.get(k); + return index !== undefined ? this._list.get(index)[1] : notSetValue; + }; + // @pragma Modification -// GREATEST COMMON DIVISOR // + OrderedMap.prototype.clear = function clear () { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._map.clear(); + this._list.clear(); + this.__altered = true; + return this; + } + return emptyOrderedMap(); + }; -/** -* FUNCTION: compute( arr[, clbk] ) -* Computes the greatest common divisor. -* -* @param {Number[]|Number} arr - input array of integers -* @param {Function|Number} [clbk] - accessor function for accessing array values -* @returns {Number|Null} greatest common divisor or null -*/ -function compute() { - var nargs = arguments.length, - args, - clbk, - arr, - len, - a, b, - i; + OrderedMap.prototype.set = function set (k, v) { + return updateOrderedMap(this, k, v); + }; - // Copy the input arguments to an array... - args = new Array( nargs ); - for ( i = 0; i < nargs; i++ ) { - args[ i ] = arguments[ i ]; - } - // Have we been provided with integer arguments? - if ( isIntegerArray( args ) ) { - if ( nargs === 2 ) { - a = args[ 0 ]; - b = args[ 1 ]; - if ( a < 0 ) { - a = -a; - } - if ( b < 0 ) { - b = -b; - } - if ( a <= MAXINT && b <= MAXINT ) { - return bitwise( a, b ); - } else { - return gcd( a, b ); - } - } - arr = args; - } - // If not integers, ensure the first argument is an array... - else if ( !isArray( args[ 0 ] ) ) { - throw new TypeError( 'gcd()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' ); - } - // Have we been provided with more than one argument? If so, ensure that the accessor argument is a function... - else if ( nargs > 1 ) { - arr = args[ 0 ]; - clbk = args[ 1 ]; - if ( !isFunction( clbk ) ) { - throw new TypeError( 'gcd()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' ); - } - } - // We have been provided an array... - else { - arr = args[ 0 ]; - } - len = arr.length; + OrderedMap.prototype.remove = function remove (k) { + return updateOrderedMap(this, k, NOT_SET); + }; - // Check if a sufficient number of values have been provided... - if ( len < 2 ) { - return null; - } - // If an accessor is provided, extract the array values... - if ( clbk ) { - a = new Array( len ); - for ( i = 0; i < len; i++ ) { - a[ i ] = clbk( arr[ i ], i ); - } - arr = a; - } - // Given an input array, ensure all array values are integers... - if ( nargs < 3 ) { - if ( !isIntegerArray( arr ) ) { - throw new TypeError( 'gcd()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' ); - } - } - // Convert any negative integers to positive integers... - for ( i = 0; i < len; i++ ) { - a = arr[ i ]; - if ( a < 0 ) { - arr[ i ] = -a; - } - } - // Exploit the fact that the gcd is an associative function... - a = arr[ 0 ]; - for ( i = 1; i < len; i++ ) { - b = arr[ i ]; - if ( b <= MAXINT && a <= MAXINT ) { - a = bitwise( a, b ); - } else { - a = gcd( a, b ); - } - } - return a; -} // end FUNCTION compute() + OrderedMap.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; + return this._list.__iterate( + function (entry) { return entry && fn(entry[1], entry[0], this$1$1); }, + reverse + ); + }; -// EXPORTS // + OrderedMap.prototype.__iterator = function __iterator (type, reverse) { + return this._list.fromEntrySeq().__iterator(type, reverse); + }; -module.exports = compute; + OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + var newList = this._list.__ensureOwner(ownerID); + if (!ownerID) { + if (this.size === 0) { + return emptyOrderedMap(); + } + this.__ownerID = ownerID; + this.__altered = false; + this._map = newMap; + this._list = newList; + return this; + } + return makeOrderedMap(newMap, newList, ownerID, this.__hash); + }; + return OrderedMap; +}(Map)); -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { +OrderedMap.isOrderedMap = isOrderedMap; -"use strict"; +OrderedMap.prototype[IS_ORDERED_SYMBOL] = true; +OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; +function makeOrderedMap(map, list, ownerID, hash) { + var omap = Object.create(OrderedMap.prototype); + omap.size = map ? map.size : 0; + omap._map = map; + omap._list = list; + omap.__ownerID = ownerID; + omap.__hash = hash; + omap.__altered = false; + return omap; +} -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /** - * Lambdoma Triangle - * @module index.js; - */ +var EMPTY_ORDERED_MAP; +function emptyOrderedMap() { + return ( + EMPTY_ORDERED_MAP || + (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())) + ); +} -var _computeGcd = __webpack_require__(12); +function updateOrderedMap(omap, k, v) { + var map = omap._map; + var list = omap._list; + var i = map.get(k); + var has = i !== undefined; + var newMap; + var newList; + if (v === NOT_SET) { + // removed + if (!has) { + return omap; + } + if (list.size >= SIZE && list.size >= map.size * 2) { + newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; }); + newMap = newList + .toKeyedSeq() + .map(function (entry) { return entry[0]; }) + .flip() + .toMap(); + if (omap.__ownerID) { + newMap.__ownerID = newList.__ownerID = omap.__ownerID; + } + } else { + newMap = map.remove(k); + newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); + } + } else if (has) { + if (v === list.get(i)[1]) { + return omap; + } + newMap = map; + newList = list.set(i, [k, v]); + } else { + newMap = map.set(k, list.size); + newList = list.set(list.size, [k, v]); + } + if (omap.__ownerID) { + omap.size = newMap.size; + omap._map = newMap; + omap._list = newList; + omap.__hash = undefined; + omap.__altered = true; + return omap; + } + return makeOrderedMap(newMap, newList); +} -var _computeGcd2 = _interopRequireDefault(_computeGcd); +var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@'; +/** + * True if `maybeStack` is a Stack. + */ +function isStack(maybeStack) { + return Boolean(maybeStack && + // @ts-expect-error: maybeStack is typed as `{}`, need to change in 6.0 to `maybeStack && typeof maybeStack === 'object' && MAYBE_STACK_SYMBOL in maybeStack` + maybeStack[IS_STACK_SYMBOL]); +} -var _keys = __webpack_require__(6); +var Stack = /*@__PURE__*/(function (IndexedCollection) { + function Stack(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptyStack() + : isStack(value) + ? value + : emptyStack().pushAll(value); + } -var _keys2 = _interopRequireDefault(_keys); + if ( IndexedCollection ) Stack.__proto__ = IndexedCollection; + Stack.prototype = Object.create( IndexedCollection && IndexedCollection.prototype ); + Stack.prototype.constructor = Stack; -var _color = __webpack_require__(4); + Stack.of = function of (/*...values*/) { + return this(arguments); + }; -var _color2 = _interopRequireDefault(_color); + Stack.prototype.toString = function toString () { + return this.__toString('Stack [', ']'); + }; -var _kalimba = __webpack_require__(5); + // @pragma Access -var _kalimba2 = _interopRequireDefault(_kalimba); + Stack.prototype.get = function get (index, notSetValue) { + var head = this._head; + index = wrapIndex(this, index); + while (head && index--) { + head = head.next; + } + return head ? head.value : notSetValue; + }; -var _sampler = __webpack_require__(10); + Stack.prototype.peek = function peek () { + return this._head && this._head.value; + }; -var _sampler2 = _interopRequireDefault(_sampler); + // @pragma Modification -var _organ = __webpack_require__(8); + Stack.prototype.push = function push (/*...values*/) { + var arguments$1 = arguments; -var _organ2 = _interopRequireDefault(_organ); + if (arguments.length === 0) { + return this; + } + var newSize = this.size + arguments.length; + var head = this._head; + for (var ii = arguments.length - 1; ii >= 0; ii--) { + head = { + value: arguments$1[ii], + next: head, + }; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pushAll = function pushAll (iter) { + iter = IndexedCollection(iter); + if (iter.size === 0) { + return this; + } + if (this.size === 0 && isStack(iter)) { + return iter; + } + assertNotInfinite(iter.size); + var newSize = this.size; + var head = this._head; + iter.__iterate(function (value) { + newSize++; + head = { + value: value, + next: head, + }; + }, /* reverse */ true); + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; -var _midi = __webpack_require__(7); + Stack.prototype.pop = function pop () { + return this.slice(1); + }; -var _midi2 = _interopRequireDefault(_midi); + Stack.prototype.clear = function clear () { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._head = undefined; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyStack(); + }; + + Stack.prototype.slice = function slice (begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + var resolvedBegin = resolveBegin(begin, this.size); + var resolvedEnd = resolveEnd(end, this.size); + if (resolvedEnd !== this.size) { + // super.slice(begin, end); + return IndexedCollection.prototype.slice.call(this, begin, end); + } + var newSize = this.size - resolvedBegin; + var head = this._head; + while (resolvedBegin--) { + head = head.next; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; -var _oktransition = __webpack_require__(637); + // @pragma Mutability -var _oktransition2 = _interopRequireDefault(_oktransition); + Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + if (this.size === 0) { + return emptyStack(); + } + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeStack(this.size, this._head, ownerID, this.__hash); + }; -var _output = __webpack_require__(9); + // @pragma Iteration -var _util = __webpack_require__(2); + Stack.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; -var _scales = __webpack_require__(11); + if (reverse) { + return new ArraySeq(this.toArray()).__iterate( + function (v, k) { return fn(v, k, this$1$1); }, + reverse + ); + } + var iterations = 0; + var node = this._head; + while (node) { + if (fn(node.value, iterations++, this) === false) { + break; + } + node = node.next; + } + return iterations; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + Stack.prototype.__iterator = function __iterator (type, reverse) { + if (reverse) { + return new ArraySeq(this.toArray()).__iterator(type, reverse); + } + var iterations = 0; + var node = this._head; + return new Iterator(function () { + if (node) { + var value = node.value; + node = node.next; + return iteratorValue(type, iterations++, value); + } + return iteratorDone(); + }); + }; -var instrument = _kalimba2.default; + return Stack; +}(IndexedCollection)); -var grid = document.createElement("grid"); -var root = 440; -var s = 50; -var w = void 0, - h = void 0, - ws = void 0, - hs = void 0; +Stack.isStack = isStack; -var add_on = 0; -var mul_on = 1.0; -var add_off = 0.1; -var mul_off = 0.9; +var StackPrototype = Stack.prototype; +StackPrototype[IS_STACK_SYMBOL] = true; +StackPrototype.shift = StackPrototype.pop; +StackPrototype.unshift = StackPrototype.push; +StackPrototype.unshiftAll = StackPrototype.pushAll; +StackPrototype.withMutations = withMutations; +StackPrototype.wasAltered = wasAltered; +StackPrototype.asImmutable = asImmutable; +StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable; +StackPrototype['@@transducer/step'] = function (result, arr) { + return result.unshift(arr); +}; +StackPrototype['@@transducer/result'] = function (obj) { + return obj.asImmutable(); +}; -var dragging = false; -var erasing = false; -var lastNote = 0; -var notes = []; -var base_x = 0; -var base_y = 0; -var scaleMode = 0; -var is_split = false; -var intervals = void 0; +function makeStack(size, head, ownerID, hash) { + var map = Object.create(StackPrototype); + map.size = size; + map._head = head; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; +} -(0, _util.requestAudioContext)(function () { - var output = (0, _output.getOutput)(); - document.body.appendChild(grid); - _kalimba2.default.load(output); - _organ2.default.load(output); - _sampler2.default.load(output, function ready() { - instrument = _sampler2.default; - }); - build(); - bind(); -}); +var EMPTY_STACK; +function emptyStack() { + return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); +} -function build() { - w = window.innerWidth; - h = window.innerHeight; - ws = Math.ceil(w / s); - hs = Math.ceil(h / s); - var scale = _scales.scales[scaleMode % _scales.scales.length]; - if (scale.reset) { - scale.reset(Math.round(base_x), Math.round(base_y), ws, hs); - } - for (var i = 0; i < ws; i++) { - notes[i] = []; - for (var j = 0; j < hs; j++) { - notes[i][j] = add(i, j); - } - } - log(); +var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@'; +/** + * True if `maybeSet` is a Set. + * + * Also true for OrderedSets. + */ +function isSet(maybeSet) { + return Boolean(maybeSet && + // @ts-expect-error: maybeSet is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSet === 'object' && MAYBE_SET_SYMBOL in maybeSet` + maybeSet[IS_SET_SYMBOL]); } -function rebuild() { - notes.forEach(function (row) { - return row.forEach(function (note) { - return note.destroy(); - }); - }); - build(); + +/** + * True if `maybeOrderedSet` is an OrderedSet. + */ +function isOrderedSet(maybeOrderedSet) { + return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } -function log() { - var seen = {}; - // console.log(notes); - for (var i = 0; i < 8; i++) { - for (var j = 0; j < 8; j++) { - var interval = notes[i][j].interval; - var rounded = (0, _util.roundInterval)(interval); - if (!seen[rounded] && (0, _util.intervalInRange)(interval, root)) { - seen[rounded] = notes[i][j].interval; - } + +function deepEqual(a, b) { + if (a === b) { + return true; } - } - intervals = Object.values(seen).sort(function (a, b) { - return a - b; - }); - // console.log(intervals); - console.log(intervals.length, "unique intervals in 8x8"); -} -function play(note) { - if (!_organ2.default.isPlaying(note.interval)) { - var interval = note.interval; - // while (interval < root) { - // interval *= 2; - // } - // while (interval > root) { - // interval /= 2; - // } - var rounded = (0, _util.roundInterval)(note.interval); - _organ2.default.play(interval); - notes.forEach(function (row) { - return row.forEach(function (note) { - return note.rounded === rounded && note.div.classList.add("playing"); - }); + if (!isCollection(b) || + // @ts-expect-error size should exists on Collection + (a.size !== undefined && b.size !== undefined && a.size !== b.size) || + // @ts-expect-error __hash exists on Collection + (a.__hash !== undefined && + // @ts-expect-error __hash exists on Collection + b.__hash !== undefined && + // @ts-expect-error __hash exists on Collection + a.__hash !== b.__hash) || + isKeyed(a) !== isKeyed(b) || + isIndexed(a) !== isIndexed(b) || + // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid + isOrdered(a) !== isOrdered(b)) { + return false; + } + // @ts-expect-error size should exists on Collection + if (a.size === 0 && b.size === 0) { + return true; + } + var notAssociative = !isAssociative(a); + // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid + if (isOrdered(a)) { + var entries = a.entries(); + // @ts-expect-error need to cast as boolean + return (b.every(function (v, k) { + var entry = entries.next().value; + return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); + }) && entries.next().done); + } + var flipped = false; + if (a.size === undefined) { + // @ts-expect-error size should exists on Collection + if (b.size === undefined) { + if (typeof a.cacheResult === 'function') { + a.cacheResult(); + } + } + else { + flipped = true; + var _ = a; + a = b; + b = _; + } + } + var allEqual = true; + var bSize = + // @ts-expect-error b is Range | Repeat | Collection as it may have been flipped, and __iterate is valid + b.__iterate(function (v, k) { + if (notAssociative + ? // @ts-expect-error has exists on Collection + !a.has(v) + : flipped + ? // @ts-expect-error type of `get` does not "catch" the version with `notSetValue` + !is(v, a.get(k, NOT_SET)) + : // @ts-expect-error type of `get` does not "catch" the version with `notSetValue` + !is(a.get(k, NOT_SET), v)) { + allEqual = false; + return false; + } }); - } + return (allEqual && + // @ts-expect-error size should exists on Collection + a.size === bSize); +} + +/** + * Contributes additional methods to a constructor + */ +function mixin(ctor, +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +methods) { + var keyCopier = function (key) { + // @ts-expect-error how to handle symbol ? + ctor.prototype[key] = methods[key]; + }; + Object.keys(methods).forEach(keyCopier); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + Object.getOwnPropertySymbols && + Object.getOwnPropertySymbols(methods).forEach(keyCopier); + return ctor; } -function trigger(note) { - if ((0, _util.intervalInRange)(note.interval, root)) { - instrument.play(note.interval, root); + +function toJS(value) { + if (!value || typeof value !== 'object') { + return value; } -} -function trigger_index(index) { - var interval = intervals[index]; - if (interval) { - instrument.play(interval, root); + if (!isCollection(value)) { + if (!isDataStructure(value)) { + return value; + } + value = Seq(value); } -} -function pause(note) { - _organ2.default.pause(note.interval); - var rounded = (0, _util.roundInterval)(note.interval); - notes.forEach(function (row) { - return row.forEach(function (note) { - return note.rounded === rounded && note.div.classList.remove("playing"); + if (isKeyed(value)) { + var result$1 = {}; + value.__iterate(function (v, k) { + result$1[k] = toJS(v); }); + return result$1; + } + var result = []; + value.__iterate(function (v) { + result.push(toJS(v)); }); + return result; } -function toggle(note) { - if (_organ2.default.isPlaying(note.rounded) || note.div.classList.contains("playing")) { - pause(note); - } else { - play(note); + +var Set = /*@__PURE__*/(function (SetCollection) { + function Set(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptySet() + : isSet(value) && !isOrdered(value) + ? value + : emptySet().withMutations(function (set) { + var iter = SetCollection(value); + assertNotInfinite(iter.size); + iter.forEach(function (v) { return set.add(v); }); + }); } -} -function add(i, j) { - var ii = i + Math.round(base_x); - var jj = j + Math.round(base_y); + if ( SetCollection ) Set.__proto__ = SetCollection; + Set.prototype = Object.create( SetCollection && SetCollection.prototype ); + Set.prototype.constructor = Set; - var scale = _scales.scales[scaleMode % _scales.scales.length]; + Set.of = function of (/*...values*/) { + return this(arguments); + }; - var _scale$get = scale.get(ii, jj, i, j, Math.round(base_x), Math.round(base_y)), - _scale$get2 = _slicedToArray(_scale$get, 2), - a = _scale$get2[0], - b = _scale$get2[1]; + Set.fromKeys = function fromKeys (value) { + return this(KeyedCollection(value).keySeq()); + }; - var div = document.createElement("div"); - var interval = a / b; - // const interval = root * Math.pow(2, ((b / a) % 1) + 1); - var add = 0; - var frac = void 0; - div.style.left = i * s + "px"; - div.style.top = j * s + "px"; + Set.intersect = function intersect (sets) { + sets = Collection(sets).toArray(); + return sets.length + ? SetPrototype.intersect.apply(Set(sets.pop()), sets) + : emptySet(); + }; - var note = { - interval: interval, - rounded: (0, _util.roundInterval)(interval, root), - div: div, - i: i, - j: j, - playing: false, - destroy: function destroy() { - div.parentNode && div.parentNode.removeChild(div); - }, - recolor: function recolor(numerator, denominator) { - var aa = a / numerator; - var bb = b / denominator; - if (aa < bb) { - add = -Math.log(bb / aa) / 3.5; - } else { - add = Math.log(aa / bb) / 6; - } - var a_inv = a * denominator; - var b_inv = b * numerator; - var ba_gcd = (0, _computeGcd2.default)(a_inv, b_inv); - var a_disp = a_inv / ba_gcd; - var b_disp = b_inv / ba_gcd; + Set.union = function union (sets) { + sets = Collection(sets).toArray(); + return sets.length + ? SetPrototype.union.apply(Set(sets.pop()), sets) + : emptySet(); + }; - frac = Math.log2(aa / bb) % 1; - var frac_orig = Math.log2(a / b) % 1; - if (frac < 0) { - frac += 1; - } - if (frac_orig < 0) { - frac += 1; - } - if (frac_orig === 0) { - div.style.fontWeight = "900"; - } else { - div.style.fontWeight = "500"; - } + Set.prototype.toString = function toString () { + return this.__toString('Set {', '}'); + }; - div.innerHTML = "
" + a_disp + "
/
" + b_disp + "
"; - if (note.playing) { - div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); - } else { - div.style.backgroundColor = (0, _color2.default)(frac, add + add_off, mul_off); - } + // @pragma Access - if (_organ2.default.isPlaying(interval)) { - div.classList.add("playing"); - } - } + Set.prototype.has = function has (value) { + return this._map.has(value); }; - note.recolor(1, 1); + // @pragma Modification - if (_util.browser.isDesktop) { - div.addEventListener("mousedown", function (event) { - if (event.button === 2) { - // rightclick - event.preventDefault(); - // notes.forEach((row) => row.forEach((note) => note.recolor(a, b))); - is_split = [a, b]; - toggle(note); - return; - } - div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); - dragging = true; - trigger(note); - }); - div.addEventListener("mouseenter", function () { - div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); - if (dragging) { - trigger(note); - } - }); - div.addEventListener("mouseleave", function () { - div.style.backgroundColor = (0, _color2.default)(frac, add + add_off, mul_off); - }); - div.addEventListener("contextmenu", function (event) { - if (!event.ctrlKey || !event.metaKey || !event.altKey) { - event.preventDefault(); - } - }); - } else { - div.addEventListener("touchstart", function (e) { - e.preventDefault(); - trigger(note); - // erasing = !note.playing; - dragging = true; - lastNote = note; - }); - } - grid.appendChild(div); - return note; -} + Set.prototype.add = function add (value) { + return updateSet(this, this._map.set(value, value)); + }; -function bind() { - if (_util.browser.isDesktop) { - document.addEventListener("mousedown", function (event) { - if (event.button !== 2) { - dragging = true; - } - }); - document.addEventListener("mouseup", function () { - dragging = false; - }); - } else { - document.addEventListener("touchstart", function (e) { - e.preventDefault(); - dragging = true; - }); - document.addEventListener("touchmove", function (e) { - e.preventDefault(); - var x = Math.floor(e.touches[0].pageX / s); - var y = Math.floor(e.touches[0].pageY / s); - if (!(x in notes) || !(y in notes[x])) return; - var note = notes[x][y]; - if (note !== lastNote) { - if (dragging) { - trigger(note); - } - lastNote = note; - } - }); - document.addEventListener("touchend", function () { - dragging = false; - }); - } - window.addEventListener("resize", build); - window.addEventListener("keydown", keydown, true); - _keys2.default.listen(trigger_index); - document.querySelector("#help .close").addEventListener("click", function () { - return document.querySelector("#help").classList.remove("visible"); - }); - document.querySelector("#help-button").addEventListener("click", function () { - return document.querySelector("#help").classList.toggle("visible"); - }); - if (_util.browser.isDesktop) { - grid.addEventListener("wheel", function (e) { - var new_base_x = Math.max(0, base_x + e.deltaX / 32); - var new_base_y = Math.max(0, base_y + e.deltaY / 32); - if (Math.round(base_x) !== Math.round(new_base_x) || Math.round(base_y) !== Math.round(new_base_y)) { - base_x = new_base_x; - base_y = new_base_y; - rebuild(); - } else { - base_x = new_base_x; - base_y = new_base_y; - } - }); - } -} + Set.prototype.remove = function remove (value) { + return updateSet(this, this._map.remove(value)); + }; -var isReset = false; -function keydown(e) { - var step = 1; - if (e.shiftKey) { - step += 4; - } - console.log(e.keyCode); - switch (e.keyCode) { - case 27: - // esc - PANIC - if (isReset) { - base_x = 0; - base_y = 0; - showMessage("reset!"); - } - _organ2.default.stop(); - _sampler2.default.stop(); - rebuild(); - isReset = true; - setTimeout(function () { - return isReset = false; - }, 500); - break; - case 37: - // left - if (e.altKey || e.ctrlKey || e.metaKey) return; - base_x = Math.max(0, base_x - step); - rebuild(); - break; - case 38: - // up - if (e.altKey || e.ctrlKey || e.metaKey) return; - base_y = Math.max(0, base_y - step); - rebuild(); - break; - case 39: - // right - if (e.altKey || e.ctrlKey || e.metaKey) return; - base_x += step; - rebuild(); - break; - case 40: - // down - if (e.altKey || e.ctrlKey || e.metaKey) return; - base_y += step; - rebuild(); - break; - case 220: - // \ - _midi2.default.enable(trigger_index); - break; - case 191: - // ? - document.querySelector("#help").classList.toggle("visible"); - break; - case 189: - // - - e.preventDefault(); - if (e.altKey || e.metaKey) { - root = (0, _util.clamp)(root - (e.shiftKey ? 10 : 1), 1, 200000); - _organ2.default.setRoot(root); - showMessage("Root: " + root + " hz"); - } else { - scaleMode = (0, _util.mod)(scaleMode - 1, _scales.scales.length); - rebuild(); - showMessage(_scales.scales[scaleMode].name); - } - break; - case 187: - // = - e.preventDefault(); - if (e.altKey || e.metaKey) { - root = (0, _util.clamp)(root + (e.shiftKey ? 10 : 1), 1, 200000); - _organ2.default.setRoot(root); - showMessage("Root: " + root + " hz"); - } else { - scaleMode = (0, _util.mod)(scaleMode + 1, _scales.scales.length); - rebuild(); - showMessage(_scales.scales[scaleMode].name); - } - break; - } -} + Set.prototype.clear = function clear () { + return updateSet(this, this._map.clear()); + }; -var messageTransition = void 0; -function showMessage(message) { - var el = document.getElementById("message"); - el.innerHTML = message; - el.style.opacity = 1; - if (messageTransition) { - messageTransition.cancel(); - } - messageTransition = _oktransition2.default.add({ - obj: el.style, - from: { opacity: 1 }, - to: { opacity: 0 }, - delay: 1500, - duration: 2000, - easing: _oktransition2.default.easing.circ_out - }); -} + // @pragma Composition -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { + Set.prototype.map = function map (mapper, context) { + var this$1$1 = this; -"use strict"; -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; + // keep track if the set is altered by the map function + var didChanges = false; -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + var newMap = updateSet( + this, + this._map.mapEntries(function (ref) { + var v = ref[1]; -/** - * StartAudioContext.js - * @author Yotam Mann - * @license http://opensource.org/licenses/MIT MIT License - * @copyright 2016 Yotam Mann - */ -(function (root, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { - module.exports = factory(); - } else { - root.StartAudioContext = factory(); - } -})(undefined, function () { - /** - * The StartAudioContext object - */ - var StartAudioContext = { - /** - * The audio context passed in by the user - * @type {AudioContext} - */ - context: null, - /** - * The TapListeners bound to the elements - * @type {Array} - * @private - */ - _tapListeners: [], - /** - * Callbacks to invoke when the audio context is started - * @type {Array} - * @private - */ - _onStarted: [] - }; + var mapped = mapper.call(context, v, v, this$1$1); - /** - * Set the context - * @param {AudioContext} ctx - * @returns {StartAudioContext} - */ - StartAudioContext.setContext = function (ctx) { - StartAudioContext.context = ctx; - return StartAudioContext; + if (mapped !== v) { + didChanges = true; + } + + return [mapped, mapped]; + }, context) + ); + + return didChanges ? newMap : this; }; - /** - * Add a tap listener to the audio context - * @param {Array|Element|String|jQuery} element - * @returns {StartAudioContext} - */ - StartAudioContext.on = function (element) { - if (Array.isArray(element) || NodeList && element instanceof NodeList) { - for (var i = 0; i < element.length; i++) { - StartAudioContext.on(element[i]); + Set.prototype.union = function union () { + var iters = [], len = arguments.length; + while ( len-- ) iters[ len ] = arguments[ len ]; + + iters = iters.filter(function (x) { return x.size !== 0; }); + if (iters.length === 0) { + return this; + } + if (this.size === 0 && !this.__ownerID && iters.length === 1) { + return this.constructor(iters[0]); + } + return this.withMutations(function (set) { + for (var ii = 0; ii < iters.length; ii++) { + if (typeof iters[ii] === 'string') { + set.add(iters[ii]); + } else { + SetCollection(iters[ii]).forEach(function (value) { return set.add(value); }); + } } - } else if (typeof element === "string") { - StartAudioContext.on(document.querySelectorAll(element)); - } else if (element.jquery && typeof element.toArray === "function") { - StartAudioContext.on(element.toArray()); - } else if (Element && element instanceof Element) { - //if it's an element, create a TapListener - var tap = new TapListener(element, onTap); - StartAudioContext._tapListeners.push(tap); + }); + }; + + Set.prototype.intersect = function intersect () { + var iters = [], len = arguments.length; + while ( len-- ) iters[ len ] = arguments[ len ]; + + if (iters.length === 0) { + return this; } - return StartAudioContext; + iters = iters.map(function (iter) { return SetCollection(iter); }); + var toRemove = []; + this.forEach(function (value) { + if (!iters.every(function (iter) { return iter.includes(value); })) { + toRemove.push(value); + } + }); + return this.withMutations(function (set) { + toRemove.forEach(function (value) { + set.remove(value); + }); + }); }; - /** - * Bind a callback to when the audio context is started. - * @param {Function} cb - * @return {StartAudioContext} - */ - StartAudioContext.onStarted = function (cb) { - //if it's already started, invoke the callback - if (StartAudioContext.isStarted()) { - cb(); - } else { - StartAudioContext._onStarted.push(cb); + Set.prototype.subtract = function subtract () { + var iters = [], len = arguments.length; + while ( len-- ) iters[ len ] = arguments[ len ]; + + if (iters.length === 0) { + return this; } - return StartAudioContext; + iters = iters.map(function (iter) { return SetCollection(iter); }); + var toRemove = []; + this.forEach(function (value) { + if (iters.some(function (iter) { return iter.includes(value); })) { + toRemove.push(value); + } + }); + return this.withMutations(function (set) { + toRemove.forEach(function (value) { + set.remove(value); + }); + }); + }; + + Set.prototype.sort = function sort (comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator)); }; - /** - * returns true if the context is started - * @return {Boolean} - */ - StartAudioContext.isStarted = function () { - return StartAudioContext.context !== null && StartAudioContext.context.state === "running"; + Set.prototype.sortBy = function sortBy (mapper, comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator, mapper)); }; - /** - * @class Listens for non-dragging tap ends on the given element - * @param {Element} element - * @internal - */ - var TapListener = function TapListener(element) { - this._dragged = false; - - this._element = element; + Set.prototype.wasAltered = function wasAltered () { + return this._map.wasAltered(); + }; - this._bindedMove = this._moved.bind(this); - this._bindedEnd = this._ended.bind(this); + Set.prototype.__iterate = function __iterate (fn, reverse) { + var this$1$1 = this; - element.addEventListener("touchmove", this._bindedMove); - element.addEventListener("touchend", this._bindedEnd); - element.addEventListener("mouseup", this._bindedEnd); + return this._map.__iterate(function (k) { return fn(k, k, this$1$1); }, reverse); }; - /** - * drag move event - */ - TapListener.prototype._moved = function (e) { - this._dragged = true; + Set.prototype.__iterator = function __iterator (type, reverse) { + return this._map.__iterator(type, reverse); }; - /** - * tap ended listener - */ - TapListener.prototype._ended = function (e) { - if (!this._dragged) { - onTap(); + Set.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; } - this._dragged = false; + var newMap = this._map.__ensureOwner(ownerID); + if (!ownerID) { + if (this.size === 0) { + return this.__empty(); + } + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return this.__make(newMap, ownerID); }; - /** - * remove all the bound events - */ - TapListener.prototype.dispose = function () { - this._element.removeEventListener("touchmove", this._bindedMove); - this._element.removeEventListener("touchend", this._bindedEnd); - this._element.removeEventListener("mouseup", this._bindedEnd); - this._bindedMove = null; - this._bindedEnd = null; - this._element = null; - }; + return Set; +}(SetCollection)); - /** - * Invoked the first time of the elements is tapped. - * Creates a silent oscillator when a non-dragging touchend - * event has been triggered. - */ - function onTap() { - //start the audio context with a silent oscillator - if (StartAudioContext.context && !StartAudioContext.isStarted()) { - var osc = StartAudioContext.context.createOscillator(); - var silent = StartAudioContext.context.createGain(); - silent.gain.value = 0; - osc.connect(silent); - silent.connect(StartAudioContext.context.destination); - var now = StartAudioContext.context.currentTime; - osc.start(now); - osc.stop(now + 0.5); +Set.isSet = isSet; + +var SetPrototype = Set.prototype; +SetPrototype[IS_SET_SYMBOL] = true; +SetPrototype[DELETE] = SetPrototype.remove; +SetPrototype.merge = SetPrototype.concat = SetPrototype.union; +SetPrototype.withMutations = withMutations; +SetPrototype.asImmutable = asImmutable; +SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable; +SetPrototype['@@transducer/step'] = function (result, arr) { + return result.add(arr); +}; +SetPrototype['@@transducer/result'] = function (obj) { + return obj.asImmutable(); +}; + +SetPrototype.__empty = emptySet; +SetPrototype.__make = makeSet; + +function updateSet(set, newMap) { + if (set.__ownerID) { + set.size = newMap.size; + set._map = newMap; + return set; + } + return newMap === set._map + ? set + : newMap.size === 0 + ? set.__empty() + : set.__make(newMap); +} + +function makeSet(map, ownerID) { + var set = Object.create(SetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; +} + +var EMPTY_SET; +function emptySet() { + return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); +} + +/** + * Returns a lazy seq of nums from start (inclusive) to end + * (exclusive), by step, where start defaults to 0, step to 1, and end to + * infinity. When start is equal to end, returns empty list. + */ +var Range = /*@__PURE__*/(function (IndexedSeq) { + function Range(start, end, step) { + if ( step === void 0 ) step = 1; + + if (!(this instanceof Range)) { + // eslint-disable-next-line no-constructor-return + return new Range(start, end, step); } + invariant(step !== 0, 'Cannot step a Range by 0'); + invariant( + start !== undefined, + 'You must define a start value when using Range' + ); + invariant( + end !== undefined, + 'You must define an end value when using Range' + ); - //dispose all the tap listeners - if (StartAudioContext._tapListeners) { - for (var i = 0; i < StartAudioContext._tapListeners.length; i++) { - StartAudioContext._tapListeners[i].dispose(); - } - StartAudioContext._tapListeners = null; + step = Math.abs(step); + if (end < start) { + step = -step; } - //the onstarted callbacks - if (StartAudioContext._onStarted) { - for (var j = 0; j < StartAudioContext._onStarted.length; j++) { - StartAudioContext._onStarted[j](); + this._start = start; + this._end = end; + this._step = step; + this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); + if (this.size === 0) { + if (EMPTY_RANGE) { + // eslint-disable-next-line no-constructor-return + return EMPTY_RANGE; } - StartAudioContext._onStarted = null; + // eslint-disable-next-line @typescript-eslint/no-this-alias + EMPTY_RANGE = this; } } - return StartAudioContext; -}); + if ( IndexedSeq ) Range.__proto__ = IndexedSeq; + Range.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); + Range.prototype.constructor = Range; -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { + Range.prototype.toString = function toString () { + return this.size === 0 + ? 'Range []' + : ("Range [ " + (this._start) + "..." + (this._end) + (this._step !== 1 ? ' by ' + this._step : '') + " ]"); + }; -"use strict"; + Range.prototype.get = function get (index, notSetValue) { + return this.has(index) + ? this._start + wrapIndex(this, index) * this._step + : notSetValue; + }; + Range.prototype.includes = function includes (searchValue) { + var possibleIndex = (searchValue - this._start) / this._step; + return ( + possibleIndex >= 0 && + possibleIndex < this.size && + possibleIndex === Math.floor(possibleIndex) + ); + }; -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + Range.prototype.slice = function slice (begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + begin = resolveBegin(begin, this.size); + end = resolveEnd(end, this.size); + if (end <= begin) { + return new Range(0, 0); + } + return new Range( + this.get(begin, this._end), + this.get(end, this._end), + this._step + ); + }; -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Arithmetic - * - * @param {*} start The number to start at - * @param {*} commonDifference The number to increment by each time - * - * Produces an arithmetic number sequence. Arithmetic number - * sequences are sequences which add or subtract a certain amount - * for each iteration. - */ -// Public API -exports.default = function (start, commonDifference) { - return (0, immutable_1.Seq)(generator(start, commonDifference)); -}; -// Generator -function generator() { - var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var commonDifference = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + Range.prototype.indexOf = function indexOf (searchValue) { + var offsetValue = searchValue - this._start; + if (offsetValue % this._step === 0) { + var index = offsetValue / this._step; + if (index >= 0 && index < this.size) { + return index; + } + } + return -1; + }; - case 2: - return _context.delegateYield(generator(current + commonDifference, commonDifference), "t0", 3); + Range.prototype.lastIndexOf = function lastIndexOf (searchValue) { + return this.indexOf(searchValue); + }; - case 3: - case "end": - return _context.stop(); + Range.prototype.__iterate = function __iterate (fn, reverse) { + var size = this.size; + var step = this._step; + var value = reverse ? this._start + (size - 1) * step : this._start; + var i = 0; + while (i !== size) { + if (fn(value, reverse ? size - ++i : i++, this) === false) { + break; } + value += reverse ? -step : step; } - }, _marked, this); -} -//# sourceMappingURL=arithmetic.js.map + return i; + }; -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { + Range.prototype.__iterator = function __iterator (type, reverse) { + var size = this.size; + var step = this._step; + var value = reverse ? this._start + (size - 1) * step : this._start; + var i = 0; + return new Iterator(function () { + if (i === size) { + return iteratorDone(); + } + var v = value; + value += reverse ? -step : step; + return iteratorValue(type, reverse ? size - ++i : i++, v); + }); + }; -"use strict"; + Range.prototype.equals = function equals (other) { + return other instanceof Range + ? this._start === other._start && + this._end === other._end && + this._step === other._step + : deepEqual(this, other); + }; + return Range; +}(IndexedSeq)); -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); +var EMPTY_RANGE; -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); /** - * Collatz + * Returns the value at the provided key path starting at the provided + * collection, or notSetValue if the key path is not defined. * - * @param {*} start The number to start at + * A functional alternative to `collection.getIn(keypath)` which will also + * work with plain Objects and Arrays. + */ +function getIn$1(collection, searchKeyPath, notSetValue) { + var keyPath = coerceKeyPath(searchKeyPath); + var i = 0; + while (i !== keyPath.length) { + // @ts-expect-error keyPath[i++] can not be undefined by design + collection = get(collection, keyPath[i++], NOT_SET); + if (collection === NOT_SET) { + return notSetValue; + } + } + return collection; +} + +function getIn(searchKeyPath, notSetValue) { + return getIn$1(this, searchKeyPath, notSetValue); +} + +/** + * Returns true if the key path is defined in the provided collection. * - * Produces the Collatz sequence for a given start number - * After (presumably) hitting 1, will loop infinitely on 1 -> 4 -> 2 -> 1 etc + * A functional alternative to `collection.hasIn(keypath)` which will also + * work with plain Objects and Arrays. */ -// Public API -exports.default = function (start) { - return (0, immutable_1.Seq)(generator(start)); -}; -// Generator -function generator(current) { - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; +function hasIn$1(collection, keyPath) { + return getIn$1(collection, keyPath, NOT_SET) !== NOT_SET; +} - case 2: - return _context.delegateYield(generator(current % 2 === 0 ? current / 2 : 3 * current + 1), "t0", 3); +function hasIn(searchKeyPath) { + return hasIn$1(this, searchKeyPath); +} - case 3: - case "end": - return _context.stop(); - } - } - }, _marked, this); +function toObject() { + assertNotInfinite(this.size); + var object = {}; + this.__iterate(function (v, k) { + object[k] = v; + }); + return object; } -//# sourceMappingURL=collatz.js.map -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { +Collection.Iterator = Iterator; -"use strict"; +mixin(Collection, { + // ### Conversion to other types + + toArray: function toArray() { + assertNotInfinite(this.size); + var array = new Array(this.size || 0); + var useTuples = isKeyed(this); + var i = 0; + this.__iterate(function (v, k) { + // Keyed collections produce an array of tuples. + array[i++] = useTuples ? [k, v] : v; + }); + return array; + }, + toIndexedSeq: function toIndexedSeq() { + return new ToIndexedSequence(this); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + toJS: function toJS$1() { + return toJS(this); + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Fibonacci - * - * Produces an Fibonacci number sequence. In Fibonacci number - * sequences, each number is the sum of the two preceding - * ones, starting from 0 and 1. - */ -// Public API -exports.default = function () { - return (0, immutable_1.Seq)(generator()); -}; -// Generator -function generator() { - var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var next = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + toKeyedSeq: function toKeyedSeq() { + return new ToKeyedSequence(this, true); + }, - case 2: - return _context.delegateYield(generator(next, current + next), "t0", 3); + toMap: function toMap() { + // Use Late Binding here to solve the circular dependency. + return Map(this.toKeyedSeq()); + }, - case 3: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=fibonacci.js.map + toObject: toObject, -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { + toOrderedMap: function toOrderedMap() { + // Use Late Binding here to solve the circular dependency. + return OrderedMap(this.toKeyedSeq()); + }, -"use strict"; + toOrderedSet: function toOrderedSet() { + // Use Late Binding here to solve the circular dependency. + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, + toSet: function toSet() { + // Use Late Binding here to solve the circular dependency. + return Set(isKeyed(this) ? this.valueSeq() : this); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + toSetSeq: function toSetSeq() { + return new ToSetSequence(this); + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Geometric - * - * @param {*} start The number to start at - * @param {*} commonRatio The number to multiply by each time - * - * Produces a geometric number sequence. Geometric number - * sequences are sequences which multiply or divide by a certain - * amount for each iteration. - */ -// Public API -exports.default = function (start, commonRatio) { - return (0, immutable_1.Seq)(generator(start, commonRatio)); -}; -// Generator -function generator() { - var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var commonRatio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + toSeq: function toSeq() { + return isIndexed(this) + ? this.toIndexedSeq() + : isKeyed(this) + ? this.toKeyedSeq() + : this.toSetSeq(); + }, + + toStack: function toStack() { + // Use Late Binding here to solve the circular dependency. + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, + + toList: function toList() { + // Use Late Binding here to solve the circular dependency. + return List(isKeyed(this) ? this.valueSeq() : this); + }, + + // ### Common JavaScript methods and properties + + toString: function toString() { + return '[Collection]'; + }, + + __toString: function __toString(head, tail) { + if (this.size === 0) { + return head + tail; + } + return ( + head + + ' ' + + this.toSeq().map(this.__toStringMapper).join(', ') + + ' ' + + tail + ); + }, - case 2: - return _context.delegateYield(generator(current * commonRatio, commonRatio), "t0", 3); + // ### ES6 Collection methods (ES6 Array and Map) - case 3: - case "end": - return _context.stop(); + concat: function concat() { + var values = [], len = arguments.length; + while ( len-- ) values[ len ] = arguments[ len ]; + + return reify(this, concatFactory(this, values)); + }, + + includes: function includes(searchValue) { + return this.some(function (value) { return is(value, searchValue); }); + }, + + entries: function entries() { + return this.__iterator(ITERATE_ENTRIES); + }, + + every: function every(predicate, context) { + assertNotInfinite(this.size); + var returnValue = true; + this.__iterate(function (v, k, c) { + if (!predicate.call(context, v, k, c)) { + returnValue = false; + return false; } - } - }, _marked, this); -} -//# sourceMappingURL=geometric.js.map + }); + return returnValue; + }, -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { + filter: function filter(predicate, context) { + return reify(this, filterFactory(this, predicate, context, true)); + }, -"use strict"; + partition: function partition(predicate, context) { + return partitionFactory(this, predicate, context); + }, + find: function find(predicate, context, notSetValue) { + var entry = this.findEntry(predicate, context); + return entry ? entry[1] : notSetValue; + }, -var __importDefault = undefined && undefined.__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NthPower = exports.Twin = exports.Triangle = exports.Prime = exports.Power = exports.Geometric = exports.Fibonacci = exports.Collatz = exports.Arithmetic = void 0; -var arithmetic_1 = __webpack_require__(15); -Object.defineProperty(exports, "Arithmetic", { enumerable: true, get: function get() { - return __importDefault(arithmetic_1).default; - } }); -var collatz_1 = __webpack_require__(16); -Object.defineProperty(exports, "Collatz", { enumerable: true, get: function get() { - return __importDefault(collatz_1).default; - } }); -var fibonacci_1 = __webpack_require__(17); -Object.defineProperty(exports, "Fibonacci", { enumerable: true, get: function get() { - return __importDefault(fibonacci_1).default; - } }); -var geometric_1 = __webpack_require__(18); -Object.defineProperty(exports, "Geometric", { enumerable: true, get: function get() { - return __importDefault(geometric_1).default; - } }); -var power_1 = __webpack_require__(21); -Object.defineProperty(exports, "Power", { enumerable: true, get: function get() { - return __importDefault(power_1).default; - } }); -var prime_1 = __webpack_require__(22); -Object.defineProperty(exports, "Prime", { enumerable: true, get: function get() { - return __importDefault(prime_1).default; - } }); -var triangle_1 = __webpack_require__(23); -Object.defineProperty(exports, "Triangle", { enumerable: true, get: function get() { - return __importDefault(triangle_1).default; - } }); -var twin_1 = __webpack_require__(24); -Object.defineProperty(exports, "Twin", { enumerable: true, get: function get() { - return __importDefault(twin_1).default; - } }); -var nthpower_1 = __webpack_require__(20); -Object.defineProperty(exports, "NthPower", { enumerable: true, get: function get() { - return __importDefault(nthpower_1).default; - } }); -//# sourceMappingURL=index.js.map + forEach: function forEach(sideEffect, context) { + assertNotInfinite(this.size); + return this.__iterate(context ? sideEffect.bind(context) : sideEffect); + }, -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { + join: function join(separator) { + assertNotInfinite(this.size); + separator = separator !== undefined ? '' + separator : ','; + var joined = ''; + var isFirst = true; + this.__iterate(function (v) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + isFirst ? (isFirst = false) : (joined += separator); + joined += v !== null && v !== undefined ? v.toString() : ''; + }); + return joined; + }, -"use strict"; + keys: function keys() { + return this.__iterator(ITERATE_KEYS); + }, + map: function map(mapper, context) { + return reify(this, mapFactory(this, mapper, context)); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + reduce: function reduce$1(reducer, initialReduction, context) { + return reduce( + this, + reducer, + initialReduction, + context, + arguments.length < 2, + false + ); + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Power - * - * Generate all the nth powers - e.g. all squares, all cubes etc - */ -// Public API -exports.default = function (n) { - return (0, immutable_1.Seq)(generator(n)); -}; -// Generator -function generator(n) { - var current = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - var x; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + reduceRight: function reduceRight(reducer, initialReduction, context) { + return reduce( + this, + reducer, + initialReduction, + context, + arguments.length < 2, + true + ); + }, - case 2: - x = Math.pow(Math.pow(current, 1 / n) + 1, n); - return _context.delegateYield(generator(n, x), "t0", 4); + reverse: function reverse() { + return reify(this, reverseFactory(this, true)); + }, - case 4: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=nthpower.js.map + slice: function slice(begin, end) { + return reify(this, sliceFactory(this, begin, end, true)); + }, -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { + some: function some(predicate, context) { + assertNotInfinite(this.size); + var returnValue = false; + this.__iterate(function (v, k, c) { + if (predicate.call(context, v, k, c)) { + returnValue = true; + return false; + } + }); + return returnValue; + }, -"use strict"; + sort: function sort(comparator) { + return reify(this, sortFactory(this, comparator)); + }, + values: function values() { + return this.__iterator(ITERATE_VALUES); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + // ### More sequential methods -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Power - * - * Given a number, find all it's positive powers. - * e.g. for 2 it would be 2, 4, 8, 16.... - * for 3 it would be 3, 9, 27, 81.... - */ -// Public API -exports.default = function (start) { - return (0, immutable_1.Seq)(generator(start)); -}; -// Generator -function generator(current, initial) { - var x; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + butLast: function butLast() { + return this.slice(0, -1); + }, - case 2: - x = initial || current; - return _context.delegateYield(generator(current * x, x), "t0", 4); + isEmpty: function isEmpty() { + return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; }); + }, - case 4: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=power.js.map + count: function count(predicate, context) { + return ensureSize( + predicate ? this.toSeq().filter(predicate, context) : this + ); + }, -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { + countBy: function countBy(grouper, context) { + return countByFactory(this, grouper, context); + }, -"use strict"; + equals: function equals(other) { + return deepEqual(this, other); + }, + entrySeq: function entrySeq() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var collection = this; + if (collection._cache) { + // We cache as an entries array, so we can just return the cache! + return new ArraySeq(collection._cache); + } + var entriesSequence = collection.toSeq().map(entryMapper).toIndexedSeq(); + entriesSequence.fromEntrySeq = function () { return collection.toSeq(); }; + return entriesSequence; + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + filterNot: function filterNot(predicate, context) { + return this.filter(not(predicate), context); + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Prime - * - * List of all primes starting from 2 - */ -// Check if any of the primes found so far are factors of n. If not, then n is prime, so return that, else repeat for next candidate -var findNextPrime = function findNextPrime(n, knownPrimes) { - var f = knownPrimes.find(function (p) { - return n % p === 0; + findEntry: function findEntry(predicate, context, notSetValue) { + var found = notSetValue; + this.__iterate(function (v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } }); - return f ? findNextPrime(nextCandidate(n), knownPrimes) : n; -}; -// Reduce computation time by only checking odd numbers - and therefore incrementing by 2 each time -// Only exception is the very first increment, because the first prime is 2, the only even prime -var nextCandidate = function nextCandidate(n) { - return n + (n === 2 ? 1 : 2); -}; -// Public API -exports.default = function () { - return (0, immutable_1.Seq)(generator(2, (0, immutable_1.List)([2]))); -}; -// Generator -function generator(current) { - var prev = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, immutable_1.List)(); - var knownPrimes, nextPrime; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; - - case 2: - knownPrimes = prev.push(current); - nextPrime = findNextPrime(nextCandidate(current), knownPrimes); - return _context.delegateYield(generator(nextPrime, knownPrimes), "t0", 5); + return found; + }, - case 5: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=prime.js.map + findKey: function findKey(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { + findLast: function findLast(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, -"use strict"; + findLastEntry: function findLastEntry(predicate, context, notSetValue) { + return this.toKeyedSeq() + .reverse() + .findEntry(predicate, context, notSetValue); + }, + findLastKey: function findLastKey(predicate, context) { + return this.toKeyedSeq().reverse().findKey(predicate, context); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + first: function first(notSetValue) { + return this.find(returnTrue, null, notSetValue); + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Triangle - * - * The triangle number sequence - 1, 3, 6, 10, 15, 21 - * = 1, (1 + 2), (1 + 2 + 3) etc - */ -// Public API -exports.default = function () { - return (0, immutable_1.Seq)(generator(1)); -}; -// Generator -// The general formula for the nth triangle number is n*(n + 1)/2 -// If the current number is x, then x = n*(n + 1)/2 -// and so with a bit of algebra and the quadratic formula (only taking the positive answer) -// n = (1 + 8*x)^(1/2)/2 -// So we can work out from the current value that it's the nth value, and then just -// add n + 1 to get the next term -// e.g. if current term is 10, then the above formula tells us it's the 4th term, -// so we add 5 to get the 5th term = 15 -function generator(current) { - var n; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return current; + flatMap: function flatMap(mapper, context) { + return reify(this, flatMapFactory(this, mapper, context)); + }, - case 2: - n = (Math.sqrt(1 + 8 * current) - 1) / 2; - return _context.delegateYield(generator(current + n + 1), "t0", 4); + flatten: function flatten(depth) { + return reify(this, flattenFactory(this, depth, true)); + }, - case 4: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=triangle.js.map + fromEntrySeq: function fromEntrySeq() { + return new FromEntriesSequence(this); + }, -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { + get: function get(searchKey, notSetValue) { + return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue); + }, -"use strict"; + getIn: getIn, + groupBy: function groupBy(grouper, context) { + return groupByFactory(this, grouper, context); + }, -var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + has: function has(searchKey) { + return this.get(searchKey, NOT_SET) !== NOT_SET; + }, -Object.defineProperty(exports, "__esModule", { value: true }); -var immutable_1 = __webpack_require__(0); -/** - * Twin - * - * Given two sequences, interweave them, alternating terms - */ -// Public API -exports.default = function (a, b) { - return (0, immutable_1.Seq)(generator(a, b)); -}; -// Generator -function generator(a, b) { - var counter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - return regeneratorRuntime.wrap(function generator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return counter % 2 === 0 ? a.first() : b.first(); + hasIn: hasIn, - case 2: - return _context.delegateYield(generator(a, b, counter + 1), "t0", 3); + isSubset: function isSubset(iter) { + iter = typeof iter.includes === 'function' ? iter : Collection(iter); + return this.every(function (value) { return iter.includes(value); }); + }, - case 3: - case "end": - return _context.stop(); - } - } - }, _marked, this); -} -//# sourceMappingURL=twin.js.map + isSuperset: function isSuperset(iter) { + iter = typeof iter.isSubset === 'function' ? iter : Collection(iter); + return iter.isSubset(this); + }, -/***/ }), -/* 25 */ -/***/ (function(module, exports) { + keyOf: function keyOf(searchValue) { + return this.findKey(function (value) { return is(value, searchValue); }); + }, -// shim for using process in browser -var process = module.exports = {}; + keySeq: function keySeq() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + last: function last(notSetValue) { + return this.toSeq().reverse().first(notSetValue); + }, -var cachedSetTimeout; -var cachedClearTimeout; + lastKeyOf: function lastKeyOf(searchValue) { + return this.toKeyedSeq().reverse().keyOf(searchValue); + }, -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + max: function max(comparator) { + return maxFactory(this, comparator); + }, + maxBy: function maxBy(mapper, comparator) { + return maxFactory(this, comparator, mapper); + }, -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + min: function min(comparator) { + return maxFactory( + this, + comparator ? neg(comparator) : defaultNegComparator + ); + }, + minBy: function minBy(mapper, comparator) { + return maxFactory( + this, + comparator ? neg(comparator) : defaultNegComparator, + mapper + ); + }, + rest: function rest() { + return this.slice(1); + }, -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + skip: function skip(amount) { + return amount === 0 ? this : this.slice(Math.max(0, amount)); + }, -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} + skipLast: function skipLast(amount) { + return amount === 0 ? this : this.slice(0, -Math.max(0, amount)); + }, -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + skipWhile: function skipWhile(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, true)); + }, - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} + skipUntil: function skipUntil(predicate, context) { + return this.skipWhile(not(predicate), context); + }, -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; + sortBy: function sortBy(mapper, comparator) { + return reify(this, sortFactory(this, comparator, mapper)); + }, -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; + take: function take(amount) { + return this.slice(0, Math.max(0, amount)); + }, -function noop() {} + takeLast: function takeLast(amount) { + return this.slice(-Math.max(0, amount)); + }, -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; + takeWhile: function takeWhile(predicate, context) { + return reify(this, takeWhileFactory(this, predicate, context)); + }, -process.listeners = function (name) { return [] } + takeUntil: function takeUntil(predicate, context) { + return this.takeWhile(not(predicate), context); + }, -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + update: function update(fn) { + return fn(this); + }, -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + valueSeq: function valueSeq() { + return this.toIndexedSeq(); + }, + // ### Hashable Object -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { + hashCode: function hashCode() { + return this.__hash || (this.__hash = hashCollection(this)); + }, -"use strict"; -/** -* -* VALIDATE: function -* -* -* DESCRIPTION: -* - Validates if a value is a function. -* -* -* NOTES: -* [1] -* -* -* TODO: -* [1] -* -* -* LICENSE: -* MIT -* -* Copyright (c) 2014. Athan Reines. -* -* -* AUTHOR: -* Athan Reines. kgryte@gmail.com. 2014. -* -*/ + // ### Internal + // abstract __iterate(fn, reverse) + // abstract __iterator(type, reverse) +}); -/** -* FUNCTION: isFunction( value ) -* Validates if a value is a function. -* -* @param {*} value - value to be validated -* @returns {Boolean} boolean indicating whether value is a function -*/ -function isFunction( value ) { - return ( typeof value === 'function' ); -} // end FUNCTION isFunction() +var CollectionPrototype = Collection.prototype; +CollectionPrototype[IS_COLLECTION_SYMBOL] = true; +CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values; +CollectionPrototype.toJSON = CollectionPrototype.toArray; +CollectionPrototype.__toStringMapper = quoteString; +CollectionPrototype.inspect = CollectionPrototype.toSource = function () { + return this.toString(); +}; +CollectionPrototype.chain = CollectionPrototype.flatMap; +CollectionPrototype.contains = CollectionPrototype.includes; +mixin(KeyedCollection, { + // ### More sequential methods -// EXPORTS // + flip: function flip() { + return reify(this, flipFactory(this)); + }, -module.exports = isFunction; + mapEntries: function mapEntries(mapper, context) { + var this$1$1 = this; + var iterations = 0; + return reify( + this, + this.toSeq() + .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1$1); }) + .fromEntrySeq() + ); + }, -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { + mapKeys: function mapKeys(mapper, context) { + var this$1$1 = this; -"use strict"; -/** -* -* VALIDATE: integer-array -* -* -* DESCRIPTION: -* - Validates if a value is an integer array. -* -* -* NOTES: -* [1] -* -* -* TODO: -* [1] -* -* -* LICENSE: -* MIT -* -* Copyright (c) 2015. Athan Reines. -* -* -* AUTHOR: -* Athan Reines. kgryte@gmail.com. 2015. -* -*/ + return reify( + this, + this.toSeq() + .flip() + .map(function (k, v) { return mapper.call(context, k, v, this$1$1); }) + .flip() + ); + }, +}); +var KeyedCollectionPrototype = KeyedCollection.prototype; +KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true; +KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries; +KeyedCollectionPrototype.toJSON = toObject; +KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); }; +mixin(IndexedCollection, { + // ### Conversion to other types -// MODULES // + toKeyedSeq: function toKeyedSeq() { + return new ToKeyedSequence(this, false); + }, -var isArray = __webpack_require__( 3 ), - isInteger = __webpack_require__( 28 ); + // ### ES6 Collection methods (ES6 Array and Map) + filter: function filter(predicate, context) { + return reify(this, filterFactory(this, predicate, context, false)); + }, -// IS INTEGER ARRAY // + findIndex: function findIndex(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry ? entry[0] : -1; + }, -/** -* FUNCTION: isIntegerArray( value ) -* Validates if a value is an integer array. -* -* @param {*} value - value to be validated -* @returns {Boolean} boolean indicating if a value is an integer array -*/ -function isIntegerArray( value ) { - var len; - if ( !isArray( value ) ) { - return false; - } - len = value.length; - if ( !len ) { - return false; - } - for ( var i = 0; i < len; i++ ) { - if ( !isInteger( value[i] ) ) { - return false; - } - } - return true; -} // end FUNCTION isIntegerArray() + indexOf: function indexOf(searchValue) { + var key = this.keyOf(searchValue); + return key === undefined ? -1 : key; + }, + lastIndexOf: function lastIndexOf(searchValue) { + var key = this.lastKeyOf(searchValue); + return key === undefined ? -1 : key; + }, -// EXPORTS // + reverse: function reverse() { + return reify(this, reverseFactory(this, false)); + }, -module.exports = isIntegerArray; + slice: function slice(begin, end) { + return reify(this, sliceFactory(this, begin, end, false)); + }, + splice: function splice(index, removeNum /*, ...values*/) { + var numArgs = arguments.length; + removeNum = Math.max(removeNum || 0, 0); + if (numArgs === 0 || (numArgs === 2 && !removeNum)) { + return this; + } + // If index is negative, it should resolve relative to the size of the + // collection. However size may be expensive to compute if not cached, so + // only call count() if the number is in fact negative. + index = resolveBegin(index, index < 0 ? this.count() : this.size); + var spliced = this.slice(0, index); + return reify( + this, + numArgs === 1 + ? spliced + : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) + ); + }, -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { + // ### More collection methods -"use strict"; -/** -* -* VALIDATE: integer -* -* -* DESCRIPTION: -* - Validates if a value is an integer. -* -* -* NOTES: -* [1] -* -* -* TODO: -* [1] -* -* -* LICENSE: -* MIT -* -* Copyright (c) 2014. Athan Reines. -* -* -* AUTHOR: -* Athan Reines. kgryte@gmail.com. 2014. -* -*/ + findLastIndex: function findLastIndex(predicate, context) { + var entry = this.findLastEntry(predicate, context); + return entry ? entry[0] : -1; + }, + + first: function first(notSetValue) { + return this.get(0, notSetValue); + }, + flatten: function flatten(depth) { + return reify(this, flattenFactory(this, depth, false)); + }, + get: function get(index, notSetValue) { + index = wrapIndex(this, index); + return index < 0 || + this.size === Infinity || + (this.size !== undefined && index > this.size) + ? notSetValue + : this.find(function (_, key) { return key === index; }, undefined, notSetValue); + }, -// MODULES // + has: function has(index) { + index = wrapIndex(this, index); + return ( + index >= 0 && + (this.size !== undefined + ? this.size === Infinity || index < this.size + : this.indexOf(index) !== -1) + ); + }, -var isNumber = __webpack_require__( 29 ); + interpose: function interpose(separator) { + return reify(this, interposeFactory(this, separator)); + }, + interleave: function interleave(/*...collections*/) { + var collections = [this].concat(arrCopy(arguments)); + var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections); + var interleaved = zipped.flatten(true); + if (zipped.size) { + interleaved.size = zipped.size * collections.length; + } + return reify(this, interleaved); + }, -// ISINTEGER // + keySeq: function keySeq() { + return Range(0, this.size); + }, -/** -* FUNCTION: isInteger( value ) -* Validates if a value is an integer. -* -* @param {Number} value - value to be validated -* @returns {Boolean} boolean indicating whether value is an integer -*/ -function isInteger( value ) { - return isNumber( value ) && value%1 === 0; -} // end FUNCTION isInteger() + last: function last(notSetValue) { + return this.get(-1, notSetValue); + }, + skipWhile: function skipWhile(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, false)); + }, -// EXPORTS // + zip: function zip(/*, ...collections */) { + var collections = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, collections)); + }, -module.exports = isInteger; + zipAll: function zipAll(/*, ...collections */) { + var collections = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, collections, true)); + }, + zipWith: function zipWith(zipper /*, ...collections */) { + var collections = arrCopy(arguments); + collections[0] = this; + return reify(this, zipWithFactory(this, zipper, collections)); + }, +}); -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { +var IndexedCollectionPrototype = IndexedCollection.prototype; +IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true; +IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true; -"use strict"; -/** -* -* VALIDATE: number -* -* -* DESCRIPTION: -* - Validates if a value is a number. -* -* -* NOTES: -* [1] -* -* -* TODO: -* [1] -* -* -* LICENSE: -* MIT -* -* Copyright (c) 2014. Athan Reines. -* -* -* AUTHOR: -* Athan Reines. kgryte@gmail.com. 2014. -* -*/ +mixin(SetCollection, { + // ### ES6 Collection methods (ES6 Array and Map) + get: function get(value, notSetValue) { + return this.has(value) ? value : notSetValue; + }, + + includes: function includes(value) { + return this.has(value); + }, + // ### More sequential methods -/** -* FUNCTION: isNumber( value ) -* Validates if a value is a number. -* -* @param {*} value - value to be validated -* @returns {Boolean} boolean indicating whether value is a number -*/ -function isNumber( value ) { - return ( typeof value === 'number' || Object.prototype.toString.call( value ) === '[object Number]' ) && value.valueOf() === value.valueOf(); -} // end FUNCTION isNumber() + keySeq: function keySeq() { + return this.valueSeq(); + }, +}); +var SetCollectionPrototype = SetCollection.prototype; +SetCollectionPrototype.has = CollectionPrototype.includes; +SetCollectionPrototype.contains = SetCollectionPrototype.includes; +SetCollectionPrototype.keys = SetCollectionPrototype.values; -// EXPORTS // +// Mixin subclasses -module.exports = isNumber; +mixin(KeyedSeq, KeyedCollectionPrototype); +mixin(IndexedSeq, IndexedCollectionPrototype); +mixin(SetSeq, SetCollectionPrototype); +// #pragma Helper functions -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { +function reduce(collection, reducer, reduction, context, useFirst, reverse) { + assertNotInfinite(collection.size); + collection.__iterate(function (v, k, c) { + if (useFirst) { + useFirst = false; + reduction = v; + } else { + reduction = reducer.call(context, reduction, v, k, c); + } + }, reverse); + return reduction; +} -"use strict"; -/* WEBPACK VAR INJECTION */(function(process, global) {/** - * WEBMIDI.js v3.1.12 - * A JavaScript library to kickstart your MIDI projects - * https://webmidijs.org - * Build generated on November 22nd, 2024. - * - * © Copyright 2015-2024, Jean-Philippe Côté. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +function keyMapper(v, k) { + return k; +} -Object.defineProperty(exports,"__esModule",{value:!0});class EventEmitter{constructor(e=!1){this.eventMap={},this.eventsSuspended=1==e}addListener(e,t,n={}){if("string"==typeof e&&e.length<1||e instanceof String&&e.length<1||"string"!=typeof e&&!(e instanceof String)&&e!==EventEmitter.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if("function"!=typeof t)throw new TypeError("The callback must be a function.");const r=new Listener(e,this,t,n);return this.eventMap[e]||(this.eventMap[e]=[]),n.prepend?this.eventMap[e].unshift(r):this.eventMap[e].push(r),r}addOneTimeListener(e,t,n={}){n.remaining=1,this.addListener(e,t,n)}static get ANY_EVENT(){return Symbol.for("Any event")}hasListener(e,t){if(void 0===e)return!!(this.eventMap[EventEmitter.ANY_EVENT]&&this.eventMap[EventEmitter.ANY_EVENT].length>0)||Object.entries(this.eventMap).some(([,e])=>e.length>0);if(this.eventMap[e]&&this.eventMap[e].length>0){if(t instanceof Listener){return this.eventMap[e].filter(e=>e===t).length>0}if("function"==typeof t){return this.eventMap[e].filter(e=>e.callback===t).length>0}return null==t}return!1}get eventNames(){return Object.keys(this.eventMap)}getListeners(e){return this.eventMap[e]||[]}suspendEvent(e){this.getListeners(e).forEach(e=>{e.suspended=!0})}unsuspendEvent(e){this.getListeners(e).forEach(e=>{e.suspended=!1})}getListenerCount(e){return this.getListeners(e).length}emit(e,...t){if("string"!=typeof e&&!(e instanceof String))throw new TypeError("The 'event' parameter must be a string.");if(this.eventsSuspended)return;let n=[],r=this.eventMap[EventEmitter.ANY_EVENT]||[];return this.eventMap[e]&&(r=r.concat(this.eventMap[e])),r.forEach(e=>{if(e.suspended)return;let r=[...t];Array.isArray(e.arguments)&&(r=r.concat(e.arguments)),e.remaining>0&&(n.push(e.callback.apply(e.context,r)),e.count++),--e.remaining<1&&e.remove()}),n}removeListener(e,t,n={}){if(void 0===e)return void(this.eventMap={});if(!this.eventMap[e])return;let r=this.eventMap[e].filter(e=>t&&e.callback!==t||n.remaining&&n.remaining!==e.remaining||n.context&&n.context!==e.context);r.length?this.eventMap[e]=r:delete this.eventMap[e]}async waitFor(e,t={}){return t.duration=parseInt(t.duration),(isNaN(t.duration)||t.duration<=0)&&(t.duration=1/0),new Promise((n,r)=>{let i,s=this.addListener(e,()=>{clearTimeout(i),n()},{remaining:1});t.duration!==1/0&&(i=setTimeout(()=>{s.remove(),r("The duration expired before the event was emitted.")},t.duration))})}get eventCount(){return Object.keys(this.eventMap).length}}class Listener{constructor(e,t,n,r={}){if("string"!=typeof e&&!(e instanceof String)&&e!==EventEmitter.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(!t)throw new ReferenceError("The 'target' parameter is mandatory.");if("function"!=typeof n)throw new TypeError("The 'callback' must be a function.");void 0===r.arguments||Array.isArray(r.arguments)||(r.arguments=[r.arguments]),(r=Object.assign({context:t,remaining:1/0,arguments:void 0,duration:1/0},r)).duration!==1/0&&setTimeout(()=>this.remove(),r.duration),this.arguments=r.arguments,this.callback=n,this.context=r.context,this.count=0,this.event=e,this.remaining=parseInt(r.remaining)>=1?parseInt(r.remaining):1/0,this.suspended=!1,this.target=t}remove(){this.target.removeListener(this.event,this.callback,{context:this.context,remaining:this.remaining})}} -/** - * The `Enumerations` class contains enumerations and arrays of elements used throughout the - * library. All its properties are static and should be referenced using the class name. For - * example: `Enumerations.CHANNEL_MESSAGES`. - * - * @license Apache-2.0 - * @since 3.0.0 - */class Enumerations{static get MIDI_CHANNEL_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MESSAGES enum has been deprecated. Use the Enumerations.CHANNEL_MESSAGES enum instead."),Enumerations.CHANNEL_MESSAGES}static get CHANNEL_MESSAGES(){return{noteoff:8,noteon:9,keyaftertouch:10,controlchange:11,programchange:12,channelaftertouch:13,pitchbend:14}}static get CHANNEL_NUMBERS(){return[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]}static get MIDI_CHANNEL_NUMBERS(){return this.validation&&console.warn("The MIDI_CHANNEL_NUMBERS array has been deprecated. Use the Enumerations.CHANNEL_NUMBERS array instead."),[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]}static get CHANNEL_MODE_MESSAGES(){return{allsoundoff:120,resetallcontrollers:121,localcontrol:122,allnotesoff:123,omnimodeoff:124,omnimodeon:125,monomodeon:126,polymodeon:127}}static get MIDI_CHANNEL_MODE_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MODE_MESSAGES enum has been deprecated. Use the Enumerations.CHANNEL_MODE_MESSAGES enum instead."),Enumerations.CHANNEL_MODE_MESSAGES}static get MIDI_CONTROL_CHANGE_MESSAGES(){return this.validation&&console.warn("The MIDI_CONTROL_CHANGE_MESSAGES enum has been deprecated. Use the Enumerations.CONTROL_CHANGE_MESSAGES array instead."),{bankselectcoarse:0,modulationwheelcoarse:1,breathcontrollercoarse:2,controller3:3,footcontrollercoarse:4,portamentotimecoarse:5,dataentrycoarse:6,volumecoarse:7,balancecoarse:8,controller9:9,pancoarse:10,expressioncoarse:11,effectcontrol1coarse:12,effectcontrol2coarse:13,controller14:14,controller15:15,generalpurposeslider1:16,generalpurposeslider2:17,generalpurposeslider3:18,generalpurposeslider4:19,controller20:20,controller21:21,controller22:22,controller23:23,controller24:24,controller25:25,controller26:26,controller27:27,controller28:28,controller29:29,controller30:30,controller31:31,bankselectfine:32,modulationwheelfine:33,breathcontrollerfine:34,controller35:35,footcontrollerfine:36,portamentotimefine:37,dataentryfine:38,volumefine:39,balancefine:40,controller41:41,panfine:42,expressionfine:43,effectcontrol1fine:44,effectcontrol2fine:45,controller46:46,controller47:47,controller48:48,controller49:49,controller50:50,controller51:51,controller52:52,controller53:53,controller54:54,controller55:55,controller56:56,controller57:57,controller58:58,controller59:59,controller60:60,controller61:61,controller62:62,controller63:63,holdpedal:64,portamento:65,sustenutopedal:66,softpedal:67,legatopedal:68,hold2pedal:69,soundvariation:70,resonance:71,soundreleasetime:72,soundattacktime:73,brightness:74,soundcontrol6:75,soundcontrol7:76,soundcontrol8:77,soundcontrol9:78,soundcontrol10:79,generalpurposebutton1:80,generalpurposebutton2:81,generalpurposebutton3:82,generalpurposebutton4:83,controller84:84,controller85:85,controller86:86,controller87:87,controller88:88,controller89:89,controller90:90,reverblevel:91,tremololevel:92,choruslevel:93,celestelevel:94,phaserlevel:95,databuttonincrement:96,databuttondecrement:97,nonregisteredparametercoarse:98,nonregisteredparameterfine:99,registeredparametercoarse:100,registeredparameterfine:101,controller102:102,controller103:103,controller104:104,controller105:105,controller106:106,controller107:107,controller108:108,controller109:109,controller110:110,controller111:111,controller112:112,controller113:113,controller114:114,controller115:115,controller116:116,controller117:117,controller118:118,controller119:119,allsoundoff:120,resetallcontrollers:121,localcontrol:122,allnotesoff:123,omnimodeoff:124,omnimodeon:125,monomodeon:126,polymodeon:127}}static get CONTROL_CHANGE_MESSAGES(){return[{number:0,name:"bankselectcoarse",description:"Bank Select (Coarse)",position:"msb"},{number:1,name:"modulationwheelcoarse",description:"Modulation Wheel (Coarse)",position:"msb"},{number:2,name:"breathcontrollercoarse",description:"Breath Controller (Coarse)",position:"msb"},{number:3,name:"controller3",description:"Undefined",position:"msb"},{number:4,name:"footcontrollercoarse",description:"Foot Controller (Coarse)",position:"msb"},{number:5,name:"portamentotimecoarse",description:"Portamento Time (Coarse)",position:"msb"},{number:6,name:"dataentrycoarse",description:"Data Entry (Coarse)",position:"msb"},{number:7,name:"volumecoarse",description:"Channel Volume (Coarse)",position:"msb"},{number:8,name:"balancecoarse",description:"Balance (Coarse)",position:"msb"},{number:9,name:"controller9",description:"Controller 9 (Coarse)",position:"msb"},{number:10,name:"pancoarse",description:"Pan (Coarse)",position:"msb"},{number:11,name:"expressioncoarse",description:"Expression Controller (Coarse)",position:"msb"},{number:12,name:"effectcontrol1coarse",description:"Effect Control 1 (Coarse)",position:"msb"},{number:13,name:"effectcontrol2coarse",description:"Effect Control 2 (Coarse)",position:"msb"},{number:14,name:"controller14",description:"Undefined",position:"msb"},{number:15,name:"controller15",description:"Undefined",position:"msb"},{number:16,name:"generalpurposecontroller1",description:"General Purpose Controller 1 (Coarse)",position:"msb"},{number:17,name:"generalpurposecontroller2",description:"General Purpose Controller 2 (Coarse)",position:"msb"},{number:18,name:"generalpurposecontroller3",description:"General Purpose Controller 3 (Coarse)",position:"msb"},{number:19,name:"generalpurposecontroller4",description:"General Purpose Controller 4 (Coarse)",position:"msb"},{number:20,name:"controller20",description:"Undefined",position:"msb"},{number:21,name:"controller21",description:"Undefined",position:"msb"},{number:22,name:"controller22",description:"Undefined",position:"msb"},{number:23,name:"controller23",description:"Undefined",position:"msb"},{number:24,name:"controller24",description:"Undefined",position:"msb"},{number:25,name:"controller25",description:"Undefined",position:"msb"},{number:26,name:"controller26",description:"Undefined",position:"msb"},{number:27,name:"controller27",description:"Undefined",position:"msb"},{number:28,name:"controller28",description:"Undefined",position:"msb"},{number:29,name:"controller29",description:"Undefined",position:"msb"},{number:30,name:"controller30",description:"Undefined",position:"msb"},{number:31,name:"controller31",description:"Undefined",position:"msb"},{number:32,name:"bankselectfine",description:"Bank Select (Fine)",position:"lsb"},{number:33,name:"modulationwheelfine",description:"Modulation Wheel (Fine)",position:"lsb"},{number:34,name:"breathcontrollerfine",description:"Breath Controller (Fine)",position:"lsb"},{number:35,name:"controller35",description:"Undefined",position:"lsb"},{number:36,name:"footcontrollerfine",description:"Foot Controller (Fine)",position:"lsb"},{number:37,name:"portamentotimefine",description:"Portamento Time (Fine)",position:"lsb"},{number:38,name:"dataentryfine",description:"Data Entry (Fine)",position:"lsb"},{number:39,name:"channelvolumefine",description:"Channel Volume (Fine)",position:"lsb"},{number:40,name:"balancefine",description:"Balance (Fine)",position:"lsb"},{number:41,name:"controller41",description:"Undefined",position:"lsb"},{number:42,name:"panfine",description:"Pan (Fine)",position:"lsb"},{number:43,name:"expressionfine",description:"Expression Controller (Fine)",position:"lsb"},{number:44,name:"effectcontrol1fine",description:"Effect control 1 (Fine)",position:"lsb"},{number:45,name:"effectcontrol2fine",description:"Effect control 2 (Fine)",position:"lsb"},{number:46,name:"controller46",description:"Undefined",position:"lsb"},{number:47,name:"controller47",description:"Undefined",position:"lsb"},{number:48,name:"controller48",description:"General Purpose Controller 1 (Fine)",position:"lsb"},{number:49,name:"controller49",description:"General Purpose Controller 2 (Fine)",position:"lsb"},{number:50,name:"controller50",description:"General Purpose Controller 3 (Fine)",position:"lsb"},{number:51,name:"controller51",description:"General Purpose Controller 4 (Fine)",position:"lsb"},{number:52,name:"controller52",description:"Undefined",position:"lsb"},{number:53,name:"controller53",description:"Undefined",position:"lsb"},{number:54,name:"controller54",description:"Undefined",position:"lsb"},{number:55,name:"controller55",description:"Undefined",position:"lsb"},{number:56,name:"controller56",description:"Undefined",position:"lsb"},{number:57,name:"controller57",description:"Undefined",position:"lsb"},{number:58,name:"controller58",description:"Undefined",position:"lsb"},{number:59,name:"controller59",description:"Undefined",position:"lsb"},{number:60,name:"controller60",description:"Undefined",position:"lsb"},{number:61,name:"controller61",description:"Undefined",position:"lsb"},{number:62,name:"controller62",description:"Undefined",position:"lsb"},{number:63,name:"controller63",description:"Undefined",position:"lsb"},{number:64,name:"damperpedal",description:"Damper Pedal On/Off"},{number:65,name:"portamento",description:"Portamento On/Off"},{number:66,name:"sostenuto",description:"Sostenuto On/Off"},{number:67,name:"softpedal",description:"Soft Pedal On/Off"},{number:68,name:"legatopedal",description:"Legato Pedal On/Off"},{number:69,name:"hold2",description:"Hold 2 On/Off"},{number:70,name:"soundvariation",description:"Sound Variation",position:"lsb"},{number:71,name:"resonance",description:"Resonance",position:"lsb"},{number:72,name:"releasetime",description:"Release Time",position:"lsb"},{number:73,name:"attacktime",description:"Attack Time",position:"lsb"},{number:74,name:"brightness",description:"Brightness",position:"lsb"},{number:75,name:"decaytime",description:"Decay Time",position:"lsb"},{number:76,name:"vibratorate",description:"Vibrato Rate",position:"lsb"},{number:77,name:"vibratodepth",description:"Vibrato Depth",position:"lsb"},{number:78,name:"vibratodelay",description:"Vibrato Delay",position:"lsb"},{number:79,name:"controller79",description:"Undefined",position:"lsb"},{number:80,name:"generalpurposecontroller5",description:"General Purpose Controller 5",position:"lsb"},{number:81,name:"generalpurposecontroller6",description:"General Purpose Controller 6",position:"lsb"},{number:82,name:"generalpurposecontroller7",description:"General Purpose Controller 7",position:"lsb"},{number:83,name:"generalpurposecontroller8",description:"General Purpose Controller 8",position:"lsb"},{number:84,name:"portamentocontrol",description:"Portamento Control",position:"lsb"},{number:85,name:"controller85",description:"Undefined"},{number:86,name:"controller86",description:"Undefined"},{number:87,name:"controller87",description:"Undefined"},{number:88,name:"highresolutionvelocityprefix",description:"High Resolution Velocity Prefix",position:"lsb"},{number:89,name:"controller89",description:"Undefined"},{number:90,name:"controller90",description:"Undefined"},{number:91,name:"effect1depth",description:"Effects 1 Depth (Reverb Send Level)"},{number:92,name:"effect2depth",description:"Effects 2 Depth"},{number:93,name:"effect3depth",description:"Effects 3 Depth (Chorus Send Level)"},{number:94,name:"effect4depth",description:"Effects 4 Depth"},{number:95,name:"effect5depth",description:"Effects 5 Depth"},{number:96,name:"dataincrement",description:"Data Increment"},{number:97,name:"datadecrement",description:"Data Decrement"},{number:98,name:"nonregisteredparameterfine",description:"Non-Registered Parameter Number (Fine)",position:"lsb"},{number:99,name:"nonregisteredparametercoarse",description:"Non-Registered Parameter Number (Coarse)",position:"msb"},{number:100,name:"registeredparameterfine",description:"Registered Parameter Number (Fine)",position:"lsb"},{number:101,name:"registeredparametercoarse",description:"Registered Parameter Number (Coarse)",position:"msb"},{number:102,name:"controller102",description:"Undefined"},{number:103,name:"controller103",description:"Undefined"},{number:104,name:"controller104",description:"Undefined"},{number:105,name:"controller105",description:"Undefined"},{number:106,name:"controller106",description:"Undefined"},{number:107,name:"controller107",description:"Undefined"},{number:108,name:"controller108",description:"Undefined"},{number:109,name:"controller109",description:"Undefined"},{number:110,name:"controller110",description:"Undefined"},{number:111,name:"controller111",description:"Undefined"},{number:112,name:"controller112",description:"Undefined"},{number:113,name:"controller113",description:"Undefined"},{number:114,name:"controller114",description:"Undefined"},{number:115,name:"controller115",description:"Undefined"},{number:116,name:"controller116",description:"Undefined"},{number:117,name:"controller117",description:"Undefined"},{number:118,name:"controller118",description:"Undefined"},{number:119,name:"controller119",description:"Undefined"},{number:120,name:"allsoundoff",description:"All Sound Off"},{number:121,name:"resetallcontrollers",description:"Reset All Controllers"},{number:122,name:"localcontrol",description:"Local Control On/Off"},{number:123,name:"allnotesoff",description:"All Notes Off"},{number:124,name:"omnimodeoff",description:"Omni Mode Off"},{number:125,name:"omnimodeon",description:"Omni Mode On"},{number:126,name:"monomodeon",description:"Mono Mode On"},{number:127,name:"polymodeon",description:"Poly Mode On"}]}static get REGISTERED_PARAMETERS(){return{pitchbendrange:[0,0],channelfinetuning:[0,1],channelcoarsetuning:[0,2],tuningprogram:[0,3],tuningbank:[0,4],modulationrange:[0,5],azimuthangle:[61,0],elevationangle:[61,1],gain:[61,2],distanceratio:[61,3],maximumdistance:[61,4],maximumdistancegain:[61,5],referencedistanceratio:[61,6],panspreadangle:[61,7],rollangle:[61,8]}}static get MIDI_REGISTERED_PARAMETERS(){return this.validation&&console.warn("The MIDI_REGISTERED_PARAMETERS enum has been deprecated. Use the Enumerations.REGISTERED_PARAMETERS enum instead."),Enumerations.MIDI_REGISTERED_PARAMETERS}static get SYSTEM_MESSAGES(){return{sysex:240,timecode:241,songposition:242,songselect:243,tunerequest:246,tuningrequest:246,sysexend:247,clock:248,start:250,continue:251,stop:252,activesensing:254,reset:255,midimessage:0,unknownsystemmessage:-1}}static get MIDI_SYSTEM_MESSAGES(){return this.validation&&console.warn("The MIDI_SYSTEM_MESSAGES enum has been deprecated. Use the Enumerations.SYSTEM_MESSAGES enum instead."),Enumerations.SYSTEM_MESSAGES}static get CHANNEL_EVENTS(){return["noteoff","controlchange","noteon","keyaftertouch","programchange","channelaftertouch","pitchbend","allnotesoff","allsoundoff","localcontrol","monomode","omnimode","resetallcontrollers","nrpn","nrpn-dataentrycoarse","nrpn-dataentryfine","nrpn-dataincrement","nrpn-datadecrement","rpn","rpn-dataentrycoarse","rpn-dataentryfine","rpn-dataincrement","rpn-datadecrement","nrpn-databuttonincrement","nrpn-databuttondecrement","rpn-databuttonincrement","rpn-databuttondecrement"]}} -/** - * The `Note` class represents a single musical note such as `"D3"`, `"G#4"`, `"F-1"`, `"Gb7"`, etc. - * - * `Note` objects can be played back on a single channel by calling - * [`OutputChannel.playNote()`]{@link OutputChannel#playNote} or, on multiple channels of the same - * output, by calling [`Output.playNote()`]{@link Output#playNote}. - * - * The note has [`attack`](#attack) and [`release`](#release) velocities set at `0.5` by default. - * These can be changed by passing in the appropriate option. It is also possible to set a - * system-wide default for attack and release velocities by using the - * [`WebMidi.defaults`](WebMidi#defaults) property. - * - * If you prefer to work with raw MIDI values (`0` to `127`), you can use [`rawAttack`](#rawAttack) and - * [`rawRelease`](#rawRelease) to both get and set the values. - * - * The note may have a [`duration`](#duration). If it does, playback will be automatically stopped - * when the duration has elapsed by sending a `"noteoff"` event. By default, the duration is set to - * `Infinity`. In this case, it will never stop playing unless explicitly stopped by calling a - * method such as [`OutputChannel.stopNote()`]{@link OutputChannel#stopNote}, - * [`Output.stopNote()`]{@link Output#stopNote} or similar. - * - * @license Apache-2.0 - * @since 3.0.0 - */class Note{constructor(e,t={}){this.duration=wm.defaults.note.duration,this.attack=wm.defaults.note.attack,this.release=wm.defaults.note.release,null!=t.duration&&(this.duration=t.duration),null!=t.attack&&(this.attack=t.attack),null!=t.rawAttack&&(this.attack=Utilities.from7bitToFloat(t.rawAttack)),null!=t.release&&(this.release=t.release),null!=t.rawRelease&&(this.release=Utilities.from7bitToFloat(t.rawRelease)),Number.isInteger(e)?this.identifier=Utilities.toNoteIdentifier(e):this.identifier=e}get identifier(){return this._name+(this._accidental||"")+this._octave}set identifier(e){const t=Utilities.getNoteDetails(e);if(wm.validation&&!e)throw new Error("Invalid note identifier");this._name=t.name,this._accidental=t.accidental,this._octave=t.octave}get name(){return this._name}set name(e){if(wm.validation&&(e=e.toUpperCase(),!["C","D","E","F","G","A","B"].includes(e)))throw new Error("Invalid name value");this._name=e}get accidental(){return this._accidental}set accidental(e){if(wm.validation&&(e=e.toLowerCase(),!["#","##","b","bb"].includes(e)))throw new Error("Invalid accidental value");this._accidental=e}get octave(){return this._octave}set octave(e){if(wm.validation&&(e=parseInt(e),isNaN(e)))throw new Error("Invalid octave value");this._octave=e}get duration(){return this._duration}set duration(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||null===e||e<0))throw new RangeError("Invalid duration value.");this._duration=e}get attack(){return this._attack}set attack(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||!(e>=0&&e<=1)))throw new RangeError("Invalid attack value.");this._attack=e}get release(){return this._release}set release(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||!(e>=0&&e<=1)))throw new RangeError("Invalid release value.");this._release=e}get rawAttack(){return Utilities.fromFloatTo7Bit(this._attack)}set rawAttack(e){this._attack=Utilities.from7bitToFloat(e)}get rawRelease(){return Utilities.fromFloatTo7Bit(this._release)}set rawRelease(e){this._release=Utilities.from7bitToFloat(e)}get number(){return Utilities.toNoteNumber(this.identifier)}getOffsetNumber(e=0,t=0){return wm.validation&&(e=parseInt(e)||0,t=parseInt(t)||0),Math.min(Math.max(this.number+12*e+t,0),127)}} -/** - * The `Utilities` class contains general-purpose utility methods. All methods are static and - * should be called using the class name. For example: `Utilities.getNoteDetails("C4")`. - * - * @license Apache-2.0 - * @since 3.0.0 - */class Utilities{ -/** - * Returns a MIDI note number matching the identifier passed in the form of a string. The - * identifier must include the octave number. The identifier also optionally include a sharp (#), - * a double sharp (##), a flat (b) or a double flat (bb) symbol. For example, these are all valid - * identifiers: C5, G4, D#-1, F0, Gb7, Eb-1, Abb4, B##6, etc. - * - * When converting note identifiers to numbers, C4 is considered to be middle C (MIDI note number - * 60) as per the scientific pitch notation standard. - * - * The resulting note number can be offset by using the `octaveOffset` parameter. - * - * @param identifier {string} The identifier in the form of a letter, followed by an optional "#", - * "##", "b" or "bb" followed by the octave number. For exemple: C5, G4, D#-1, F0, Gb7, Eb-1, - * Abb4, B##6, etc. - * - * @param {number} [octaveOffset=0] A integer to offset the octave by. - * - * @returns {number} The MIDI note number (an integer between 0 and 127). - * - * @throws RangeError Invalid 'octaveOffset' value - * - * @throws TypeError Invalid note identifier - * - * @license Apache-2.0 - * @since 3.0.0 - * @static - */ -static toNoteNumber(e,t=0){if(t=null==t?0:parseInt(t),isNaN(t))throw new RangeError("Invalid 'octaveOffset' value");"string"!=typeof e&&(e="");const n=this.getNoteDetails(e);if(!n)throw new TypeError("Invalid note identifier");let r=12*(n.octave+1+t);if(r+={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[n.name],n.accidental&&(n.accidental.startsWith("b")?r-=n.accidental.length:r+=n.accidental.length),r<0||r>127)throw new RangeError("Invalid octaveOffset value");return r}static getNoteDetails(e){Number.isInteger(e)&&(e=this.toNoteIdentifier(e));const t=e.match(/^([CDEFGAB])(#{0,2}|b{0,2})(-?\d+)$/i);if(!t)throw new TypeError("Invalid note identifier");const n=t[1].toUpperCase(),r=parseInt(t[3]);let i=t[2].toLowerCase();i=""===i?void 0:i;return{accidental:i,identifier:n+(i||"")+r,name:n,octave:r}}static sanitizeChannels(e){let t;if(wm.validation)if("all"===e)t=["all"];else if("none"===e)return[];return t=Array.isArray(e)?e:[e],t.indexOf("all")>-1&&(t=Enumerations.MIDI_CHANNEL_NUMBERS),t.map((function(e){return parseInt(e)})).filter((function(e){return e>=1&&e<=16}))}static toTimestamp(e){let t=!1;const n=parseFloat(e);return!isNaN(n)&&("string"==typeof e&&"+"===e.substring(0,1)?n>=0&&(t=wm.time+n):n>=0&&(t=n),t)}static guessNoteNumber(e,t){t=parseInt(t)||0;let n=!1;if(Number.isInteger(e)&&e>=0&&e<=127)n=parseInt(e);else if(parseInt(e)>=0&&parseInt(e)<=127)n=parseInt(e);else if("string"==typeof e||e instanceof String)try{n=this.toNoteNumber(e.trim(),t)}catch(e){return!1}return n}static toNoteIdentifier(e,t){if(e=parseInt(e),isNaN(e)||e<0||e>127)throw new RangeError("Invalid note number");if(t=null==t?0:parseInt(t),isNaN(t))throw new RangeError("Invalid octaveOffset value");const n=Math.floor(e/12-1)+t;return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][e%12]+n.toString()}static buildNote(e,t={}){if(t.octaveOffset=parseInt(t.octaveOffset)||0,e instanceof Note)return e;let n=this.guessNoteNumber(e,t.octaveOffset);if(!1===n)throw new TypeError(`The input could not be parsed as a note (${e})`);return t.octaveOffset=void 0,new Note(n,t)}static buildNoteArray(e,t={}){let n=[];return Array.isArray(e)||(e=[e]),e.forEach(e=>{n.push(this.buildNote(e,t))}),n}static from7bitToFloat(e){return e===1/0&&(e=127),e=parseInt(e)||0,Math.min(Math.max(e/127,0),1)}static fromFloatTo7Bit(e){return e===1/0&&(e=1),e=parseFloat(e)||0,Math.min(Math.max(Math.round(127*e),0),127)}static fromMsbLsbToFloat(e,t=0){wm.validation&&(e=Math.min(Math.max(parseInt(e)||0,0),127),t=Math.min(Math.max(parseInt(t)||0,0),127));const n=((e<<7)+t)/16383;return Math.min(Math.max(n,0),1)}static fromFloatToMsbLsb(e){wm.validation&&(e=Math.min(Math.max(parseFloat(e)||0,0),1));const t=Math.round(16383*e);return{msb:t>>7,lsb:127&t}}static offsetNumber(e,t=0,n=0){if(wm.validation){if(e=parseInt(e),isNaN(e))throw new Error("Invalid note number");t=parseInt(t)||0,n=parseInt(n)||0}return Math.min(Math.max(e+12*t+n,0),127)}static getPropertyByValue(e,t){return Object.keys(e).find(n=>e[n]===t)}static getCcNameByNumber(e){if(!wm.validation||(e=parseInt(e))>=0&&e<=127)return Enumerations.CONTROL_CHANGE_MESSAGES[e].name}static getCcNumberByName(e){let t=Enumerations.CONTROL_CHANGE_MESSAGES.find(t=>t.name===e);return t?t.number:Enumerations.MIDI_CONTROL_CHANGE_MESSAGES[e]}static getChannelModeByNumber(e){if(!(e>=120&&e<=127))return!1;for(let t in Enumerations.CHANNEL_MODE_MESSAGES)if(Enumerations.CHANNEL_MODE_MESSAGES.hasOwnProperty(t)&&e===Enumerations.CHANNEL_MODE_MESSAGES[t])return t;return!1}static get isNode(){return"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node}static get isBrowser(){return"undefined"!=typeof window&&void 0!==window.document}} -/** - * The `OutputChannel` class represents a single output MIDI channel. `OutputChannel` objects are - * provided by an [`Output`](Output) port which, itself, is made available by a device. The - * `OutputChannel` object is derived from the host's MIDI subsystem and should not be instantiated - * directly. - * - * All 16 `OutputChannel` objects can be found inside the parent output's - * [`channels`]{@link Output#channels} property. - * - * @param {Output} output The [`Output`](Output) this channel belongs to. - * @param {number} number The MIDI channel number (`1` - `16`). - * - * @extends EventEmitter - * @license Apache-2.0 - * @since 3.0.0 - */class OutputChannel extends EventEmitter{constructor(e,t){super(),this._output=e,this._number=t,this._octaveOffset=0}destroy(){this._output=null,this._number=null,this._octaveOffset=0,this.removeListener()}send(e,t={time:0}){return this.output.send(e,t),this}sendKeyAftertouch(e,t,n={}){if(wm.validation){if(n.useRawValue&&(n.rawValue=n.useRawValue),isNaN(parseFloat(t)))throw new RangeError("Invalid key aftertouch value.");if(n.rawValue){if(!(t>=0&&t<=127&&Number.isInteger(t)))throw new RangeError("Key aftertouch raw value must be an integer between 0 and 127.")}else if(!(t>=0&&t<=1))throw new RangeError("Key aftertouch value must be a float between 0 and 1.")}n.rawValue||(t=Utilities.fromFloatTo7Bit(t));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Array.isArray(e)||(e=[e]),Utilities.buildNoteArray(e).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.keyaftertouch<<4)+(this.number-1),e.getOffsetNumber(r),t],{time:Utilities.toTimestamp(n.time)})}),this} -/** - * Sends a MIDI **control change** message to the channel at the scheduled time. The control - * change message to send can be specified numerically (`0` to `127`) or by using one of the - * following common names: - * - * | Number | Name | - * |--------|-------------------------------| - * | 0 |`bankselectcoarse` | - * | 1 |`modulationwheelcoarse` | - * | 2 |`breathcontrollercoarse` | - * | 4 |`footcontrollercoarse` | - * | 5 |`portamentotimecoarse` | - * | 6 |`dataentrycoarse` | - * | 7 |`volumecoarse` | - * | 8 |`balancecoarse` | - * | 10 |`pancoarse` | - * | 11 |`expressioncoarse` | - * | 12 |`effectcontrol1coarse` | - * | 13 |`effectcontrol2coarse` | - * | 18 |`generalpurposeslider3` | - * | 19 |`generalpurposeslider4` | - * | 32 |`bankselectfine` | - * | 33 |`modulationwheelfine` | - * | 34 |`breathcontrollerfine` | - * | 36 |`footcontrollerfine` | - * | 37 |`portamentotimefine` | - * | 38 |`dataentryfine` | - * | 39 |`volumefine` | - * | 40 |`balancefine` | - * | 42 |`panfine` | - * | 43 |`expressionfine` | - * | 44 |`effectcontrol1fine` | - * | 45 |`effectcontrol2fine` | - * | 64 |`holdpedal` | - * | 65 |`portamento` | - * | 66 |`sustenutopedal` | - * | 67 |`softpedal` | - * | 68 |`legatopedal` | - * | 69 |`hold2pedal` | - * | 70 |`soundvariation` | - * | 71 |`resonance` | - * | 72 |`soundreleasetime` | - * | 73 |`soundattacktime` | - * | 74 |`brightness` | - * | 75 |`soundcontrol6` | - * | 76 |`soundcontrol7` | - * | 77 |`soundcontrol8` | - * | 78 |`soundcontrol9` | - * | 79 |`soundcontrol10` | - * | 80 |`generalpurposebutton1` | - * | 81 |`generalpurposebutton2` | - * | 82 |`generalpurposebutton3` | - * | 83 |`generalpurposebutton4` | - * | 91 |`reverblevel` | - * | 92 |`tremololevel` | - * | 93 |`choruslevel` | - * | 94 |`celestelevel` | - * | 95 |`phaserlevel` | - * | 96 |`dataincrement` | - * | 97 |`datadecrement` | - * | 98 |`nonregisteredparametercoarse` | - * | 99 |`nonregisteredparameterfine` | - * | 100 |`registeredparametercoarse` | - * | 101 |`registeredparameterfine` | - * | 120 |`allsoundoff` | - * | 121 |`resetallcontrollers` | - * | 122 |`localcontrol` | - * | 123 |`allnotesoff` | - * | 124 |`omnimodeoff` | - * | 125 |`omnimodeon` | - * | 126 |`monomodeon` | - * | 127 |`polymodeon` | - * - * As you can see above, not all control change message have a matching name. This does not mean - * you cannot use the others. It simply means you will need to use their number - * (`0` to `127`) instead of their name. While you can still use them, numbers `120` to `127` are - * usually reserved for *channel mode* messages. See - * [`sendChannelMode()`]{@link OutputChannel#sendChannelMode} method for more info. - * - * To view a detailed list of all available **control change** messages, please consult "Table 3 - - * Control Change Messages" from the [MIDI Messages]( - * https://www.midi.org/specifications/item/table-3-control-change-messages-data-bytes-2) - * specification. - * - * **Note**: messages #0-31 (MSB) are paired with messages #32-63 (LSB). For example, message #1 - * (`modulationwheelcoarse`) can be accompanied by a second control change message for - * `modulationwheelfine` to achieve a greater level of precision. if you want to specify both MSB - * and LSB for messages between `0` and `31`, you can do so by passing a 2-value array as the - * second parameter. - * - * @param {number|string} controller The MIDI controller name or number (`0` - `127`). - * - * @param {number|number[]} value The value to send (0-127). You can also use a two-position array - * for controllers 0 to 31. In this scenario, the first value will be sent as usual and the second - * value will be sent to the matching LSB controller (which is obtained by adding 32 to the first - * controller) - * - * @param {object} [options={}] - * - * @param {number|string} [options.time=(now)] If `time` is a string prefixed with `"+"` and - * followed by a number, the message will be delayed by that many milliseconds. If the value is a - * positive number - * ([`DOMHighResTimeStamp`]{@link https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp}), - * the operation will be scheduled for that time. The current time can be retrieved with - * [`WebMidi.time`]{@link WebMidi#time}. If `options.time` is omitted, or in the past, the - * operation will be carried out as soon as possible. - * - * @throws {RangeError} Controller numbers must be between 0 and 127. - * @throws {RangeError} Invalid controller name. - * @throws {TypeError} The value array must have a length of 2. - * - * @returns {OutputChannel} Returns the `OutputChannel` object so methods can be chained. - * - * @license Apache-2.0 - * @since 3.0.0 - */sendControlChange(e,t,n={}){if("string"==typeof e&&(e=Utilities.getCcNumberByName(e)),Array.isArray(t)||(t=[t]),wm.validation){if(void 0===e)throw new TypeError("Control change must be identified with a valid name or an integer between 0 and 127.");if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new TypeError("Control change number must be an integer between 0 and 127.");if(2===(t=t.map(e=>{const t=Math.min(Math.max(parseInt(e),0),127);if(isNaN(t))throw new TypeError("Values must be integers between 0 and 127");return t})).length&&e>=32)throw new TypeError("To use a value array, the controller must be between 0 and 31")}return t.forEach((r,i)=>{this.send([(Enumerations.CHANNEL_MESSAGES.controlchange<<4)+(this.number-1),e+32*i,t[i]],{time:Utilities.toTimestamp(n.time)})}),this}_selectNonRegisteredParameter(e,t={}){return this.sendControlChange(99,e[0],t),this.sendControlChange(98,e[1],t),this}_deselectRegisteredParameter(e={}){return this.sendControlChange(101,127,e),this.sendControlChange(100,127,e),this}_deselectNonRegisteredParameter(e={}){return this.sendControlChange(101,127,e),this.sendControlChange(100,127,e),this}_selectRegisteredParameter(e,t={}){return this.sendControlChange(101,e[0],t),this.sendControlChange(100,e[1],t),this}_setCurrentParameter(e,t={}){return e=[].concat(e),this.sendControlChange(6,e[0],t),e.length<2||this.sendControlChange(38,e[1],t),this}sendRpnDecrement(e,t={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(void 0===e)throw new TypeError("The specified registered parameter is invalid.");let t=!1;if(Object.getOwnPropertyNames(Enumerations.REGISTERED_PARAMETERS).forEach(n=>{Enumerations.REGISTERED_PARAMETERS[n][0]===e[0]&&Enumerations.REGISTERED_PARAMETERS[n][1]===e[1]&&(t=!0)}),!t)throw new TypeError("The specified registered parameter is invalid.")}return this._selectRegisteredParameter(e,t),this.sendControlChange(97,0,t),this._deselectRegisteredParameter(t),this}sendRpnIncrement(e,t={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(void 0===e)throw new TypeError("The specified registered parameter is invalid.");let t=!1;if(Object.getOwnPropertyNames(Enumerations.REGISTERED_PARAMETERS).forEach(n=>{Enumerations.REGISTERED_PARAMETERS[n][0]===e[0]&&Enumerations.REGISTERED_PARAMETERS[n][1]===e[1]&&(t=!0)}),!t)throw new TypeError("The specified registered parameter is invalid.")}return this._selectRegisteredParameter(e,t),this.sendControlChange(96,0,t),this._deselectRegisteredParameter(t),this}playNote(e,t={}){this.sendNoteOn(e,t);const n=Array.isArray(e)?e:[e];for(let e of n)if(parseInt(e.duration)>0){const n={time:(Utilities.toTimestamp(t.time)||wm.time)+parseInt(e.duration),release:e.release,rawRelease:e.rawRelease};this.sendNoteOff(e,n)}else if(parseInt(t.duration)>0){const n={time:(Utilities.toTimestamp(t.time)||wm.time)+parseInt(t.duration),release:t.release,rawRelease:t.rawRelease};this.sendNoteOff(e,n)}return this}sendNoteOff(e,t={}){if(wm.validation){if(null!=t.rawRelease&&!(t.rawRelease>=0&&t.rawRelease<=127))throw new RangeError("The 'rawRelease' option must be an integer between 0 and 127");if(null!=t.release&&!(t.release>=0&&t.release<=1))throw new RangeError("The 'release' option must be an number between 0 and 1");t.rawVelocity&&(t.rawRelease=t.velocity,console.warn("The 'rawVelocity' option is deprecated. Use 'rawRelease' instead.")),t.velocity&&(t.release=t.velocity,console.warn("The 'velocity' option is deprecated. Use 'attack' instead."))}let n=64;null!=t.rawRelease?n=t.rawRelease:isNaN(t.release)||(n=Math.round(127*t.release));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Utilities.buildNoteArray(e,{rawRelease:parseInt(n)}).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.noteoff<<4)+(this.number-1),e.getOffsetNumber(r),e.rawRelease],{time:Utilities.toTimestamp(t.time)})}),this}stopNote(e,t={}){return this.sendNoteOff(e,t)}sendNoteOn(e,t={}){if(wm.validation){if(null!=t.rawAttack&&!(t.rawAttack>=0&&t.rawAttack<=127))throw new RangeError("The 'rawAttack' option must be an integer between 0 and 127");if(null!=t.attack&&!(t.attack>=0&&t.attack<=1))throw new RangeError("The 'attack' option must be an number between 0 and 1");t.rawVelocity&&(t.rawAttack=t.velocity,t.rawRelease=t.release,console.warn("The 'rawVelocity' option is deprecated. Use 'rawAttack' or 'rawRelease'.")),t.velocity&&(t.attack=t.velocity,console.warn("The 'velocity' option is deprecated. Use 'attack' instead."))}let n=64;null!=t.rawAttack?n=t.rawAttack:isNaN(t.attack)||(n=Math.round(127*t.attack));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Utilities.buildNoteArray(e,{rawAttack:n}).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.noteon<<4)+(this.number-1),e.getOffsetNumber(r),e.rawAttack],{time:Utilities.toTimestamp(t.time)})}),this}sendChannelMode(e,t=0,n={}){if("string"==typeof e&&(e=Enumerations.CHANNEL_MODE_MESSAGES[e]),wm.validation){if(void 0===e)throw new TypeError("Invalid channel mode message name or number.");if(isNaN(e)||!(e>=120&&e<=127))throw new TypeError("Invalid channel mode message number.");if(isNaN(parseInt(t))||t<0||t>127)throw new RangeError("Value must be an integer between 0 and 127.")}return this.send([(Enumerations.CHANNEL_MESSAGES.controlchange<<4)+(this.number-1),e,t],{time:Utilities.toTimestamp(n.time)}),this}sendOmniMode(e,t={}){return void 0===e||e?this.sendChannelMode("omnimodeon",0,t):this.sendChannelMode("omnimodeoff",0,t),this}sendChannelAftertouch(e,t={}){if(wm.validation){if(isNaN(parseFloat(e)))throw new RangeError("Invalid channel aftertouch value.");if(t.rawValue){if(!(e>=0&&e<=127&&Number.isInteger(e)))throw new RangeError("Channel aftertouch raw value must be an integer between 0 and 127.")}else if(!(e>=0&&e<=1))throw new RangeError("Channel aftertouch value must be a float between 0 and 1.")}return t.rawValue||(e=Utilities.fromFloatTo7Bit(e)),this.send([(Enumerations.CHANNEL_MESSAGES.channelaftertouch<<4)+(this.number-1),Math.round(e)],{time:Utilities.toTimestamp(t.time)}),this}sendMasterTuning(e,t={}){if(e=parseFloat(e)||0,wm.validation&&!(e>-65&&e<64))throw new RangeError("The value must be a decimal number larger than -65 and smaller than 64.");let n=Math.floor(e)+64,r=e-Math.floor(e);r=Math.round((r+1)/2*16383);let i=r>>7&127,s=127&r;return this.sendRpnValue("channelcoarsetuning",n,t),this.sendRpnValue("channelfinetuning",[i,s],t),this}sendModulationRange(e,t,n={}){if(wm.validation){if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new RangeError("The semitones value must be an integer between 0 and 127.");if(!(null==t||Number.isInteger(t)&&t>=0&&t<=127))throw new RangeError("If specified, the cents value must be an integer between 0 and 127.")}return t>=0&&t<=127||(t=0),this.sendRpnValue("modulationrange",[e,t],n),this}sendNrpnValue(e,t,n={}){if(t=[].concat(t),wm.validation){if(!Array.isArray(e)||!Number.isInteger(e[0])||!Number.isInteger(e[1]))throw new TypeError("The specified NRPN is invalid.");if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The first byte of the NRPN must be between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The second byte of the NRPN must be between 0 and 127.");t.forEach(e=>{if(!(e>=0&&e<=127))throw new RangeError("The data bytes of the NRPN must be between 0 and 127.")})}return this._selectNonRegisteredParameter(e,n),this._setCurrentParameter(t,n),this._deselectNonRegisteredParameter(n),this}sendPitchBend(e,t={}){if(wm.validation)if(t.rawValue&&Array.isArray(e)){if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The pitch bend MSB must be an integer between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The pitch bend LSB must be an integer between 0 and 127.")}else if(t.rawValue&&!Array.isArray(e)){if(!(e>=0&&e<=127))throw new RangeError("The pitch bend MSB must be an integer between 0 and 127.")}else{if(isNaN(e)||null===e)throw new RangeError("Invalid pitch bend value.");if(!(e>=-1&&e<=1))throw new RangeError("The pitch bend value must be a float between -1 and 1.")}let n=0,r=0;if(t.rawValue&&Array.isArray(e))n=e[0],r=e[1];else if(t.rawValue&&!Array.isArray(e))n=e;else{const t=Utilities.fromFloatToMsbLsb((e+1)/2);n=t.msb,r=t.lsb}return this.send([(Enumerations.CHANNEL_MESSAGES.pitchbend<<4)+(this.number-1),r,n],{time:Utilities.toTimestamp(t.time)}),this}sendPitchBendRange(e,t,n={}){if(wm.validation){if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new RangeError("The semitones value must be an integer between 0 and 127.");if(!Number.isInteger(t)||!(t>=0&&t<=127))throw new RangeError("The cents value must be an integer between 0 and 127.")}return this.sendRpnValue("pitchbendrange",[e,t],n),this}sendProgramChange(e,t={}){if(e=parseInt(e)||0,wm.validation&&!(e>=0&&e<=127))throw new RangeError("The program number must be between 0 and 127.");return this.send([(Enumerations.CHANNEL_MESSAGES.programchange<<4)+(this.number-1),e],{time:Utilities.toTimestamp(t.time)}),this}sendRpnValue(e,t,n={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(!Number.isInteger(e[0])||!Number.isInteger(e[1]))throw new TypeError("The specified NRPN is invalid.");if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The first byte of the RPN must be between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The second byte of the RPN must be between 0 and 127.");[].concat(t).forEach(e=>{if(!(e>=0&&e<=127))throw new RangeError("The data bytes of the RPN must be between 0 and 127.")})}return this._selectRegisteredParameter(e,n),this._setCurrentParameter(t,n),this._deselectRegisteredParameter(n),this}sendTuningBank(e,t={}){if(wm.validation&&(!Number.isInteger(e)||!(e>=0&&e<=127)))throw new RangeError("The tuning bank number must be between 0 and 127.");return this.sendRpnValue("tuningbank",e,t),this}sendTuningProgram(e,t={}){if(wm.validation&&(!Number.isInteger(e)||!(e>=0&&e<=127)))throw new RangeError("The tuning program number must be between 0 and 127.");return this.sendRpnValue("tuningprogram",e,t),this}sendLocalControl(e,t={}){return e?this.sendChannelMode("localcontrol",127,t):this.sendChannelMode("localcontrol",0,t)}sendAllNotesOff(e={}){return this.sendChannelMode("allnotesoff",0,e)}sendAllSoundOff(e={}){return this.sendChannelMode("allsoundoff",0,e)}sendResetAllControllers(e={}){return this.sendChannelMode("resetallcontrollers",0,e)}sendPolyphonicMode(e,t={}){return"mono"===e?this.sendChannelMode("monomodeon",0,t):this.sendChannelMode("polymodeon",0,t)}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get output(){return this._output}get number(){return this._number}} -/** - * The `Output` class represents a single MIDI output port (not to be confused with a MIDI channel). - * A port is made available by a MIDI device. A MIDI device can advertise several input and output - * ports. Each port has 16 MIDI channels which can be accessed via the [`channels`](#channels) - * property. - * - * The `Output` object is automatically instantiated by the library according to the host's MIDI - * subsystem and should not be directly instantiated. - * - * You can access all available `Output` objects by referring to the - * [`WebMidi.outputs`](WebMidi#outputs) array or by using methods such as - * [`WebMidi.getOutputByName()`](WebMidi#getOutputByName) or - * [`WebMidi.getOutputById()`](WebMidi#getOutputById). - * - * @fires Output#opened - * @fires Output#disconnected - * @fires Output#closed - * - * @extends EventEmitter - * @license Apache-2.0 - */class Output extends EventEmitter{constructor(e){super(),this._midiOutput=e,this._octaveOffset=0,this.channels=[];for(let e=1;e<=16;e++)this.channels[e]=new OutputChannel(this,e);this._midiOutput.onstatechange=this._onStateChange.bind(this)}async destroy(){this.removeListener(),this.channels.forEach(e=>e.destroy()),this.channels=[],this._midiOutput&&(this._midiOutput.onstatechange=null),await this.close(),this._midiOutput=null}_onStateChange(e){let t={timestamp:wm.time};"open"===e.port.connection?(t.type="opened",t.target=this,t.port=t.target,this.emit("opened",t)):"closed"===e.port.connection&&"connected"===e.port.state?(t.type="closed",t.target=this,t.port=t.target,this.emit("closed",t)):"closed"===e.port.connection&&"disconnected"===e.port.state?(t.type="disconnected",t.port={connection:e.port.connection,id:e.port.id,manufacturer:e.port.manufacturer,name:e.port.name,state:e.port.state,type:e.port.type},this.emit("disconnected",t)):"pending"===e.port.connection&&"disconnected"===e.port.state||console.warn("This statechange event was not caught:",e.port.connection,e.port.state)}async open(){try{return await this._midiOutput.open(),Promise.resolve(this)}catch(e){return Promise.reject(e)}}async close(){this._midiOutput?await this._midiOutput.close():await Promise.resolve()} -/** - * Sends a MIDI message on the MIDI output port. If no time is specified, the message will be - * sent immediately. The message should be an array of 8 bit unsigned integers (0-225), a - * [`Uint8Array`]{@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array} - * object or a [`Message`](Message) object. - * - * It is usually not necessary to use this method directly as you can use one of the simpler - * helper methods such as [`playNote()`](#playNote), [`stopNote()`](#stopNote), - * [`sendControlChange()`](#sendControlChange), etc. - * - * Details on the format of MIDI messages are available in the summary of - * [MIDI messages]{@link https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message} - * from the MIDI Manufacturers Association. - * - * @param message {number[]|Uint8Array|Message} An array of 8bit unsigned integers, a `Uint8Array` - * object (not available in Node.js) containing the message bytes or a `Message` object. - * - * @param {object} [options={}] - * - * @param {number|string} [options.time=(now)] If `time` is a string prefixed with `"+"` and - * followed by a number, the message will be delayed by that many milliseconds. If the value is a - * positive number - * ([`DOMHighResTimeStamp`]{@link https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp}), - * the operation will be scheduled for that time. The current time can be retrieved with - * [`WebMidi.time`]{@link WebMidi#time}. If `options.time` is omitted, or in the past, the - * operation will be carried out as soon as possible. - * - * @throws {RangeError} The first byte (status) must be an integer between 128 and 255. - * - * @returns {Output} Returns the `Output` object so methods can be chained. - * - * @license Apache-2.0 - */send(e,t={time:0},n=0){if(e instanceof Message&&(e=Utilities.isNode?e.data:e.rawData),e instanceof Uint8Array&&Utilities.isNode&&(e=Array.from(e)),wm.validation){if(Array.isArray(e)||e instanceof Uint8Array||(e=[e],Array.isArray(t)&&(e=e.concat(t)),t=isNaN(n)?{time:0}:{time:n}),!(parseInt(e[0])>=128&&parseInt(e[0])<=255))throw new RangeError("The first byte (status) must be an integer between 128 and 255.");e.slice(1).forEach(e=>{if(!((e=parseInt(e))>=0&&e<=255))throw new RangeError("Data bytes must be integers between 0 and 255.")}),t||(t={time:0})}return this._midiOutput.send(e,Utilities.toTimestamp(t.time)),this}sendSysex(e,t=[],n={}){if(e=[].concat(e),t instanceof Uint8Array){const r=new Uint8Array(1+e.length+t.length+1);r[0]=Enumerations.SYSTEM_MESSAGES.sysex,r.set(Uint8Array.from(e),1),r.set(t,1+e.length),r[r.length-1]=Enumerations.SYSTEM_MESSAGES.sysexend,this.send(r,{time:n.time})}else{const r=e.concat(t,Enumerations.SYSTEM_MESSAGES.sysexend);this.send([Enumerations.SYSTEM_MESSAGES.sysex].concat(r),{time:n.time})}return this}clear(){return this._midiOutput.clear?this._midiOutput.clear():wm.validation&&console.warn("The 'clear()' method has not yet been implemented in your environment."),this}sendTimecodeQuarterFrame(e,t={}){if(wm.validation&&(e=parseInt(e),isNaN(e)||!(e>=0&&e<=127)))throw new RangeError("The value must be an integer between 0 and 127.");return this.send([Enumerations.SYSTEM_MESSAGES.timecode,e],{time:t.time}),this}sendSongPosition(e=0,t={}){var n=(e=Math.floor(e)||0)>>7&127,r=127&e;return this.send([Enumerations.SYSTEM_MESSAGES.songposition,n,r],{time:t.time}),this}sendSongSelect(e=0,t={}){if(wm.validation&&(e=parseInt(e),isNaN(e)||!(e>=0&&e<=127)))throw new RangeError("The program value must be between 0 and 127");return this.send([Enumerations.SYSTEM_MESSAGES.songselect,e],{time:t.time}),this}sendTuneRequest(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.tunerequest],{time:e.time}),this}sendClock(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.clock],{time:e.time}),this}sendStart(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.start],{time:e.time}),this}sendContinue(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.continue],{time:e.time}),this}sendStop(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.stop],{time:e.time}),this}sendActiveSensing(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.activesensing],{time:e.time}),this}sendReset(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.reset],{time:e.time}),this}sendTuningRequest(e={}){return wm.validation&&console.warn("The sendTuningRequest() method has been deprecated. Use sendTuningRequest() instead."),this.sendTuneRequest(e)}sendKeyAftertouch(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendKeyAftertouch(e,t,n)}),this}sendControlChange(e,t,n={},r={}){if(wm.validation&&(Array.isArray(n)||Number.isInteger(n)||"all"===n)){const e=n;(n=r).channels=e,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendControlChange(e,t,n)}),this}sendPitchBendRange(e=0,t=0,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendPitchBendRange(e,t,n)}),this}setPitchBendRange(e=0,t=0,n="all",r={}){return wm.validation&&(console.warn("The setPitchBendRange() method is deprecated. Use sendPitchBendRange() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendPitchBendRange(e,t,r)}sendRpnValue(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendRpnValue(e,t,n)}),this}setRegisteredParameter(e,t=[],n="all",r={}){return wm.validation&&(console.warn("The setRegisteredParameter() method is deprecated. Use sendRpnValue() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnValue(e,t,r)}sendChannelAftertouch(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendChannelAftertouch(e,t)}),this}sendPitchBend(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendPitchBend(e,t)}),this}sendProgramChange(e=0,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendProgramChange(e,t)}),this}sendModulationRange(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendModulationRange(e,t,n)}),this}setModulationRange(e=0,t=0,n="all",r={}){return wm.validation&&(console.warn("The setModulationRange() method is deprecated. Use sendModulationRange() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendModulationRange(e,t,r)}sendMasterTuning(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendMasterTuning(e,t)}),this}setMasterTuning(e,t={},n={}){return wm.validation&&(console.warn("The setMasterTuning() method is deprecated. Use sendMasterTuning() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendMasterTuning(e,n)}sendTuningProgram(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendTuningProgram(e,t)}),this}setTuningProgram(e,t="all",n={}){return wm.validation&&(console.warn("The setTuningProgram() method is deprecated. Use sendTuningProgram() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendTuningProgram(e,n)}sendTuningBank(e=0,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendTuningBank(e,t)}),this}setTuningBank(e,t="all",n={}){return wm.validation&&(console.warn("The setTuningBank() method is deprecated. Use sendTuningBank() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendTuningBank(e,n)}sendChannelMode(e,t=0,n={},r={}){if(wm.validation&&(Array.isArray(n)||Number.isInteger(n)||"all"===n)){const e=n;(n=r).channels=e,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendChannelMode(e,t,n)}),this}sendAllSoundOff(e={}){return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendAllSoundOff(e)}),this}sendAllNotesOff(e={}){return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendAllNotesOff(e)}),this}sendResetAllControllers(e={},t={}){if(wm.validation&&(Array.isArray(e)||Number.isInteger(e)||"all"===e)){const n=e;(e=t).channels=n,"all"===e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendResetAllControllers(e)}),this}sendPolyphonicMode(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendPolyphonicMode(e,t)}),this}sendLocalControl(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendLocalControl(e,t)}),this}sendOmniMode(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendOmniMode(e,t)}),this}sendNrpnValue(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendNrpnValue(e,t,n)}),this}setNonRegisteredParameter(e,t=[],n="all",r={}){return wm.validation&&(console.warn("The setNonRegisteredParameter() method is deprecated. Use sendNrpnValue() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendNrpnValue(e,t,r)}sendRpnIncrement(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendRpnIncrement(e,t)}),this}incrementRegisteredParameter(e,t="all",n={}){return wm.validation&&(console.warn("The incrementRegisteredParameter() method is deprecated. Use sendRpnIncrement() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnIncrement(e,n)}sendRpnDecrement(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendRpnDecrement(e,t)}),this}decrementRegisteredParameter(e,t="all",n={}){return wm.validation&&(console.warn("The decrementRegisteredParameter() method is deprecated. Use sendRpnDecrement() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnDecrement(e,n)}sendNoteOff(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendNoteOff(e,t)}),this}stopNote(e,t){return this.sendNoteOff(e,t)}playNote(e,t={},n={}){if(wm.validation&&(t.rawVelocity&&console.warn("The 'rawVelocity' option is deprecated. Use 'rawAttack' instead."),t.velocity&&console.warn("The 'velocity' option is deprecated. Use 'velocity' instead."),Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].playNote(e,t)}),this}sendNoteOn(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendNoteOn(e,t)}),this}get name(){return this._midiOutput.name}get id(){return this._midiOutput.id}get connection(){return this._midiOutput.connection}get manufacturer(){return this._midiOutput.manufacturer}get state(){return this._midiOutput.state}get type(){return this._midiOutput.type}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}} -/** - * The `Forwarder` class allows the forwarding of MIDI messages to predetermined outputs. When you - * call its [`forward()`](#forward) method, it will send the specified [`Message`](Message) object - * to all the outputs listed in its [`destinations`](#destinations) property. - * - * If specific channels or message types have been defined in the [`channels`](#channels) or - * [`types`](#types) properties, only messages matching the channels/types will be forwarded. - * - * While it can be manually instantiated, you are more likely to come across a `Forwarder` object as - * the return value of the [`Input.addForwarder()`](Input#addForwarder) method. - * - * @license Apache-2.0 - * @since 3.0.0 - */class Forwarder{constructor(e=[],t={}){this.destinations=[],this.types=[...Object.keys(Enumerations.SYSTEM_MESSAGES),...Object.keys(Enumerations.CHANNEL_MESSAGES)],this.channels=Enumerations.MIDI_CHANNEL_NUMBERS,this.suspended=!1,Array.isArray(e)||(e=[e]),t.types&&!Array.isArray(t.types)&&(t.types=[t.types]),t.channels&&!Array.isArray(t.channels)&&(t.channels=[t.channels]),wm.validation&&(e.forEach(e=>{if(!(e instanceof Output))throw new TypeError("Destinations must be of type 'Output'.")}),void 0!==t.types&&t.types.forEach(e=>{if(!Enumerations.SYSTEM_MESSAGES.hasOwnProperty(e)&&!Enumerations.CHANNEL_MESSAGES.hasOwnProperty(e))throw new TypeError("Type must be a valid message type.")}),void 0!==t.channels&&t.channels.forEach(e=>{if(!Enumerations.MIDI_CHANNEL_NUMBERS.includes(e))throw new TypeError("MIDI channel must be between 1 and 16.")})),this.destinations=e,t.types&&(this.types=t.types),t.channels&&(this.channels=t.channels)}forward(e){this.suspended||this.types.includes(e.type)&&(e.channel&&!this.channels.includes(e.channel)||this.destinations.forEach(t=>{(!wm.validation||t instanceof Output)&&t.send(e)}))}} -/** - * The `InputChannel` class represents a single MIDI input channel (1-16) from a single input - * device. This object is derived from the host's MIDI subsystem and should not be instantiated - * directly. - * - * All 16 `InputChannel` objects can be found inside the input's [`channels`](Input#channels) - * property. - * - * @fires InputChannel#midimessage - * @fires InputChannel#unknownmessage - * - * @fires InputChannel#noteoff - * @fires InputChannel#noteon - * @fires InputChannel#keyaftertouch - * @fires InputChannel#programchange - * @fires InputChannel#channelaftertouch - * @fires InputChannel#pitchbend - * - * @fires InputChannel#allnotesoff - * @fires InputChannel#allsoundoff - * @fires InputChannel#localcontrol - * @fires InputChannel#monomode - * @fires InputChannel#omnimode - * @fires InputChannel#resetallcontrollers - * - * @fires InputChannel#event:nrpn - * @fires InputChannel#event:nrpn-dataentrycoarse - * @fires InputChannel#event:nrpn-dataentryfine - * @fires InputChannel#event:nrpn-dataincrement - * @fires InputChannel#event:nrpn-datadecrement - * @fires InputChannel#event:rpn - * @fires InputChannel#event:rpn-dataentrycoarse - * @fires InputChannel#event:rpn-dataentryfine - * @fires InputChannel#event:rpn-dataincrement - * @fires InputChannel#event:rpn-datadecrement - * - * @fires InputChannel#controlchange - * @fires InputChannel#event:controlchange-controllerxxx - * @fires InputChannel#event:controlchange-bankselectcoarse - * @fires InputChannel#event:controlchange-modulationwheelcoarse - * @fires InputChannel#event:controlchange-breathcontrollercoarse - * @fires InputChannel#event:controlchange-footcontrollercoarse - * @fires InputChannel#event:controlchange-portamentotimecoarse - * @fires InputChannel#event:controlchange-dataentrycoarse - * @fires InputChannel#event:controlchange-volumecoarse - * @fires InputChannel#event:controlchange-balancecoarse - * @fires InputChannel#event:controlchange-pancoarse - * @fires InputChannel#event:controlchange-expressioncoarse - * @fires InputChannel#event:controlchange-effectcontrol1coarse - * @fires InputChannel#event:controlchange-effectcontrol2coarse - * @fires InputChannel#event:controlchange-generalpurposecontroller1 - * @fires InputChannel#event:controlchange-generalpurposecontroller2 - * @fires InputChannel#event:controlchange-generalpurposecontroller3 - * @fires InputChannel#event:controlchange-generalpurposecontroller4 - * @fires InputChannel#event:controlchange-bankselectfine - * @fires InputChannel#event:controlchange-modulationwheelfine - * @fires InputChannel#event:controlchange-breathcontrollerfine - * @fires InputChannel#event:controlchange-footcontrollerfine - * @fires InputChannel#event:controlchange-portamentotimefine - * @fires InputChannel#event:controlchange-dataentryfine - * @fires InputChannel#event:controlchange-channelvolumefine - * @fires InputChannel#event:controlchange-balancefine - * @fires InputChannel#event:controlchange-panfine - * @fires InputChannel#event:controlchange-expressionfine - * @fires InputChannel#event:controlchange-effectcontrol1fine - * @fires InputChannel#event:controlchange-effectcontrol2fine - * @fires InputChannel#event:controlchange-damperpedal - * @fires InputChannel#event:controlchange-portamento - * @fires InputChannel#event:controlchange-sostenuto - * @fires InputChannel#event:controlchange-softpedal - * @fires InputChannel#event:controlchange-legatopedal - * @fires InputChannel#event:controlchange-hold2 - * @fires InputChannel#event:controlchange-soundvariation - * @fires InputChannel#event:controlchange-resonance - * @fires InputChannel#event:controlchange-releasetime - * @fires InputChannel#event:controlchange-attacktime - * @fires InputChannel#event:controlchange-brightness - * @fires InputChannel#event:controlchange-decaytime - * @fires InputChannel#event:controlchange-vibratorate - * @fires InputChannel#event:controlchange-vibratodepth - * @fires InputChannel#event:controlchange-vibratodelay - * @fires InputChannel#event:controlchange-generalpurposecontroller5 - * @fires InputChannel#event:controlchange-generalpurposecontroller6 - * @fires InputChannel#event:controlchange-generalpurposecontroller7 - * @fires InputChannel#event:controlchange-generalpurposecontroller8 - * @fires InputChannel#event:controlchange-portamentocontrol - * @fires InputChannel#event:controlchange-highresolutionvelocityprefix - * @fires InputChannel#event:controlchange-effect1depth - * @fires InputChannel#event:controlchange-effect2depth - * @fires InputChannel#event:controlchange-effect3depth - * @fires InputChannel#event:controlchange-effect4depth - * @fires InputChannel#event:controlchange-effect5depth - * @fires InputChannel#event:controlchange-dataincrement - * @fires InputChannel#event:controlchange-datadecrement - * @fires InputChannel#event:controlchange-nonregisteredparameterfine - * @fires InputChannel#event:controlchange-nonregisteredparametercoarse - * @fires InputChannel#event:controlchange-registeredparameterfine - * @fires InputChannel#event:controlchange-registeredparametercoarse - * @fires InputChannel#event:controlchange-allsoundoff - * @fires InputChannel#event:controlchange-resetallcontrollers - * @fires InputChannel#event:controlchange-localcontrol - * @fires InputChannel#event:controlchange-allnotesoff - * @fires InputChannel#event:controlchange-omnimodeoff - * @fires InputChannel#event:controlchange-omnimodeon - * @fires InputChannel#event:controlchange-monomodeon - * @fires InputChannel#event:controlchange-polymodeon - * @fires InputChannel#event: - * - * @extends EventEmitter - * @license Apache-2.0 - * @since 3.0.0 - */class InputChannel extends EventEmitter{constructor(e,t){super(),this._input=e,this._number=t,this._octaveOffset=0,this._nrpnBuffer=[],this._rpnBuffer=[],this.parameterNumberEventsEnabled=!0,this.notesState=new Array(128).fill(!1)}destroy(){this._input=null,this._number=null,this._octaveOffset=0,this._nrpnBuffer=[],this.notesState=new Array(128).fill(!1),this.parameterNumberEventsEnabled=!1,this.removeListener()}_processMidiMessageEvent(e){const t=Object.assign({},e);t.port=this.input,t.target=this,t.type="midimessage",this.emit(t.type,t),this._parseEventForStandardMessages(t)}_parseEventForStandardMessages(e){const t=Object.assign({},e);t.type=t.message.type||"unknownmessage";const n=e.message.dataBytes[0],r=e.message.dataBytes[1];if("noteoff"===t.type||"noteon"===t.type&&0===r)this.notesState[n]=!1,t.type="noteoff",t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset),{rawAttack:0,rawRelease:r}),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.velocity=t.note.release,t.rawVelocity=t.note.rawRelease;else if("noteon"===t.type)this.notesState[n]=!0,t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset),{rawAttack:r}),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.velocity=t.note.attack,t.rawVelocity=t.note.rawAttack;else if("keyaftertouch"===t.type)t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset)),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.identifier=t.note.identifier,t.key=t.note.number,t.rawKey=n;else if("controlchange"===t.type){t.controller={number:n,name:Enumerations.CONTROL_CHANGE_MESSAGES[n].name,description:Enumerations.CONTROL_CHANGE_MESSAGES[n].description,position:Enumerations.CONTROL_CHANGE_MESSAGES[n].position},t.subtype=t.controller.name||"controller"+n,t.value=Utilities.from7bitToFloat(r),t.rawValue=r;const e=Object.assign({},t);e.type=`${t.type}-controller${n}`,delete e.subtype,this.emit(e.type,e);const i=Object.assign({},t);i.type=t.type+"-"+Enumerations.CONTROL_CHANGE_MESSAGES[n].name,delete i.subtype,0!==i.type.indexOf("controller")&&this.emit(i.type,i),t.message.dataBytes[0]>=120&&this._parseChannelModeMessage(t),this.parameterNumberEventsEnabled&&this._isRpnOrNrpnController(t.message.dataBytes[0])&&this._parseEventForParameterNumber(t)}else"programchange"===t.type?(t.value=n,t.rawValue=t.value):"channelaftertouch"===t.type?(t.value=Utilities.from7bitToFloat(n),t.rawValue=n):"pitchbend"===t.type?(t.value=((r<<7)+n-8192)/8192,t.rawValue=(r<<7)+n):t.type="unknownmessage";this.emit(t.type,t)}_parseChannelModeMessage(e){const t=Object.assign({},e);t.type=t.controller.name,"localcontrol"===t.type&&(t.value=127===t.message.data[2],t.rawValue=t.message.data[2]),"omnimodeon"===t.type?(t.type="omnimode",t.value=!0,t.rawValue=t.message.data[2]):"omnimodeoff"===t.type&&(t.type="omnimode",t.value=!1,t.rawValue=t.message.data[2]),"monomodeon"===t.type?(t.type="monomode",t.value=!0,t.rawValue=t.message.data[2]):"polymodeon"===t.type&&(t.type="monomode",t.value=!1,t.rawValue=t.message.data[2]),this.emit(t.type,t)}_parseEventForParameterNumber(e){const t=e.message.dataBytes[0],n=e.message.dataBytes[1];99===t||101===t?(this._nrpnBuffer=[],this._rpnBuffer=[],99===t?this._nrpnBuffer=[e.message]:127!==n&&(this._rpnBuffer=[e.message])):98===t||100===t?98===t?(this._rpnBuffer=[],1===this._nrpnBuffer.length?this._nrpnBuffer.push(e.message):this._nrpnBuffer=[]):(this._nrpnBuffer=[],1===this._rpnBuffer.length&&127!==n?this._rpnBuffer.push(e.message):this._rpnBuffer=[]):6!==t&&38!==t&&96!==t&&97!==t||(2===this._rpnBuffer.length?this._dispatchParameterNumberEvent("rpn",this._rpnBuffer[0].dataBytes[1],this._rpnBuffer[1].dataBytes[1],e):2===this._nrpnBuffer.length?this._dispatchParameterNumberEvent("nrpn",this._nrpnBuffer[0].dataBytes[1],this._nrpnBuffer[1].dataBytes[1],e):(this._nrpnBuffer=[],this._rpnBuffer=[]))}_isRpnOrNrpnController(e){return 6===e||38===e||96===e||97===e||98===e||99===e||100===e||101===e}_dispatchParameterNumberEvent(e,t,n,r){e="nrpn"===e?"nrpn":"rpn";const i={target:r.target,timestamp:r.timestamp,message:r.message,parameterMsb:t,parameterLsb:n,value:Utilities.from7bitToFloat(r.message.dataBytes[1]),rawValue:r.message.dataBytes[1]};i.parameter="rpn"===e?Object.keys(Enumerations.REGISTERED_PARAMETERS).find(e=>Enumerations.REGISTERED_PARAMETERS[e][0]===t&&Enumerations.REGISTERED_PARAMETERS[e][1]===n):(t<<7)+n;const s=Enumerations.CONTROL_CHANGE_MESSAGES[r.message.dataBytes[0]].name;i.type=`${e}-${s}`,this.emit(i.type,i);const a=Object.assign({},i);"nrpn-dataincrement"===a.type?a.type="nrpn-databuttonincrement":"nrpn-datadecrement"===a.type?a.type="nrpn-databuttondecrement":"rpn-dataincrement"===a.type?a.type="rpn-databuttonincrement":"rpn-datadecrement"===a.type&&(a.type="rpn-databuttondecrement"),this.emit(a.type,a),i.type=e,i.subtype=s,this.emit(i.type,i)}getChannelModeByNumber(e){return wm.validation&&(console.warn("The 'getChannelModeByNumber()' method has been moved to the 'Utilities' class."),e=Math.floor(e)),Utilities.getChannelModeByNumber(e)}getCcNameByNumber(e){if(wm.validation&&(console.warn("The 'getCcNameByNumber()' method has been moved to the 'Utilities' class."),!((e=parseInt(e))>=0&&e<=127)))throw new RangeError("Invalid control change number.");return Utilities.getCcNameByNumber(e)}getNoteState(e){e instanceof Note&&(e=e.identifier);const t=Utilities.guessNoteNumber(e,wm.octaveOffset+this.input.octaveOffset+this.octaveOffset);return this.notesState[t]}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get input(){return this._input}get number(){return this._number}get nrpnEventsEnabled(){return this.parameterNumberEventsEnabled}set nrpnEventsEnabled(e){this.validation&&(e=!!e),this.parameterNumberEventsEnabled=e}} -/** - * The `Message` class represents a single MIDI message. It has several properties that make it - * easy to make sense of the binary data it contains. - * - * @license Apache-2.0 - * @since 3.0.0 - */class Message{constructor(e){this.rawData=e,this.data=Array.from(this.rawData),this.statusByte=this.rawData[0],this.rawDataBytes=this.rawData.slice(1),this.dataBytes=this.data.slice(1),this.isChannelMessage=!1,this.isSystemMessage=!1,this.command=void 0,this.channel=void 0,this.manufacturerId=void 0,this.type=void 0,this.statusByte<240?(this.isChannelMessage=!0,this.command=this.statusByte>>4,this.channel=1+(15&this.statusByte)):(this.isSystemMessage=!0,this.command=this.statusByte),this.isChannelMessage?this.type=Utilities.getPropertyByValue(Enumerations.CHANNEL_MESSAGES,this.command):this.isSystemMessage&&(this.type=Utilities.getPropertyByValue(Enumerations.SYSTEM_MESSAGES,this.command)),this.statusByte===Enumerations.SYSTEM_MESSAGES.sysex&&(0===this.dataBytes[0]?(this.manufacturerId=this.dataBytes.slice(0,3),this.dataBytes=this.dataBytes.slice(3,this.rawDataBytes.length-1),this.rawDataBytes=this.rawDataBytes.slice(3,this.rawDataBytes.length-1)):(this.manufacturerId=[this.dataBytes[0]],this.dataBytes=this.dataBytes.slice(1,this.dataBytes.length-1),this.rawDataBytes=this.rawDataBytes.slice(1,this.rawDataBytes.length-1)))}} -/** - * The `Input` class represents a single MIDI input port. This object is automatically instantiated - * by the library according to the host's MIDI subsystem and does not need to be directly - * instantiated. Instead, you can access all `Input` objects by referring to the - * [`WebMidi.inputs`](WebMidi#inputs) array. You can also retrieve inputs by using methods such as - * [`WebMidi.getInputByName()`](WebMidi#getInputByName) and - * [`WebMidi.getInputById()`](WebMidi#getInputById). - * - * Note that a single MIDI device may expose several inputs and/or outputs. - * - * **Important**: the `Input` class does not directly fire channel-specific MIDI messages - * (such as [`noteon`](InputChannel#event:noteon) or - * [`controlchange`](InputChannel#event:controlchange), etc.). The [`InputChannel`](InputChannel) - * object does that. However, you can still use the - * [`Input.addListener()`](#addListener) method to listen to channel-specific events on multiple - * [`InputChannel`](InputChannel) objects at once. - * - * @fires Input#opened - * @fires Input#disconnected - * @fires Input#closed - * @fires Input#midimessage - * - * @fires Input#sysex - * @fires Input#timecode - * @fires Input#songposition - * @fires Input#songselect - * @fires Input#tunerequest - * @fires Input#clock - * @fires Input#start - * @fires Input#continue - * @fires Input#stop - * @fires Input#activesensing - * @fires Input#reset - * - * @fires Input#unknownmidimessage - * - * @extends EventEmitter - * @license Apache-2.0 - */class Input extends EventEmitter{constructor(e){super(),this._midiInput=e,this._octaveOffset=0,this.channels=[];for(let e=1;e<=16;e++)this.channels[e]=new InputChannel(this,e);this._forwarders=[],this._midiInput.onstatechange=this._onStateChange.bind(this),this._midiInput.onmidimessage=this._onMidiMessage.bind(this)}async destroy(){this.removeListener(),this.channels.forEach(e=>e.destroy()),this.channels=[],this._forwarders=[],this._midiInput&&(this._midiInput.onstatechange=null,this._midiInput.onmidimessage=null),await this.close(),this._midiInput=null}_onStateChange(e){let t={timestamp:wm.time,target:this,port:this};"open"===e.port.connection?(t.type="opened",this.emit("opened",t)):"closed"===e.port.connection&&"connected"===e.port.state?(t.type="closed",this.emit("closed",t)):"closed"===e.port.connection&&"disconnected"===e.port.state?(t.type="disconnected",t.port={connection:e.port.connection,id:e.port.id,manufacturer:e.port.manufacturer,name:e.port.name,state:e.port.state,type:e.port.type},this.emit("disconnected",t)):"pending"===e.port.connection&&"disconnected"===e.port.state||console.warn("This statechange event was not caught: ",e.port.connection,e.port.state)}_onMidiMessage(e){const t=new Message(e.data),n={port:this,target:this,message:t,timestamp:e.timeStamp,type:"midimessage",data:t.data,rawData:t.data,statusByte:t.data[0],dataBytes:t.dataBytes};this.emit("midimessage",n),t.isSystemMessage?this._parseEvent(n):t.isChannelMessage&&this.channels[t.channel]._processMidiMessageEvent(n),this._forwarders.forEach(e=>e.forward(t))}_parseEvent(e){const t=Object.assign({},e);t.type=t.message.type||"unknownmidimessage","songselect"===t.type&&(t.song=e.data[1]+1,t.value=e.data[1],t.rawValue=t.value),this.emit(t.type,t)}async open(){try{await this._midiInput.open()}catch(e){return Promise.reject(e)}return Promise.resolve(this)}async close(){if(!this._midiInput)return Promise.resolve(this);try{await this._midiInput.close()}catch(e){return Promise.reject(e)}return Promise.resolve(this)}getChannelModeByNumber(){wm.validation&&console.warn("The 'getChannelModeByNumber()' method has been moved to the 'Utilities' class.")}addListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=null!=t?[].concat(t):void 0;t=n,n={channels:e}}if(Enumerations.CHANNEL_EVENTS.includes(e)){void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS);let r=[];return Utilities.sanitizeChannels(n.channels).forEach(i=>{r.push(this.channels[i].addListener(e,t,n))}),r}return super.addListener(e,t,n)}addOneTimeListener(e,t,n={}){return n.remaining=1,this.addListener(e,t,n)}on(e,t,n,r){return this.addListener(e,t,n,r)}hasListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=[].concat(t);t=n,n={channels:e}}return Enumerations.CHANNEL_EVENTS.includes(e)?(void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).every(n=>this.channels[n].hasListener(e,t))):super.hasListener(e,t)}removeListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=[].concat(t);t=n,n={channels:e}}if(void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),null==e)return Utilities.sanitizeChannels(n.channels).forEach(e=>{this.channels[e]&&this.channels[e].removeListener()}),super.removeListener();Enumerations.CHANNEL_EVENTS.includes(e)?Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].removeListener(e,t,n)}):super.removeListener(e,t,n)}addForwarder(e,t={}){let n;return n=e instanceof Forwarder?e:new Forwarder(e,t),this._forwarders.push(n),n}removeForwarder(e){this._forwarders=this._forwarders.filter(t=>t!==e)}hasForwarder(e){return this._forwarders.includes(e)}get name(){return this._midiInput.name}get id(){return this._midiInput.id}get connection(){return this._midiInput.connection}get manufacturer(){return this._midiInput.manufacturer}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get state(){return this._midiInput.state}get type(){return this._midiInput.type}get nrpnEventsEnabled(){return wm.validation&&console.warn("The 'nrpnEventsEnabled' property has been moved to the 'InputChannel' class."),!1}}if(Utilities.isNode){try{window.navigator}catch(err){let jzz;eval('jzz = require("jzz")'),global.navigator||(global.navigator={}),Object.assign(global.navigator,jzz)}try{performance}catch(err){let performance;eval('performance = require("perf_hooks").performance'),global.performance=performance}} -/** - * The `WebMidi` object makes it easier to work with the low-level Web MIDI API. Basically, it - * simplifies sending outgoing MIDI messages and reacting to incoming MIDI messages. - * - * When using the WebMidi.js library, you should know that the `WebMidi` class has already been - * instantiated. You cannot instantiate it yourself. If you use the **IIFE** version, you should - * simply use the global object called `WebMidi`. If you use the **CJS** (CommonJS) or **ESM** (ES6 - * module) version, you get an already-instantiated object when you import the module. - * - * @fires WebMidi#connected - * @fires WebMidi#disabled - * @fires WebMidi#disconnected - * @fires WebMidi#enabled - * @fires WebMidi#error - * @fires WebMidi#midiaccessgranted - * @fires WebMidi#portschanged - * - * @extends EventEmitter - * @license Apache-2.0 - */class WebMidi extends EventEmitter{constructor(){super(),this.defaults={note:{attack:Utilities.from7bitToFloat(64),release:Utilities.from7bitToFloat(64),duration:1/0}},this.interface=null,this.validation=!0,this._inputs=[],this._disconnectedInputs=[],this._outputs=[],this._disconnectedOutputs=[],this._stateChangeQueue=[],this._octaveOffset=0}async enable(e={},t=!1){if(this.validation=!1!==e.validation,this.validation&&("function"==typeof e&&(e={callback:e,sysex:t}),t&&(e.sysex=!0)),this.enabled)return"function"==typeof e.callback&&e.callback(),Promise.resolve();const n={timestamp:this.time,target:this,type:"error",error:void 0},r={timestamp:this.time,target:this,type:"midiaccessgranted"},i={timestamp:this.time,target:this,type:"enabled"};try{"function"==typeof e.requestMIDIAccessFunction?this.interface=await e.requestMIDIAccessFunction({sysex:e.sysex,software:e.software}):this.interface=await navigator.requestMIDIAccess({sysex:e.sysex,software:e.software})}catch(t){return n.error=t,this.emit("error",n),"function"==typeof e.callback&&e.callback(t),Promise.reject(t)}this.emit("midiaccessgranted",r),this.interface.onstatechange=this._onInterfaceStateChange.bind(this);try{await this._updateInputsAndOutputs()}catch(t){return n.error=t,this.emit("error",n),"function"==typeof e.callback&&e.callback(t),Promise.reject(t)}return this.emit("enabled",i),"function"==typeof e.callback&&e.callback(),Promise.resolve(this)}async disable(){return this.interface&&(this.interface.onstatechange=void 0),this._destroyInputsAndOutputs().then(()=>{navigator&&"function"==typeof navigator.close&&navigator.close(),this.interface=null;let e={timestamp:this.time,target:this,type:"disabled"};this.emit("disabled",e),this.removeListener()})}getInputById(e,t={disconnected:!1}){if(this.validation){if(!this.enabled)throw new Error("WebMidi is not enabled.");if(!e)return}if(t.disconnected){for(let t=0;t=0&&e<=127&&Utilities.getNoteDetails(Utilities.offsetNumber(e,this.octaveOffset)).octave}sanitizeChannels(e){return this.validation&&console.warn("The sanitizeChannels() method has been moved to the utilities class."),Utilities.sanitizeChannels(e)}toMIDIChannels(e){return this.validation&&console.warn("The toMIDIChannels() method has been deprecated. Use Utilities.sanitizeChannels() instead."),Utilities.sanitizeChannels(e)}guessNoteNumber(e){return this.validation&&console.warn("The guessNoteNumber() method has been deprecated. Use Utilities.guessNoteNumber() instead."),Utilities.guessNoteNumber(e,this.octaveOffset)}getValidNoteArray(e,t={}){return this.validation&&console.warn("The getValidNoteArray() method has been moved to the Utilities.buildNoteArray()"),Utilities.buildNoteArray(e,t)}convertToTimestamp(e){return this.validation&&console.warn("The convertToTimestamp() method has been moved to Utilities.toTimestamp()."),Utilities.toTimestamp(e)}async _destroyInputsAndOutputs(){let e=[];return this.inputs.forEach(t=>e.push(t.destroy())),this.outputs.forEach(t=>e.push(t.destroy())),Promise.all(e).then(()=>{this._inputs=[],this._outputs=[]})}_onInterfaceStateChange(e){this._updateInputsAndOutputs();let t={timestamp:e.timeStamp,type:e.port.state,target:this};if("connected"===e.port.state&&"open"===e.port.connection){"output"===e.port.type?t.port=this.getOutputById(e.port.id):"input"===e.port.type&&(t.port=this.getInputById(e.port.id)),this.emit(e.port.state,t);const n=Object.assign({},t);n.type="portschanged",this.emit(n.type,n)}else if("disconnected"===e.port.state&&"pending"===e.port.connection){"input"===e.port.type?t.port=this.getInputById(e.port.id,{disconnected:!0}):"output"===e.port.type&&(t.port=this.getOutputById(e.port.id,{disconnected:!0})),this.emit(e.port.state,t);const n=Object.assign({},t);n.type="portschanged",this.emit(n.type,n)}}async _updateInputsAndOutputs(){return Promise.all([this._updateInputs(),this._updateOutputs()])}async _updateInputs(){if(!this.interface)return;for(let e=this._inputs.length-1;e>=0;e--){const t=this._inputs[e];Array.from(this.interface.inputs.values()).find(e=>e===t._midiInput)||(this._disconnectedInputs.push(t),this._inputs.splice(e,1))}let e=[];return this.interface.inputs.forEach(t=>{if(!this._inputs.find(e=>e._midiInput===t)){let n=this._disconnectedInputs.find(e=>e._midiInput===t);n||(n=new Input(t)),this._inputs.push(n),e.push(n.open())}}),Promise.all(e)}async _updateOutputs(){if(!this.interface)return;for(let e=this._outputs.length-1;e>=0;e--){const t=this._outputs[e];Array.from(this.interface.outputs.values()).find(e=>e===t._midiOutput)||(this._disconnectedOutputs.push(t),this._outputs.splice(e,1))}let e=[];return this.interface.outputs.forEach(t=>{if(!this._outputs.find(e=>e._midiOutput===t)){let n=this._disconnectedOutputs.find(e=>e._midiOutput===t);n||(n=new Output(t)),this._outputs.push(n),e.push(n.open())}}),Promise.all(e)}get enabled(){return null!==this.interface}get inputs(){return this._inputs}get isNode(){return this.validation&&console.warn("WebMidi.isNode has been deprecated. Use Utilities.isNode instead."),Utilities.isNode}get isBrowser(){return this.validation&&console.warn("WebMidi.isBrowser has been deprecated. Use Utilities.isBrowser instead."),Utilities.isBrowser}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get outputs(){return this._outputs}get supported(){return"undefined"!=typeof navigator&&!!navigator.requestMIDIAccess}get sysexEnabled(){return!(!this.interface||!this.interface.sysexEnabled)}get time(){return performance.now()}get version(){return"3.1.12"}get flavour(){return"cjs"}get CHANNEL_EVENTS(){return this.validation&&console.warn("The CHANNEL_EVENTS enum has been moved to Enumerations.CHANNEL_EVENTS."),Enumerations.CHANNEL_EVENTS}get MIDI_SYSTEM_MESSAGES(){return this.validation&&console.warn("The MIDI_SYSTEM_MESSAGES enum has been moved to Enumerations.SYSTEM_MESSAGES."),Enumerations.SYSTEM_MESSAGES}get MIDI_CHANNEL_MODE_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MODE_MESSAGES enum has been moved to Enumerations.CHANNEL_MODE_MESSAGES."),Enumerations.CHANNEL_MODE_MESSAGES}get MIDI_CONTROL_CHANGE_MESSAGES(){return this.validation&&console.warn("The MIDI_CONTROL_CHANGE_MESSAGES enum has been replaced by the Enumerations.CONTROL_CHANGE_MESSAGES array."),Enumerations.MIDI_CONTROL_CHANGE_MESSAGES}get MIDI_REGISTERED_PARAMETER(){return this.validation&&console.warn("The MIDI_REGISTERED_PARAMETER enum has been moved to Enumerations.REGISTERED_PARAMETERS."),Enumerations.REGISTERED_PARAMETERS}get NOTES(){return this.validation&&console.warn("The NOTES enum has been deprecated."),["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]}}const wm=new WebMidi;wm.constructor=null,exports.Enumerations=Enumerations,exports.Forwarder=Forwarder,exports.Input=Input,exports.InputChannel=InputChannel,exports.Message=Message,exports.Note=Note,exports.Output=Output,exports.OutputChannel=OutputChannel,exports.Utilities=Utilities,exports.WebMidi=wm; -//# sourceMappingURL=webmidi.cjs.min.js.map +function entryMapper(v, k) { + return [k, v]; +} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(31))) +function not(predicate) { + return function () { + return !predicate.apply(this, arguments); + }; +} -/***/ }), -/* 31 */ -/***/ (function(module, exports) { +function neg(predicate) { + return function () { + return -predicate.apply(this, arguments); + }; +} -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; +function defaultZipper() { + return arrCopy(arguments); +} +function defaultNegComparator(a, b) { + return a < b ? 1 : a > b ? -1 : 0; +} -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { +function hashCollection(collection) { + if (collection.size === Infinity) { + return 0; + } + var ordered = isOrdered(collection); + var keyed = isKeyed(collection); + var h = ordered ? 1 : 0; -"use strict"; + collection.__iterate( + keyed + ? ordered + ? function (v, k) { + h = (31 * h + hashMerge(hash(v), hash(k))) | 0; + } + : function (v, k) { + h = (h + hashMerge(hash(v), hash(k))) | 0; + } + : ordered + ? function (v) { + h = (31 * h + hash(v)) | 0; + } + : function (v) { + h = (h + hash(v)) | 0; + } + ); -var globalThis = __webpack_require__(35); -var getOwnPropertyDescriptor = __webpack_require__(63).f; -var createNonEnumerableProperty = __webpack_require__(59); -var defineBuiltIn = __webpack_require__(49); -var defineGlobalProperty = __webpack_require__(181); -var copyConstructorProperties = __webpack_require__(110); -var isForced = __webpack_require__(132); + return murmurHashOfSize(collection.size, h); +} -/* - options.target - name of the target object - options.global - target is the global object - options.stat - export as static methods of target - options.proto - export as prototype methods of target - options.real - real prototype method for the `pure` version - options.forced - export even if the native feature is available - options.bind - bind methods to the target, required for the `pure` version - options.wrap - wrap constructors to preventing global pollution, required for the `pure` version - options.unsafe - use the simple assignment of property instead of delete + defineProperty - options.sham - add a flag to not completely full polyfills - options.enumerable - export as enumerable property - options.dontCallGetSet - prevent calling a getter on target - options.name - the .name of the function if it does not match the key -*/ -module.exports = function (options, source) { - var TARGET = options.target; - var GLOBAL = options.global; - var STATIC = options.stat; - var FORCED, target, key, targetProperty, sourceProperty, descriptor; - if (GLOBAL) { - target = globalThis; - } else if (STATIC) { - target = globalThis[TARGET] || defineGlobalProperty(TARGET, {}); - } else { - target = globalThis[TARGET] && globalThis[TARGET].prototype; +function murmurHashOfSize(size, h) { + h = imul(h, 0xcc9e2d51); + h = imul((h << 15) | (h >>> -15), 0x1b873593); + h = imul((h << 13) | (h >>> -13), 5); + h = ((h + 0xe6546b64) | 0) ^ size; + h = imul(h ^ (h >>> 16), 0x85ebca6b); + h = imul(h ^ (h >>> 13), 0xc2b2ae35); + h = smi(h ^ (h >>> 16)); + return h; +} + +function hashMerge(a, b) { + return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int +} + +var OrderedSet = /*@__PURE__*/(function (Set) { + function OrderedSet(value) { + // eslint-disable-next-line no-constructor-return + return value === undefined || value === null + ? emptyOrderedSet() + : isOrderedSet(value) + ? value + : emptyOrderedSet().withMutations(function (set) { + var iter = SetCollection(value); + assertNotInfinite(iter.size); + iter.forEach(function (v) { return set.add(v); }); + }); } - if (target) for (key in source) { - sourceProperty = source[key]; - if (options.dontCallGetSet) { - descriptor = getOwnPropertyDescriptor(target, key); - targetProperty = descriptor && descriptor.value; - } else targetProperty = target[key]; - FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); - // contained in target - if (!FORCED && targetProperty !== undefined) { - if (typeof sourceProperty == typeof targetProperty) continue; - copyConstructorProperties(sourceProperty, targetProperty); + + if ( Set ) OrderedSet.__proto__ = Set; + OrderedSet.prototype = Object.create( Set && Set.prototype ); + OrderedSet.prototype.constructor = OrderedSet; + + OrderedSet.of = function of (/*...values*/) { + return this(arguments); + }; + + OrderedSet.fromKeys = function fromKeys (value) { + return this(KeyedCollection(value).keySeq()); + }; + + OrderedSet.prototype.toString = function toString () { + return this.__toString('OrderedSet {', '}'); + }; + + return OrderedSet; +}(Set)); + +OrderedSet.isOrderedSet = isOrderedSet; + +var OrderedSetPrototype = OrderedSet.prototype; +OrderedSetPrototype[IS_ORDERED_SYMBOL] = true; +OrderedSetPrototype.zip = IndexedCollectionPrototype.zip; +OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith; +OrderedSetPrototype.zipAll = IndexedCollectionPrototype.zipAll; + +OrderedSetPrototype.__empty = emptyOrderedSet; +OrderedSetPrototype.__make = makeOrderedSet; + +function makeOrderedSet(map, ownerID) { + var set = Object.create(OrderedSetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; +} + +var EMPTY_ORDERED_SET; +function emptyOrderedSet() { + return ( + EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())) + ); +} + +var PairSorting = { + LeftThenRight: -1, + RightThenLeft: 1, +}; + +function throwOnInvalidDefaultValues(defaultValues) { + if (isRecord(defaultValues)) { + throw new Error( + 'Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.' + ); + } + + if (isImmutable(defaultValues)) { + throw new Error( + 'Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.' + ); + } + + if (defaultValues === null || typeof defaultValues !== 'object') { + throw new Error( + 'Can not call `Record` with a non-object as default values. Use a plain javascript object instead.' + ); + } +} + +var Record = function Record(defaultValues, name) { + var hasInitialized; + + throwOnInvalidDefaultValues(defaultValues); + + var RecordType = function Record(values) { + var this$1$1 = this; + + if (values instanceof RecordType) { + return values; } - // add a flag to not completely full polyfills - if (options.sham || (targetProperty && targetProperty.sham)) { - createNonEnumerableProperty(sourceProperty, 'sham', true); + if (!(this instanceof RecordType)) { + return new RecordType(values); } - defineBuiltIn(target, key, sourceProperty, options); + if (!hasInitialized) { + hasInitialized = true; + var keys = Object.keys(defaultValues); + var indices = (RecordTypePrototype._indices = {}); + // Deprecated: left to attempt not to break any external code which + // relies on a ._name property existing on record instances. + // Use Record.getDescriptiveName() instead + RecordTypePrototype._name = name; + RecordTypePrototype._keys = keys; + RecordTypePrototype._defaultValues = defaultValues; + for (var i = 0; i < keys.length; i++) { + var propName = keys[i]; + indices[propName] = i; + if (RecordTypePrototype[propName]) { + /* eslint-disable no-console */ + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + typeof console === 'object' && + console.warn && + console.warn( + 'Cannot define ' + + recordName(this) + + ' with property "' + + propName + + '" since that property name is part of the Record API.' + ); + /* eslint-enable no-console */ + } else { + setProp(RecordTypePrototype, propName); + } + } + } + this.__ownerID = undefined; + this._values = List().withMutations(function (l) { + l.setSize(this$1$1._keys.length); + KeyedCollection(values).forEach(function (v, k) { + l.set(this$1$1._indices[k], v === this$1$1._defaultValues[k] ? undefined : v); + }); + }); + return this; + }; + + var RecordTypePrototype = (RecordType.prototype = + Object.create(RecordPrototype)); + RecordTypePrototype.constructor = RecordType; + + if (name) { + RecordType.displayName = name; } + + // eslint-disable-next-line no-constructor-return + return RecordType; }; +Record.prototype.toString = function toString () { + var str = recordName(this) + ' { '; + var keys = this._keys; + var k; + for (var i = 0, l = keys.length; i !== l; i++) { + k = keys[i]; + str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k)); + } + return str + ' }'; +}; -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { +Record.prototype.equals = function equals (other) { + return ( + this === other || + (isRecord(other) && recordSeq(this).equals(recordSeq(other))) + ); +}; -"use strict"; +Record.prototype.hashCode = function hashCode () { + return recordSeq(this).hashCode(); +}; -module.exports = function (exec) { - try { - return !!exec(); - } catch (error) { - return true; +// @pragma Access + +Record.prototype.has = function has (k) { + return this._indices.hasOwnProperty(k); +}; + +Record.prototype.get = function get (k, notSetValue) { + if (!this.has(k)) { + return notSetValue; } + var index = this._indices[k]; + var value = this._values.get(index); + return value === undefined ? this._defaultValues[k] : value; }; +// @pragma Modification -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { +Record.prototype.set = function set (k, v) { + if (this.has(k)) { + var newValues = this._values.set( + this._indices[k], + v === this._defaultValues[k] ? undefined : v + ); + if (newValues !== this._values && !this.__ownerID) { + return makeRecord(this, newValues); + } + } + return this; +}; -"use strict"; +Record.prototype.remove = function remove (k) { + return this.set(k); +}; -var NATIVE_BIND = __webpack_require__(130); +Record.prototype.clear = function clear () { + var newValues = this._values.clear().setSize(this._keys.length); -var FunctionPrototype = Function.prototype; -var call = FunctionPrototype.call; -// eslint-disable-next-line es/no-function-prototype-bind -- safe -var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); + return this.__ownerID ? this : makeRecord(this, newValues); +}; -module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) { - return function () { - return call.apply(fn, arguments); - }; +Record.prototype.wasAltered = function wasAltered () { + return this._values.wasAltered(); }; +Record.prototype.toSeq = function toSeq () { + return recordSeq(this); +}; -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { +Record.prototype.toJS = function toJS$1 () { + return toJS(this); +}; -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { -var check = function (it) { - return it && it.Math === Math && it; +Record.prototype.entries = function entries () { + return this.__iterator(ITERATE_ENTRIES); }; -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -module.exports = - // eslint-disable-next-line es/no-global-this -- safe - check(typeof globalThis == 'object' && globalThis) || - check(typeof window == 'object' && window) || - // eslint-disable-next-line no-restricted-globals -- safe - check(typeof self == 'object' && self) || - check(typeof global == 'object' && global) || - check(typeof this == 'object' && this) || - // eslint-disable-next-line no-new-func -- fallback - (function () { return this; })() || Function('return this')(); +Record.prototype.__iterator = function __iterator (type, reverse) { + return recordSeq(this).__iterator(type, reverse); +}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) +Record.prototype.__iterate = function __iterate (fn, reverse) { + return recordSeq(this).__iterate(fn, reverse); +}; -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { +Record.prototype.__ensureOwner = function __ensureOwner (ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newValues = this._values.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._values = newValues; + return this; + } + return makeRecord(this, newValues, ownerID); +}; -"use strict"; +Record.isRecord = isRecord; +Record.getDescriptiveName = recordName; +var RecordPrototype = Record.prototype; +RecordPrototype[IS_RECORD_SYMBOL] = true; +RecordPrototype[DELETE] = RecordPrototype.remove; +RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn; +RecordPrototype.getIn = getIn; +RecordPrototype.hasIn = CollectionPrototype.hasIn; +RecordPrototype.merge = merge$1; +RecordPrototype.mergeWith = mergeWith$1; +RecordPrototype.mergeIn = mergeIn; +RecordPrototype.mergeDeep = mergeDeep; +RecordPrototype.mergeDeepWith = mergeDeepWith; +RecordPrototype.mergeDeepIn = mergeDeepIn; +RecordPrototype.setIn = setIn; +RecordPrototype.update = update; +RecordPrototype.updateIn = updateIn; +RecordPrototype.withMutations = withMutations; +RecordPrototype.asMutable = asMutable; +RecordPrototype.asImmutable = asImmutable; +RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries; +RecordPrototype.toJSON = RecordPrototype.toObject = + CollectionPrototype.toObject; +RecordPrototype.inspect = RecordPrototype.toSource = function () { + return this.toString(); +}; -var NATIVE_BIND = __webpack_require__(130); +function makeRecord(likeRecord, values, ownerID) { + var record = Object.create(Object.getPrototypeOf(likeRecord)); + record._values = values; + record.__ownerID = ownerID; + return record; +} -var call = Function.prototype.call; -// eslint-disable-next-line es/no-function-prototype-bind -- safe -module.exports = NATIVE_BIND ? call.bind(call) : function () { - return call.apply(call, arguments); -}; +function recordName(record) { + return record.constructor.displayName || record.constructor.name || 'Record'; +} +function recordSeq(record) { + return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; })); +} -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { +function setProp(prototype, name) { + try { + Object.defineProperty(prototype, name, { + get: function () { + return this.get(name); + }, + set: function (value) { + invariant(this.__ownerID, 'Cannot set on an immutable record.'); + this.set(name, value); + }, + }); + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO enable eslint here + } catch (error) { + // Object.defineProperty failed. Probably IE8. + } +} -"use strict"; +/** + * Returns a lazy Seq of `value` repeated `times` times. When `times` is + * undefined, returns an infinite sequence of `value`. + */ +var Repeat = /*@__PURE__*/(function (IndexedSeq) { + function Repeat(value, times) { + if (!(this instanceof Repeat)) { + // eslint-disable-next-line no-constructor-return + return new Repeat(value, times); + } + this._value = value; + this.size = times === undefined ? Infinity : Math.max(0, times); + if (this.size === 0) { + if (EMPTY_REPEAT) { + // eslint-disable-next-line no-constructor-return + return EMPTY_REPEAT; + } + // eslint-disable-next-line @typescript-eslint/no-this-alias + EMPTY_REPEAT = this; + } + } + + if ( IndexedSeq ) Repeat.__proto__ = IndexedSeq; + Repeat.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); + Repeat.prototype.constructor = Repeat; -var isObject = __webpack_require__(40); + Repeat.prototype.toString = function toString () { + if (this.size === 0) { + return 'Repeat []'; + } + return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }; -var $String = String; -var $TypeError = TypeError; + Repeat.prototype.get = function get (index, notSetValue) { + return this.has(index) ? this._value : notSetValue; + }; -// `Assert: Type(argument) is Object` -module.exports = function (argument) { - if (isObject(argument)) return argument; - throw new $TypeError($String(argument) + ' is not an object'); -}; + Repeat.prototype.includes = function includes (searchValue) { + return is(this._value, searchValue); + }; + + Repeat.prototype.slice = function slice (begin, end) { + var size = this.size; + return wholeSlice(begin, end, size) + ? this + : new Repeat( + this._value, + resolveEnd(end, size) - resolveBegin(begin, size) + ); + }; + Repeat.prototype.reverse = function reverse () { + return this; + }; -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { + Repeat.prototype.indexOf = function indexOf (searchValue) { + if (is(this._value, searchValue)) { + return 0; + } + return -1; + }; -"use strict"; + Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) { + if (is(this._value, searchValue)) { + return this.size; + } + return -1; + }; -var fails = __webpack_require__(33); + Repeat.prototype.__iterate = function __iterate (fn, reverse) { + var size = this.size; + var i = 0; + while (i !== size) { + if (fn(this._value, reverse ? size - ++i : i++, this) === false) { + break; + } + } + return i; + }; -// Detect IE8's incomplete defineProperty implementation -module.exports = !fails(function () { - // eslint-disable-next-line es/no-object-defineproperty -- required for testing - return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7; -}); + Repeat.prototype.__iterator = function __iterator (type, reverse) { + var this$1$1 = this; + var size = this.size; + var i = 0; + return new Iterator(function () { return i === size + ? iteratorDone() + : iteratorValue(type, reverse ? size - ++i : i++, this$1$1._value); } + ); + }; -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { + Repeat.prototype.equals = function equals (other) { + return other instanceof Repeat + ? is(this._value, other._value) + : deepEqual(this, other); + }; -"use strict"; + return Repeat; +}(IndexedSeq)); -var globalThis = __webpack_require__(35); -var shared = __webpack_require__(123); -var hasOwn = __webpack_require__(45); -var uid = __webpack_require__(126); -var NATIVE_SYMBOL = __webpack_require__(125); -var USE_SYMBOL_AS_UID = __webpack_require__(278); +var EMPTY_REPEAT; -var Symbol = globalThis.Symbol; -var WellKnownSymbolsStore = shared('wks'); -var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid; +function fromJS(value, converter) { + return fromJSWith( + [], + converter || defaultConverter, + value, + '', + converter && converter.length > 2 ? [] : undefined, + { '': value } + ); +} -module.exports = function (name) { - if (!hasOwn(WellKnownSymbolsStore, name)) { - WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name) - ? Symbol[name] - : createWellKnownSymbol('Symbol.' + name); - } return WellKnownSymbolsStore[name]; -}; +function fromJSWith(stack, converter, value, key, keyPath, parentValue) { + if ( + typeof value !== 'string' && + !isImmutable(value) && + (isArrayLike(value) || hasIterator(value) || isPlainObject(value)) + ) { + if (~stack.indexOf(value)) { + throw new TypeError('Cannot convert circular structure to Immutable'); + } + stack.push(value); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + keyPath && key !== '' && keyPath.push(key); + var converted = converter.call( + parentValue, + key, + Seq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); } + ), + keyPath && keyPath.slice() + ); + stack.pop(); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here + keyPath && keyPath.pop(); + return converted; + } + return value; +} +function defaultConverter(k, v) { + // Effectively the opposite of "Collection.toSeq()" + return isIndexed(v) ? v.toList() : isKeyed(v) ? v.toMap() : v.toSet(); +} -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { +var version = "5.1.3"; -"use strict"; +// Note: Iterable is deprecated +var Iterable = Collection; -var isCallable = __webpack_require__(46); -module.exports = function (it) { - return typeof it == 'object' ? it !== null : isCallable(it); -}; /***/ }), -/* 41 */ +/* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var classof = __webpack_require__(79); - -var $String = String; +var classof = __webpack_require__(32); -module.exports = function (argument) { - if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string'); - return $String(argument); +// `IsArray` abstract operation +// https://tc39.es/ecma262/#sec-isarray +// eslint-disable-next-line es/no-array-isarray -- safe +module.exports = Array.isArray || function isArray(argument) { + return classof(argument) === 'Array'; }; /***/ }), -/* 42 */ +/* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isCallable = __webpack_require__(46); -var tryToString = __webpack_require__(109); - -var $TypeError = TypeError; +var toPrimitive = __webpack_require__(140); +var isSymbol = __webpack_require__(73); -// `Assert: IsCallable(argument) is true` +// `ToPropertyKey` abstract operation +// https://tc39.es/ecma262/#sec-topropertykey module.exports = function (argument) { - if (isCallable(argument)) return argument; - throw new $TypeError(tryToString(argument) + ' is not a function'); + var key = toPrimitive(argument, 'string'); + return isSymbol(key) ? key : key + ''; }; /***/ }), -/* 43 */ +/* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var isCallable = __webpack_require__(46); - -var aFunction = function (argument) { - return isCallable(argument) ? argument : undefined; -}; +var has = __webpack_require__(50).has; -module.exports = function (namespace, method) { - return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method]; +// Perform ? RequireInternalSlot(M, [[SetData]]) +module.exports = function (it) { + has(it); + return it; }; /***/ }), -/* 44 */ +/* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NATIVE_ARRAY_BUFFER = __webpack_require__(140); -var DESCRIPTORS = __webpack_require__(38); -var globalThis = __webpack_require__(35); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var hasOwn = __webpack_require__(45); -var classof = __webpack_require__(79); -var tryToString = __webpack_require__(109); -var createNonEnumerableProperty = __webpack_require__(59); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltInAccessor = __webpack_require__(55); -var isPrototypeOf = __webpack_require__(68); -var getPrototypeOf = __webpack_require__(67); -var setPrototypeOf = __webpack_require__(81); -var wellKnownSymbol = __webpack_require__(39); -var uid = __webpack_require__(126); -var InternalStateModule = __webpack_require__(53); - -var enforceInternalState = InternalStateModule.enforce; -var getInternalState = InternalStateModule.get; -var Int8Array = globalThis.Int8Array; -var Int8ArrayPrototype = Int8Array && Int8Array.prototype; -var Uint8ClampedArray = globalThis.Uint8ClampedArray; -var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; -var TypedArray = Int8Array && getPrototypeOf(Int8Array); -var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); -var ObjectPrototype = Object.prototype; -var TypeError = globalThis.TypeError; - -var TO_STRING_TAG = wellKnownSymbol('toStringTag'); -var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); -var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor'; -// Fixing native typed arrays in Opera Presto crashes the browser, see #595 -var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== 'Opera'; -var TYPED_ARRAY_TAG_REQUIRED = false; -var NAME, Constructor, Prototype; - -var TypedArrayConstructorsList = { - Int8Array: 1, - Uint8Array: 1, - Uint8ClampedArray: 1, - Int16Array: 2, - Uint16Array: 2, - Int32Array: 4, - Uint32Array: 4, - Float32Array: 4, - Float64Array: 8 -}; - -var BigIntArrayConstructorsList = { - BigInt64Array: 8, - BigUint64Array: 8 -}; - -var isView = function isView(it) { - if (!isObject(it)) return false; - var klass = classof(it); - return klass === 'DataView' - || hasOwn(TypedArrayConstructorsList, klass) - || hasOwn(BigIntArrayConstructorsList, klass); -}; - -var getTypedArrayConstructor = function (it) { - var proto = getPrototypeOf(it); - if (!isObject(proto)) return; - var state = getInternalState(proto); - return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto); -}; - -var isTypedArray = function (it) { - if (!isObject(it)) return false; - var klass = classof(it); - return hasOwn(TypedArrayConstructorsList, klass) - || hasOwn(BigIntArrayConstructorsList, klass); -}; - -var aTypedArray = function (it) { - if (isTypedArray(it)) return it; - throw new TypeError('Target is not a typed array'); -}; - -var aTypedArrayConstructor = function (C) { - if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C; - throw new TypeError(tryToString(C) + ' is not a typed array constructor'); -}; - -var exportTypedArrayMethod = function (KEY, property, forced, options) { - if (!DESCRIPTORS) return; - if (forced) for (var ARRAY in TypedArrayConstructorsList) { - var TypedArrayConstructor = globalThis[ARRAY]; - if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try { - delete TypedArrayConstructor.prototype[KEY]; - } catch (error) { - // old WebKit bug - some methods are non-configurable - try { - TypedArrayConstructor.prototype[KEY] = property; - } catch (error2) { /* empty */ } - } - } - if (!TypedArrayPrototype[KEY] || forced) { - defineBuiltIn(TypedArrayPrototype, KEY, forced ? property - : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options); - } -}; - -var exportTypedArrayStaticMethod = function (KEY, property, forced) { - var ARRAY, TypedArrayConstructor; - if (!DESCRIPTORS) return; - if (setPrototypeOf) { - if (forced) for (ARRAY in TypedArrayConstructorsList) { - TypedArrayConstructor = globalThis[ARRAY]; - if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try { - delete TypedArrayConstructor[KEY]; - } catch (error) { /* empty */ } - } - if (!TypedArray[KEY] || forced) { - // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable - try { - return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property); - } catch (error) { /* empty */ } - } else return; - } - for (ARRAY in TypedArrayConstructorsList) { - TypedArrayConstructor = globalThis[ARRAY]; - if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { - defineBuiltIn(TypedArrayConstructor, KEY, property); - } - } -}; - -for (NAME in TypedArrayConstructorsList) { - Constructor = globalThis[NAME]; - Prototype = Constructor && Constructor.prototype; - if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; - else NATIVE_ARRAY_BUFFER_VIEWS = false; -} - -for (NAME in BigIntArrayConstructorsList) { - Constructor = globalThis[NAME]; - Prototype = Constructor && Constructor.prototype; - if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; -} - -// WebKit bug - typed arrays constructors prototype is Object.prototype -if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) { - // eslint-disable-next-line no-shadow -- safe - TypedArray = function TypedArray() { - throw new TypeError('Incorrect invocation'); - }; - if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { - if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray); - } -} - -if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { - TypedArrayPrototype = TypedArray.prototype; - if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { - if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype); - } -} - -// WebKit bug - one more object in Uint8ClampedArray prototype chain -if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { - setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); -} - -if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) { - TYPED_ARRAY_TAG_REQUIRED = true; - defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, { - configurable: true, - get: function () { - return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; - } - }); - for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) { - createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME); - } -} - -module.exports = { - NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, - TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG, - aTypedArray: aTypedArray, - aTypedArrayConstructor: aTypedArrayConstructor, - exportTypedArrayMethod: exportTypedArrayMethod, - exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, - getTypedArrayConstructor: getTypedArrayConstructor, - isView: isView, - isTypedArray: isTypedArray, - TypedArray: TypedArray, - TypedArrayPrototype: TypedArrayPrototype +// `CreateIterResultObject` abstract operation +// https://tc39.es/ecma262/#sec-createiterresultobject +module.exports = function (value, done) { + return { value: value, done: done }; }; /***/ }), -/* 45 */ +/* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var toObject = __webpack_require__(47); - -var hasOwnProperty = uncurryThis({}.hasOwnProperty); +var $TypeError = TypeError; +var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991 -// `HasOwnProperty` abstract operation -// https://tc39.es/ecma262/#sec-hasownproperty -// eslint-disable-next-line es/no-object-hasown -- safe -module.exports = Object.hasOwn || function hasOwn(it, key) { - return hasOwnProperty(toObject(it), key); +module.exports = function (it) { + if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded'); + return it; }; /***/ }), -/* 46 */ +/* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot -var documentAll = typeof document == 'object' && document.all; +var classofRaw = __webpack_require__(32); +var uncurryThis = __webpack_require__(2); -// `IsCallable` abstract operation -// https://tc39.es/ecma262/#sec-iscallable -// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing -module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) { - return typeof argument == 'function' || argument === documentAll; -} : function (argument) { - return typeof argument == 'function'; +module.exports = function (fn) { + // Nashorn bug: + // https://github.com/zloirock/core-js/issues/1128 + // https://github.com/zloirock/core-js/issues/1130 + if (classofRaw(fn) === 'Function') return uncurryThis(fn); }; /***/ }), -/* 47 */ +/* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var requireObjectCoercible = __webpack_require__(52); +var classof = __webpack_require__(47); +var getMethod = __webpack_require__(28); +var isNullOrUndefined = __webpack_require__(57); +var Iterators = __webpack_require__(102); +var wellKnownSymbol = __webpack_require__(7); -var $Object = Object; +var ITERATOR = wellKnownSymbol('iterator'); -// `ToObject` abstract operation -// https://tc39.es/ecma262/#sec-toobject -module.exports = function (argument) { - return $Object(requireObjectCoercible(argument)); +module.exports = function (it) { + if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR) + || getMethod(it, '@@iterator') + || Iterators[classof(it)]; }; /***/ }), -/* 48 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = false; - +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var call = __webpack_require__(4); +var toIntegerOrInfinity = __webpack_require__(22); +var getIteratorDirect = __webpack_require__(33); -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { +var INVALID_SIZE = 'Invalid size'; +var $RangeError = RangeError; +var $TypeError = TypeError; +var max = Math.max; -"use strict"; +var SetRecord = function (set, intSize) { + this.set = set; + this.size = max(intSize, 0); + this.has = aCallable(set.has); + this.keys = aCallable(set.keys); +}; -var isCallable = __webpack_require__(46); -var definePropertyModule = __webpack_require__(51); -var makeBuiltIn = __webpack_require__(191); -var defineGlobalProperty = __webpack_require__(181); +SetRecord.prototype = { + getIterator: function () { + return getIteratorDirect(anObject(call(this.keys, this.set))); + }, + includes: function (it) { + return call(this.has, this.set, it); + } +}; -module.exports = function (O, key, value, options) { - if (!options) options = {}; - var simple = options.enumerable; - var name = options.name !== undefined ? options.name : key; - if (isCallable(value)) makeBuiltIn(value, name, options); - if (options.global) { - if (simple) O[key] = value; - else defineGlobalProperty(key, value); - } else { - try { - if (!options.unsafe) delete O[key]; - else if (O[key]) simple = true; - } catch (error) { /* empty */ } - if (simple) O[key] = value; - else definePropertyModule.f(O, key, { - value: value, - enumerable: false, - configurable: !options.nonConfigurable, - writable: !options.nonWritable - }); - } return O; +// `GetSetRecord` abstract operation +// https://tc39.es/proposal-set-methods/#sec-getsetrecord +module.exports = function (obj) { + anObject(obj); + var numSize = +obj.size; + // NOTE: If size is undefined, then numSize will be NaN + // eslint-disable-next-line no-self-compare -- NaN check + if (numSize !== numSize) throw new $TypeError(INVALID_SIZE); + var intSize = toIntegerOrInfinity(numSize); + if (intSize < 0) throw new $RangeError(INVALID_SIZE); + return new SetRecord(obj, intSize); }; /***/ }), -/* 50 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toLength = __webpack_require__(77); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var setPrototypeOf = __webpack_require__(49); -// `LengthOfArrayLike` abstract operation -// https://tc39.es/ecma262/#sec-lengthofarraylike -module.exports = function (obj) { - return toLength(obj.length); +// makes subclassing work correct for wrapped built-ins +module.exports = function ($this, dummy, Wrapper) { + var NewTarget, NewTargetPrototype; + if ( + // it can work only with native `setPrototypeOf` + setPrototypeOf && + // we haven't completely correct pre-ES6 way for getting `new.target`, so use this + isCallable(NewTarget = dummy.constructor) && + NewTarget !== Wrapper && + isObject(NewTargetPrototype = NewTarget.prototype) && + NewTargetPrototype !== Wrapper.prototype + ) setPrototypeOf($this, NewTargetPrototype); + return $this; }; /***/ }), -/* 51 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var IE8_DOM_DEFINE = __webpack_require__(242); -var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(279); -var anObject = __webpack_require__(37); -var toPropertyKey = __webpack_require__(94); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var hiddenKeys = __webpack_require__(100); +var isObject = __webpack_require__(8); +var hasOwn = __webpack_require__(13); +var defineProperty = __webpack_require__(19).f; +var getOwnPropertyNamesModule = __webpack_require__(75); +var getOwnPropertyNamesExternalModule = __webpack_require__(166); +var isExtensible = __webpack_require__(167); +var uid = __webpack_require__(95); +var FREEZING = __webpack_require__(81); -var $TypeError = TypeError; -// eslint-disable-next-line es/no-object-defineproperty -- safe -var $defineProperty = Object.defineProperty; -// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; -var ENUMERABLE = 'enumerable'; -var CONFIGURABLE = 'configurable'; -var WRITABLE = 'writable'; +var REQUIRED = false; +var METADATA = uid('meta'); +var id = 0; -// `Object.defineProperty` method -// https://tc39.es/ecma262/#sec-object.defineproperty -exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { - anObject(O); - P = toPropertyKey(P); - anObject(Attributes); - if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { - var current = $getOwnPropertyDescriptor(O, P); - if (current && current[WRITABLE]) { - O[P] = Attributes.value; - Attributes = { - configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], - enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], - writable: false - }; - } - } return $defineProperty(O, P, Attributes); -} : $defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPropertyKey(P); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return $defineProperty(O, P, Attributes); - } catch (error) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; +var setMetadata = function (it) { + defineProperty(it, METADATA, { value: { + objectID: 'O' + id++, // object ID + weakData: {} // weak collections IDs + } }); +}; + +var fastKey = function (it, create) { + // return a primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!hasOwn(it, METADATA)) { + // 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 + setMetadata(it); + // return object ID + } return it[METADATA].objectID; +}; + +var getWeakData = function (it, create) { + if (!hasOwn(it, METADATA)) { + // 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 + setMetadata(it); + // return the store of weak collections IDs + } return it[METADATA].weakData; }; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZING && REQUIRED && isExtensible(it) && !hasOwn(it, METADATA)) setMetadata(it); + return it; +}; -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +var enable = function () { + meta.enable = function () { /* empty */ }; + REQUIRED = true; + var getOwnPropertyNames = getOwnPropertyNamesModule.f; + var splice = uncurryThis([].splice); + var test = {}; + test[METADATA] = 1; -var isNullOrUndefined = __webpack_require__(89); + // prevent exposing of metadata key + if (getOwnPropertyNames(test).length) { + getOwnPropertyNamesModule.f = function (it) { + var result = getOwnPropertyNames(it); + for (var i = 0, length = result.length; i < length; i++) { + if (result[i] === METADATA) { + splice(result, i, 1); + break; + } + } return result; + }; -var $TypeError = TypeError; + $({ target: 'Object', stat: true, forced: true }, { + getOwnPropertyNames: getOwnPropertyNamesExternalModule.f + }); + } +}; -// `RequireObjectCoercible` abstract operation -// https://tc39.es/ecma262/#sec-requireobjectcoercible -module.exports = function (it) { - if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it); - return it; +var meta = module.exports = { + enable: enable, + fastKey: fastKey, + getWeakData: getWeakData, + onFreeze: onFreeze }; +hiddenKeys[METADATA] = true; + /***/ }), -/* 53 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NATIVE_WEAK_MAP = __webpack_require__(280); -var globalThis = __webpack_require__(35); -var isObject = __webpack_require__(40); -var createNonEnumerableProperty = __webpack_require__(59); -var hasOwn = __webpack_require__(45); -var shared = __webpack_require__(162); -var sharedKey = __webpack_require__(161); -var hiddenKeys = __webpack_require__(131); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var isCallable = __webpack_require__(14); +var classof = __webpack_require__(47); +var getBuiltIn = __webpack_require__(11); +var inspectSource = __webpack_require__(157); -var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; -var TypeError = globalThis.TypeError; -var WeakMap = globalThis.WeakMap; -var set, get, has; +var noop = function () { /* empty */ }; +var construct = getBuiltIn('Reflect', 'construct'); +var constructorRegExp = /^\s*(?:class|function)\b/; +var exec = uncurryThis(constructorRegExp.exec); +var INCORRECT_TO_STRING = !constructorRegExp.test(noop); -var enforce = function (it) { - return has(it) ? get(it) : set(it, {}); +var isConstructorModern = function isConstructor(argument) { + if (!isCallable(argument)) return false; + try { + construct(noop, [], argument); + return true; + } catch (error) { + return false; + } }; -var getterFor = function (TYPE) { - return function (it) { - var state; - if (!isObject(it) || (state = get(it)).type !== TYPE) { - throw new TypeError('Incompatible receiver, ' + TYPE + ' required'); - } return state; - }; +var isConstructorLegacy = function isConstructor(argument) { + if (!isCallable(argument)) return false; + switch (classof(argument)) { + case 'AsyncFunction': + case 'GeneratorFunction': + case 'AsyncGeneratorFunction': return false; + } + try { + // we can't check .prototype since constructors produced by .bind haven't it + // `Function#toString` throws on some built-it function in some legacy engines + // (for example, `DOMQuad` and similar in FF41-) + return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument)); + } catch (error) { + return true; + } }; -if (NATIVE_WEAK_MAP || shared.state) { - var store = shared.state || (shared.state = new WeakMap()); - /* eslint-disable no-self-assign -- prototype methods protection */ - store.get = store.get; - store.has = store.has; - store.set = store.set; - /* eslint-enable no-self-assign -- prototype methods protection */ - set = function (it, metadata) { - if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); - metadata.facade = it; - store.set(it, metadata); - return metadata; - }; - get = function (it) { - return store.get(it) || {}; - }; - has = function (it) { - return store.has(it); - }; -} else { - var STATE = sharedKey('state'); - hiddenKeys[STATE] = true; - set = function (it, metadata) { - if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); - metadata.facade = it; - createNonEnumerableProperty(it, STATE, metadata); - return metadata; - }; - get = function (it) { - return hasOwn(it, STATE) ? it[STATE] : {}; - }; - has = function (it) { - return hasOwn(it, STATE); - }; -} +isConstructorLegacy.sham = true; -module.exports = { - set: set, - get: get, - has: has, - enforce: enforce, - getterFor: getterFor -}; +// `IsConstructor` abstract operation +// https://tc39.es/ecma262/#sec-isconstructor +module.exports = !construct || fails(function () { + var called; + return isConstructorModern(isConstructorModern.call) + || !isConstructorModern(Object) + || !isConstructorModern(function () { called = true; }) + || called; +}) ? isConstructorLegacy : isConstructorModern; /***/ }), -/* 54 */ +/* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var trunc = __webpack_require__(254); +var getBuiltIn = __webpack_require__(11); +var isCallable = __webpack_require__(14); +var isPrototypeOf = __webpack_require__(36); +var USE_SYMBOL_AS_UID = __webpack_require__(249); -// `ToIntegerOrInfinity` abstract operation -// https://tc39.es/ecma262/#sec-tointegerorinfinity -module.exports = function (argument) { - var number = +argument; - // eslint-disable-next-line no-self-compare -- NaN check - return number !== number || number === 0 ? 0 : trunc(number); +var $Object = Object; + +module.exports = USE_SYMBOL_AS_UID ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + var $Symbol = getBuiltIn('Symbol'); + return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); }; /***/ }), -/* 55 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var makeBuiltIn = __webpack_require__(191); -var defineProperty = __webpack_require__(51); +var call = __webpack_require__(4); -module.exports = function (target, name, descriptor) { - if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true }); - if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true }); - return defineProperty.f(target, name, descriptor); +module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) { + var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator; + var next = record.next; + var step, result; + while (!(step = call(next, iterator)).done) { + result = fn(step.value); + if (result !== undefined) return result; + } }; /***/ }), -/* 56 */ +/* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var bind = __webpack_require__(75); -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var tryToString = __webpack_require__(109); -var isArrayIteratorMethod = __webpack_require__(187); -var lengthOfArrayLike = __webpack_require__(50); -var isPrototypeOf = __webpack_require__(68); -var getIterator = __webpack_require__(114); -var getIteratorMethod = __webpack_require__(99); -var iteratorClose = __webpack_require__(61); - -var $TypeError = TypeError; - -var Result = function (stopped, result) { - this.stopped = stopped; - this.result = result; -}; - -var ResultPrototype = Result.prototype; - -module.exports = function (iterable, unboundFunction, options) { - var that = options && options.that; - var AS_ENTRIES = !!(options && options.AS_ENTRIES); - var IS_RECORD = !!(options && options.IS_RECORD); - var IS_ITERATOR = !!(options && options.IS_ITERATOR); - var INTERRUPTED = !!(options && options.INTERRUPTED); - var fn = bind(unboundFunction, that); - var iterator, iterFn, index, length, result, next, step; - - var stop = function (condition) { - if (iterator) iteratorClose(iterator, 'normal'); - return new Result(true, condition); - }; - - var callFn = function (value) { - if (AS_ENTRIES) { - anObject(value); - return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); - } return INTERRUPTED ? fn(value, stop) : fn(value); - }; +var internalObjectKeys = __webpack_require__(231); +var enumBugKeys = __webpack_require__(153); - if (IS_RECORD) { - iterator = iterable.iterator; - } else if (IS_ITERATOR) { - iterator = iterable; - } else { - iterFn = getIteratorMethod(iterable); - if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable'); - // optimisation for array iterators - if (isArrayIteratorMethod(iterFn)) { - for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) { - result = callFn(iterable[index]); - if (result && isPrototypeOf(ResultPrototype, result)) return result; - } return new Result(false); - } - iterator = getIterator(iterable, iterFn); - } +var hiddenKeys = enumBugKeys.concat('length', 'prototype'); - next = IS_RECORD ? iterable.next : iterator.next; - while (!(step = call(next, iterator)).done) { - try { - result = callFn(step.value); - } catch (error) { - iteratorClose(iterator, 'throw', error); - } - if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result; - } return new Result(false); +// `Object.getOwnPropertyNames` method +// https://tc39.es/ecma262/#sec-object.getownpropertynames +// eslint-disable-next-line es/no-object-getownpropertynames -- safe +exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return internalObjectKeys(O, hiddenKeys); }; /***/ }), -/* 57 */ +/* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// toObject with fallback for non-array-like ES3 strings -var IndexedObject = __webpack_require__(115); -var requireObjectCoercible = __webpack_require__(52); +var call = __webpack_require__(4); +var hasOwn = __webpack_require__(13); +var isPrototypeOf = __webpack_require__(36); +var regExpFlagsDetection = __webpack_require__(237); +var regExpFlagsGetterImplementation = __webpack_require__(170); -module.exports = function (it) { - return IndexedObject(requireObjectCoercible(it)); +var RegExpPrototype = RegExp.prototype; + +module.exports = regExpFlagsDetection.correct ? function (it) { + return it.flags; +} : function (it) { + return (!regExpFlagsDetection.correct && isPrototypeOf(RegExpPrototype, it) && !hasOwn(it, 'flags')) + ? call(regExpFlagsGetterImplementation, it) + : it.flags; }; /***/ }), -/* 58 */ +/* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var bind = __webpack_require__(75); -var uncurryThis = __webpack_require__(34); -var IndexedObject = __webpack_require__(115); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var arraySpeciesCreate = __webpack_require__(129); - -var push = uncurryThis([].push); +var getBuiltIn = __webpack_require__(11); -// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation -var createMethod = function (TYPE) { - var IS_MAP = TYPE === 1; - var IS_FILTER = TYPE === 2; - var IS_SOME = TYPE === 3; - var IS_EVERY = TYPE === 4; - var IS_FIND_INDEX = TYPE === 6; - var IS_FILTER_REJECT = TYPE === 7; - var NO_HOLES = TYPE === 5 || IS_FIND_INDEX; - return function ($this, callbackfn, that, specificCreate) { - var O = toObject($this); - var self = IndexedObject(O); - var length = lengthOfArrayLike(self); - var boundFunction = bind(callbackfn, that); - var index = 0; - var create = specificCreate || arraySpeciesCreate; - var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined; - var value, result; - for (;length > index; index++) if (NO_HOLES || index in self) { - value = self[index]; - result = boundFunction(value, index, O); - if (TYPE) { - if (IS_MAP) target[index] = result; // map - else if (result) switch (TYPE) { - case 3: return true; // some - case 5: return value; // find - case 6: return index; // findIndex - case 2: push(target, value); // filter - } else switch (TYPE) { - case 4: return false; // every - case 7: push(target, value); // filterReject +var createSetLike = function (size) { + return { + size: size, + has: function () { + return false; + }, + keys: function () { + return { + next: function () { + return { done: true }; } - } + }; } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; }; }; -module.exports = { - // `Array.prototype.forEach` method - // https://tc39.es/ecma262/#sec-array.prototype.foreach - forEach: createMethod(0), - // `Array.prototype.map` method - // https://tc39.es/ecma262/#sec-array.prototype.map - map: createMethod(1), - // `Array.prototype.filter` method - // https://tc39.es/ecma262/#sec-array.prototype.filter - filter: createMethod(2), - // `Array.prototype.some` method - // https://tc39.es/ecma262/#sec-array.prototype.some - some: createMethod(3), - // `Array.prototype.every` method - // https://tc39.es/ecma262/#sec-array.prototype.every - every: createMethod(4), - // `Array.prototype.find` method - // https://tc39.es/ecma262/#sec-array.prototype.find - find: createMethod(5), - // `Array.prototype.findIndex` method - // https://tc39.es/ecma262/#sec-array.prototype.findIndex - findIndex: createMethod(6), - // `Array.prototype.filterReject` method - // https://github.com/tc39/proposal-array-filtering - filterReject: createMethod(7) +var createSetLikeWithInfinitySize = function (size) { + return { + size: size, + has: function () { + return true; + }, + keys: function () { + throw new Error('e'); + } + }; }; - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var DESCRIPTORS = __webpack_require__(38); -var definePropertyModule = __webpack_require__(51); -var createPropertyDescriptor = __webpack_require__(73); - -module.exports = DESCRIPTORS ? function (object, key, value) { - return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); -} : function (object, key, value) { - object[key] = value; - return object; +module.exports = function (name, callback) { + var Set = getBuiltIn('Set'); + try { + new Set()[name](createSetLike(0)); + try { + // late spec change, early WebKit ~ Safari 17 implementation does not pass it + // https://github.com/tc39/proposal-set-methods/pull/88 + // also covered engines with + // https://bugs.webkit.org/show_bug.cgi?id=272679 + new Set()[name](createSetLike(-1)); + return false; + } catch (error2) { + if (!callback) return true; + // early V8 implementation bug + // https://issues.chromium.org/issues/351332634 + try { + new Set()[name](createSetLikeWithInfinitySize(-Infinity)); + return false; + } catch (error) { + var set = new Set(); + set.add(1); + set.add(2); + return callback(set[name](createSetLikeWithInfinitySize(Infinity))); + } + } + } catch (error) { + return false; + } }; /***/ }), -/* 60 */ +/* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aCallable = __webpack_require__(42); -var isNullOrUndefined = __webpack_require__(89); +var $String = String; -// `GetMethod` abstract operation -// https://tc39.es/ecma262/#sec-getmethod -module.exports = function (V, P) { - var func = V[P]; - return isNullOrUndefined(func) ? undefined : aCallable(func); +module.exports = function (argument) { + try { + return $String(argument); + } catch (error) { + return 'Object'; + } }; /***/ }), -/* 61 */ +/* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var getMethod = __webpack_require__(60); +var hasOwn = __webpack_require__(13); +var ownKeys = __webpack_require__(168); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var definePropertyModule = __webpack_require__(19); -module.exports = function (iterator, kind, value) { - var innerResult, innerError; - anObject(iterator); - try { - innerResult = getMethod(iterator, 'return'); - if (!innerResult) { - if (kind === 'throw') throw value; - return value; +module.exports = function (target, source, exceptions) { + var keys = ownKeys(source); + var defineProperty = definePropertyModule.f; + var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) { + defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } - innerResult = call(innerResult, iterator); - } catch (error) { - innerError = true; - innerResult = error; } - if (kind === 'throw') throw value; - if (innerError) throw innerResult; - anObject(innerResult); - return value; }; /***/ }), -/* 62 */ +/* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* global ActiveXObject -- old IE, WSH */ -var anObject = __webpack_require__(37); -var definePropertiesModule = __webpack_require__(194); -var enumBugKeys = __webpack_require__(182); -var hiddenKeys = __webpack_require__(131); -var html = __webpack_require__(241); -var documentCreateElement = __webpack_require__(148); -var sharedKey = __webpack_require__(161); - -var GT = '>'; -var LT = '<'; -var PROTOTYPE = 'prototype'; -var SCRIPT = 'script'; -var IE_PROTO = sharedKey('IE_PROTO'); - -var EmptyConstructor = function () { /* empty */ }; +var ENVIRONMENT = __webpack_require__(119); -var scriptTag = function (content) { - return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; -}; +module.exports = ENVIRONMENT === 'NODE'; -// Create object with fake `null` prototype: use ActiveX Object with cleared prototype -var NullProtoObjectViaActiveX = function (activeXDocument) { - activeXDocument.write(scriptTag('')); - activeXDocument.close(); - var temp = activeXDocument.parentWindow.Object; - // eslint-disable-next-line no-useless-assignment -- avoid memory leak - activeXDocument = null; - return temp; -}; -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var NullProtoObjectViaIFrame = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = documentCreateElement('iframe'); - var JS = 'java' + SCRIPT + ':'; - var iframeDocument; - iframe.style.display = 'none'; - html.appendChild(iframe); - // https://github.com/zloirock/core-js/issues/475 - iframe.src = String(JS); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(scriptTag('document.F=Object')); - iframeDocument.close(); - return iframeDocument.F; -}; +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { -// Check for document.domain and active x support -// No need to use active x approach when document.domain is not set -// see https://github.com/es-shims/es5-shim/issues/150 -// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 -// avoid IE GC bug -var activeXDocument; -var NullProtoObject = function () { - try { - activeXDocument = new ActiveXObject('htmlfile'); - } catch (error) { /* ignore */ } - NullProtoObject = typeof document != 'undefined' - ? document.domain && activeXDocument - ? NullProtoObjectViaActiveX(activeXDocument) // old IE - : NullProtoObjectViaIFrame() - : NullProtoObjectViaActiveX(activeXDocument); // WSH - var length = enumBugKeys.length; - while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; - return NullProtoObject(); -}; +"use strict"; -hiddenKeys[IE_PROTO] = true; +var fails = __webpack_require__(1); -// `Object.create` method -// https://tc39.es/ecma262/#sec-object.create -// eslint-disable-next-line es/no-object-create -- safe -module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - EmptyConstructor[PROTOTYPE] = anObject(O); - result = new EmptyConstructor(); - EmptyConstructor[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = NullProtoObject(); - return Properties === undefined ? result : definePropertiesModule.f(result, Properties); -}; +module.exports = !fails(function () { + // eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing + return Object.isExtensible(Object.preventExtensions({})); +}); /***/ }), -/* 63 */ +/* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var call = __webpack_require__(36); -var propertyIsEnumerableModule = __webpack_require__(156); -var createPropertyDescriptor = __webpack_require__(73); -var toIndexedObject = __webpack_require__(57); -var toPropertyKey = __webpack_require__(94); -var hasOwn = __webpack_require__(45); -var IE8_DOM_DEFINE = __webpack_require__(242); +var DESCRIPTORS = __webpack_require__(6); +var hasOwn = __webpack_require__(13); +var FunctionPrototype = Function.prototype; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; -// `Object.getOwnPropertyDescriptor` method -// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor -exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { - O = toIndexedObject(O); - P = toPropertyKey(P); - if (IE8_DOM_DEFINE) try { - return $getOwnPropertyDescriptor(O, P); - } catch (error) { /* empty */ } - if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); +var EXISTS = hasOwn(FunctionPrototype, 'name'); +// additional protection from minified / mangled / dropped function names +var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something'; +var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable)); + +module.exports = { + EXISTS: EXISTS, + PROPER: PROPER, + CONFIGURABLE: CONFIGURABLE }; /***/ }), -/* 64 */ +/* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var tryToString = __webpack_require__(78); +var getIteratorMethod = __webpack_require__(68); -var toString = uncurryThis({}.toString); -var stringSlice = uncurryThis(''.slice); +var $TypeError = TypeError; -module.exports = function (it) { - return stringSlice(toString(it), 8, -1); +module.exports = function (argument, usingIterator) { + var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator; + if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument)); + throw new $TypeError(tryToString(argument) + ' is not iterable'); }; /***/ }), -/* 65 */ +/* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// `GetIteratorDirect(obj)` abstract operation -// https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect -module.exports = function (obj) { - return { - iterator: obj, - next: obj.next, - done: false - }; -}; +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var classof = __webpack_require__(32); + +var $Object = Object; +var split = uncurryThis(''.split); + +// fallback for non-array-like ES3 and non-enumerable old V8 strings +module.exports = fails(function () { + // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 + // eslint-disable-next-line no-prototype-builtins -- safe + return !$Object('z').propertyIsEnumerable(0); +}) ? function (it) { + return classof(it) === 'String' ? split(it, '') : $Object(it); +} : $Object; /***/ }), -/* 66 */ +/* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var path = __webpack_require__(158); -var hasOwn = __webpack_require__(45); -var wrappedWellKnownSymbolModule = __webpack_require__(281); -var defineProperty = __webpack_require__(51).f; +var call = __webpack_require__(4); +var create = __webpack_require__(30); +var createNonEnumerableProperty = __webpack_require__(27); +var defineBuiltIns = __webpack_require__(56); +var wellKnownSymbol = __webpack_require__(7); +var InternalStateModule = __webpack_require__(21); +var getMethod = __webpack_require__(28); +var IteratorPrototype = __webpack_require__(86).IteratorPrototype; +var createIterResultObject = __webpack_require__(65); +var iteratorClose = __webpack_require__(29); +var iteratorCloseAll = __webpack_require__(297); -module.exports = function (NAME) { - var Symbol = path.Symbol || (path.Symbol = {}); - if (!hasOwn(Symbol, NAME)) defineProperty(Symbol, NAME, { - value: wrappedWellKnownSymbolModule.f(NAME) +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var ITERATOR_HELPER = 'IteratorHelper'; +var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator'; +var NORMAL = 'normal'; +var THROW = 'throw'; +var setInternalState = InternalStateModule.set; + +var createIteratorProxyPrototype = function (IS_ITERATOR) { + var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER); + + return defineBuiltIns(create(IteratorPrototype), { + next: function next() { + var state = getInternalState(this); + // for simplification: + // for `%WrapForValidIteratorPrototype%.next` or with `state.returnHandlerResult` our `nextHandler` returns `IterResultObject` + // for `%IteratorHelperPrototype%.next` - just a value + if (IS_ITERATOR) return state.nextHandler(); + if (state.done) return createIterResultObject(undefined, true); + try { + var result = state.nextHandler(); + return state.returnHandlerResult ? result : createIterResultObject(result, state.done); + } catch (error) { + state.done = true; + throw error; + } + }, + 'return': function () { + var state = getInternalState(this); + var iterator = state.iterator; + state.done = true; + if (IS_ITERATOR) { + var returnMethod = getMethod(iterator, 'return'); + return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true); + } + if (state.inner) try { + iteratorClose(state.inner.iterator, NORMAL); + } catch (error) { + return iteratorClose(iterator, THROW, error); + } + if (state.openIters) try { + iteratorCloseAll(state.openIters, NORMAL); + } catch (error) { + return iteratorClose(iterator, THROW, error); + } + if (iterator) iteratorClose(iterator, NORMAL); + return createIterResultObject(undefined, true); + } }); }; +var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true); +var IteratorHelperPrototype = createIteratorProxyPrototype(false); -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper'); -var hasOwn = __webpack_require__(45); -var isCallable = __webpack_require__(46); -var toObject = __webpack_require__(47); -var sharedKey = __webpack_require__(161); -var CORRECT_PROTOTYPE_GETTER = __webpack_require__(180); +module.exports = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) { + var IteratorProxy = function Iterator(record, state) { + if (state) { + state.iterator = record.iterator; + state.next = record.next; + } else state = record; + state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER; + state.returnHandlerResult = !!RETURN_HANDLER_RESULT; + state.nextHandler = nextHandler; + state.counter = 0; + state.done = false; + setInternalState(this, state); + }; -var IE_PROTO = sharedKey('IE_PROTO'); -var $Object = Object; -var ObjectPrototype = $Object.prototype; + IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype; -// `Object.getPrototypeOf` method -// https://tc39.es/ecma262/#sec-object.getprototypeof -// eslint-disable-next-line es/no-object-getprototypeof -- safe -module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) { - var object = toObject(O); - if (hasOwn(object, IE_PROTO)) return object[IE_PROTO]; - var constructor = object.constructor; - if (isCallable(constructor) && object instanceof constructor) { - return constructor.prototype; - } return object instanceof $Object ? ObjectPrototype : null; + return IteratorProxy; }; /***/ }), -/* 68 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); - -module.exports = uncurryThis({}.isPrototypeOf); +var fails = __webpack_require__(1); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var create = __webpack_require__(30); +var getPrototypeOf = __webpack_require__(35); +var defineBuiltIn = __webpack_require__(17); +var wellKnownSymbol = __webpack_require__(7); +var IS_PURE = __webpack_require__(16); +var ITERATOR = wellKnownSymbol('iterator'); +var BUGGY_SAFARI_ITERATORS = false; -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { +// `%IteratorPrototype%` object +// https://tc39.es/ecma262/#sec-%iteratorprototype%-object +var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; -"use strict"; +/* eslint-disable es/no-array-prototype-keys -- safe */ +if ([].keys) { + arrayIterator = [].keys(); + // Safari 8 has buggy iterators w/o `next` + if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; + else { + PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); + if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; + } +} -var wellKnownSymbol = __webpack_require__(39); -var create = __webpack_require__(62); -var defineProperty = __webpack_require__(51).f; +var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () { + var test = {}; + // FF44- legacy iterators case + return IteratorPrototype[ITERATOR].call(test) !== test; +}); -var UNSCOPABLES = wellKnownSymbol('unscopables'); -var ArrayPrototype = Array.prototype; +if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {}; +else if (IS_PURE) IteratorPrototype = create(IteratorPrototype); -// Array.prototype[@@unscopables] -// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables -if (ArrayPrototype[UNSCOPABLES] === undefined) { - defineProperty(ArrayPrototype, UNSCOPABLES, { - configurable: true, - value: create(null) +// `%IteratorPrototype%[@@iterator]()` method +// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator +if (!isCallable(IteratorPrototype[ITERATOR])) { + defineBuiltIn(IteratorPrototype, ITERATOR, function () { + return this; }); } -// add a key to Array.prototype[@@unscopables] -module.exports = function (key) { - ArrayPrototype[UNSCOPABLES][key] = true; +module.exports = { + IteratorPrototype: IteratorPrototype, + BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS }; /***/ }), -/* 70 */ +/* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineProperty = __webpack_require__(51).f; -var hasOwn = __webpack_require__(45); -var wellKnownSymbol = __webpack_require__(39); +var toString = __webpack_require__(9); -var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +module.exports = function (argument, $default) { + return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument); +}; -module.exports = function (target, TAG, STATIC) { - if (target && !STATIC) target = target.prototype; - if (target && !hasOwn(target, TO_STRING_TAG)) { - defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG }); + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function (exec) { + try { + return { error: false, value: exec() }; + } catch (error) { + return { error: true, value: error }; } }; /***/ }), -/* 71 */ +/* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isPrototypeOf = __webpack_require__(68); - -var $TypeError = TypeError; +var globalThis = __webpack_require__(3); -module.exports = function (it, Prototype) { - if (isPrototypeOf(Prototype, it)) return it; - throw new $TypeError('Incorrect invocation'); -}; +module.exports = globalThis.Promise; /***/ }), -/* 72 */ +/* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toString = __webpack_require__(41); +var uncurryThis = __webpack_require__(2); +var iterateSimple = __webpack_require__(74); +var SetHelpers = __webpack_require__(50); -var quot = /"/g; -var replace = uncurryThis(''.replace); +var Set = SetHelpers.Set; +var SetPrototype = SetHelpers.proto; +var forEach = uncurryThis(SetPrototype.forEach); +var keys = uncurryThis(SetPrototype.keys); +var next = keys(new Set()).next; -// `CreateHTML` abstract operation -// https://tc39.es/ecma262/#sec-createhtml -module.exports = function (string, tag, attribute, value) { - var S = toString(requireObjectCoercible(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + replace(toString(value), quot, '"') + '"'; - return p1 + '>' + S + ''; +module.exports = function (set, fn, interruptible) { + return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn); }; /***/ }), -/* 73 */ +/* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; +var getBuiltIn = __webpack_require__(11); +var defineBuiltInAccessor = __webpack_require__(23); +var wellKnownSymbol = __webpack_require__(7); +var DESCRIPTORS = __webpack_require__(6); + +var SPECIES = wellKnownSymbol('species'); + +module.exports = function (CONSTRUCTOR_NAME) { + var Constructor = getBuiltIn(CONSTRUCTOR_NAME); + + if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) { + defineBuiltInAccessor(Constructor, SPECIES, { + configurable: true, + get: function () { return this; } + }); + } }; /***/ }), -/* 74 */ +/* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NATIVE_BIND = __webpack_require__(130); - -var FunctionPrototype = Function.prototype; -var apply = FunctionPrototype.apply; -var call = FunctionPrototype.call; +var store = __webpack_require__(132); -// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe -module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () { - return call.apply(apply, arguments); -}); +module.exports = function (key, value) { + return store[key] || (store[key] = value || {}); +}; /***/ }), -/* 75 */ +/* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(98); -var aCallable = __webpack_require__(42); -var NATIVE_BIND = __webpack_require__(130); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toString = __webpack_require__(9); +var whitespaces = __webpack_require__(107); -var bind = uncurryThis(uncurryThis.bind); +var replace = uncurryThis(''.replace); +var ltrim = RegExp('^[' + whitespaces + ']+'); +var rtrim = RegExp('(^|[^' + whitespaces + '])[' + whitespaces + ']+$'); -// optional / simple context binding -module.exports = function (fn, that) { - aCallable(fn); - return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) { - return fn.apply(that, arguments); +// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation +var createMethod = function (TYPE) { + return function ($this) { + var string = toString(requireObjectCoercible($this)); + if (TYPE & 1) string = replace(string, ltrim, ''); + if (TYPE & 2) string = replace(string, rtrim, '$1'); + return string; }; }; +module.exports = { + // `String.prototype.{ trimLeft, trimStart }` methods + // https://tc39.es/ecma262/#sec-string.prototype.trimstart + start: createMethod(1), + // `String.prototype.{ trimRight, trimEnd }` methods + // https://tc39.es/ecma262/#sec-string.prototype.trimend + end: createMethod(2), + // `String.prototype.trim` method + // https://tc39.es/ecma262/#sec-string.prototype.trim + trim: createMethod(3) +}; + /***/ }), -/* 76 */ +/* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); +/* eslint-disable es/no-symbol -- required for testing */ +var V8_VERSION = __webpack_require__(52); +var fails = __webpack_require__(1); +var globalThis = __webpack_require__(3); -// check the existence of a method, lowercase -// of a tag and escaping quotes in arguments -module.exports = function (METHOD_NAME) { - return fails(function () { - var test = ''[METHOD_NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }); -}; +var $String = globalThis.String; + +// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing +module.exports = !!Object.getOwnPropertySymbols && !fails(function () { + var symbol = Symbol('symbol detection'); + // Chrome 38 Symbol has incorrect toString conversion + // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances + // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will, + // of course, fail. + return !$String(symbol) || !(Object(symbol) instanceof Symbol) || + // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances + !Symbol.sham && V8_VERSION && V8_VERSION < 41; +}); /***/ }), -/* 77 */ +/* 95 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIntegerOrInfinity = __webpack_require__(54); +var uncurryThis = __webpack_require__(2); -var min = Math.min; +var id = 0; +var postfix = Math.random(); +var toString = uncurryThis(1.1.toString); -// `ToLength` abstract operation -// https://tc39.es/ecma262/#sec-tolength -module.exports = function (argument) { - var len = toIntegerOrInfinity(argument); - return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 +module.exports = function (key) { + return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36); }; /***/ }), -/* 78 */ +/* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); +var toIndexedObject = __webpack_require__(25); +var toAbsoluteIndex = __webpack_require__(59); +var lengthOfArrayLike = __webpack_require__(18); -module.exports = uncurryThis([].slice); +// `Array.prototype.{ indexOf, includes }` methods implementation +var createMethod = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIndexedObject($this); + var length = lengthOfArrayLike(O); + if (length === 0) return !IS_INCLUDES && -1; + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare -- NaN check + if (IS_INCLUDES && el !== el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare -- NaN check + if (value !== value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) { + if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +module.exports = { + // `Array.prototype.includes` method + // https://tc39.es/ecma262/#sec-array.prototype.includes + includes: createMethod(true), + // `Array.prototype.indexOf` method + // https://tc39.es/ecma262/#sec-array.prototype.indexof + indexOf: createMethod(false) +}; /***/ }), -/* 79 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var TO_STRING_TAG_SUPPORT = __webpack_require__(207); -var isCallable = __webpack_require__(46); -var classofRaw = __webpack_require__(64); -var wellKnownSymbol = __webpack_require__(39); - -var TO_STRING_TAG = wellKnownSymbol('toStringTag'); -var $Object = Object; - -// ES3 wrong here -var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments'; +var fails = __webpack_require__(1); +var wellKnownSymbol = __webpack_require__(7); +var V8_VERSION = __webpack_require__(52); -// fallback for IE11 Script Access Denied error -var tryGet = function (it, key) { - try { - return it[key]; - } catch (error) { /* empty */ } -}; +var SPECIES = wellKnownSymbol('species'); -// getting tag from ES6+ `Object.prototype.toString` -module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { - var O, tag, result; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag - // builtinTag case - : CORRECT_ARGUMENTS ? classofRaw(O) - // ES3 arguments fallback - : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; +module.exports = function (METHOD_NAME) { + // We can't use this feature detection in V8 since it causes + // deoptimization and serious performance degradation + // https://github.com/zloirock/core-js/issues/677 + return V8_VERSION >= 51 || !fails(function () { + var array = []; + var constructor = array.constructor = {}; + constructor[SPECIES] = function () { + return { foo: 1 }; + }; + return array[METHOD_NAME](Boolean).foo !== 1; + }); }; /***/ }), -/* 80 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $TypeError = TypeError; +var arraySpeciesConstructor = __webpack_require__(286); -module.exports = function (passed, required) { - if (passed < required) throw new $TypeError('Not enough arguments'); - return passed; +// `ArraySpeciesCreate` abstract operation +// https://tc39.es/ecma262/#sec-arrayspeciescreate +module.exports = function (originalArray, length) { + return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length); }; /***/ }), -/* 81 */ +/* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable no-proto -- safe */ -var uncurryThisAccessor = __webpack_require__(151); -var isObject = __webpack_require__(40); -var requireObjectCoercible = __webpack_require__(52); -var aPossiblePrototype = __webpack_require__(210); +var fails = __webpack_require__(1); -// `Object.setPrototypeOf` method -// https://tc39.es/ecma262/#sec-object.setprototypeof -// Works with __proto__ only. Old v8 can't work with null proto objects. -// eslint-disable-next-line es/no-object-setprototypeof -- safe -module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { - var CORRECT_SETTER = false; - var test = {}; - var setter; - try { - setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); - setter(test, []); - CORRECT_SETTER = test instanceof Array; - } catch (error) { /* empty */ } - return function setPrototypeOf(O, proto) { - requireObjectCoercible(O); - aPossiblePrototype(proto); - if (!isObject(O)) return O; - if (CORRECT_SETTER) setter(O, proto); - else O.__proto__ = proto; - return O; - }; -}() : undefined); +module.exports = !fails(function () { + // eslint-disable-next-line es/no-function-prototype-bind -- safe + var test = (function () { /* empty */ }).bind(); + // eslint-disable-next-line no-prototype-builtins -- safe + return typeof test != 'function' || test.hasOwnProperty('prototype'); +}); /***/ }), -/* 82 */ +/* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); - -// eslint-disable-next-line es/no-set -- safe -var SetPrototype = Set.prototype; - -module.exports = { - // eslint-disable-next-line es/no-set -- safe - Set: Set, - add: uncurryThis(SetPrototype.add), - has: uncurryThis(SetPrototype.has), - remove: uncurryThis(SetPrototype['delete']), - proto: SetPrototype -}; +module.exports = {}; /***/ }), -/* 83 */ +/* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +var fails = __webpack_require__(1); +var isCallable = __webpack_require__(14); -var navigator = globalThis.navigator; -var userAgent = navigator && navigator.userAgent; +var replacement = /#|\.prototype\./; -module.exports = userAgent ? String(userAgent) : ''; +var isForced = function (feature, detection) { + var value = data[normalize(feature)]; + return value === POLYFILL ? true + : value === NATIVE ? false + : isCallable(detection) ? fails(detection) + : !!detection; +}; + +var normalize = isForced.normalize = function (string) { + return String(string).replace(replacement, '.').toLowerCase(); +}; + +var data = isForced.data = {}; +var NATIVE = isForced.NATIVE = 'N'; +var POLYFILL = isForced.POLYFILL = 'P'; + +module.exports = isForced; /***/ }), -/* 84 */ +/* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var userAgent = __webpack_require__(83); +module.exports = {}; -var process = globalThis.process; -var Deno = globalThis.Deno; -var versions = process && process.versions || Deno && Deno.version; -var v8 = versions && versions.v8; -var match, version; -if (v8) { - match = v8.split('.'); - // in old Chrome, versions of V8 isn't V8 = Chrome / 10 - // but their correct versions are not interesting for us - version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); -} +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { -// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0` -// so check `userAgent` even if `.v8` exists, but 0 -if (!version && userAgent) { - match = userAgent.match(/Edge\/(\d+)/); - if (!match || match[1] >= 74) { - match = userAgent.match(/Chrome\/(\d+)/); - if (match) version = +match[1]; - } -} +"use strict"; -module.exports = version; +var internalObjectKeys = __webpack_require__(231); +var enumBugKeys = __webpack_require__(153); + +// `Object.keys` method +// https://tc39.es/ecma262/#sec-object.keys +// eslint-disable-next-line es/no-object-keys -- safe +module.exports = Object.keys || function keys(O) { + return internalObjectKeys(O, enumBugKeys); +}; /***/ }), -/* 85 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); - -// https://github.com/tc39/ecma262/pull/3467 -module.exports = function (METHOD_NAME, ExpectedError) { - var Iterator = globalThis.Iterator; - var IteratorPrototype = Iterator && Iterator.prototype; - var method = IteratorPrototype && IteratorPrototype[METHOD_NAME]; +var globalThis = __webpack_require__(3); +var NativePromiseConstructor = __webpack_require__(89); +var isCallable = __webpack_require__(14); +var isForced = __webpack_require__(101); +var inspectSource = __webpack_require__(157); +var wellKnownSymbol = __webpack_require__(7); +var ENVIRONMENT = __webpack_require__(119); +var IS_PURE = __webpack_require__(16); +var V8_VERSION = __webpack_require__(52); - var CLOSED = false; +var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype; +var SPECIES = wellKnownSymbol('species'); +var SUBCLASSING = false; +var NATIVE_PROMISE_REJECTION_EVENT = isCallable(globalThis.PromiseRejectionEvent); - if (method) try { - method.call({ - next: function () { return { done: true }; }, - 'return': function () { CLOSED = true; } - }, -1); - } catch (error) { - // https://bugs.webkit.org/show_bug.cgi?id=291195 - if (!(error instanceof ExpectedError)) CLOSED = false; - } +var FORCED_PROMISE_CONSTRUCTOR = isForced('Promise', function () { + var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor); + var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor); + // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // We can't detect it synchronously, so just check versions + if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true; + // We need Promise#{ catch, finally } in the pure version for preventing prototype pollution + if (IS_PURE && !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true; + // We can't use @@species feature detection in V8 since it causes + // deoptimization and performance degradation + // https://github.com/zloirock/core-js/issues/679 + if (!V8_VERSION || V8_VERSION < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) { + // Detect correctness of subclassing with @@species support + var promise = new NativePromiseConstructor(function (resolve) { resolve(1); }); + var FakePromise = function (exec) { + exec(function () { /* empty */ }, function () { /* empty */ }); + }; + var constructor = promise.constructor = {}; + constructor[SPECIES] = FakePromise; + SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise; + if (!SUBCLASSING) return true; + // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test + } return !GLOBAL_CORE_JS_PROMISE && (ENVIRONMENT === 'BROWSER' || ENVIRONMENT === 'DENO') && !NATIVE_PROMISE_REJECTION_EVENT; +}); - if (!CLOSED) return method; +module.exports = { + CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR, + REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT, + SUBCLASSING: SUBCLASSING }; /***/ }), -/* 86 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var isCallable = __webpack_require__(14); +var classof = __webpack_require__(32); +var regexpExec = __webpack_require__(169); -module.exports = function (METHOD_NAME, argument) { - var method = [][METHOD_NAME]; - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call -- required for testing - method.call(null, argument || function () { return 1; }, 1); - }); +var $TypeError = TypeError; + +// `RegExpExec` abstract operation +// https://tc39.es/ecma262/#sec-regexpexec +module.exports = function (R, S) { + var exec = R.exec; + if (isCallable(exec)) { + var result = call(exec, R, S); + if (result !== null) anObject(result); + return result; + } + if (classof(R) === 'RegExp') return call(regexpExec, R, S); + throw new $TypeError('RegExp#exec called on incompatible receiver'); }; /***/ }), -/* 87 */ +/* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var definePropertyModule = __webpack_require__(51); -var createPropertyDescriptor = __webpack_require__(73); +var uncurryThisAccessor = __webpack_require__(121); +var SetHelpers = __webpack_require__(50); -module.exports = function (object, key, value) { - if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value)); - else object[key] = value; +module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) { + return set.size; }; /***/ }), -/* 88 */ +/* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineBuiltIn = __webpack_require__(49); - -module.exports = function (target, src, options) { - for (var key in src) defineBuiltIn(target, key, src[key], options); - return target; -}; +// a string of all valid unicode whitespaces +module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' + + '\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; /***/ }), -/* 89 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory){ -// we can't use just `it == null` since of `document.all` special case -// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec -module.exports = function (it) { - return it === null || it === undefined; -}; + //UMD + if ( true ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { + return factory(); + }.call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof module === "object") { + module.exports = factory(); + } else { + root.Tone = factory(); + } +}(this, function(){ + + "use strict"; + + var Tone; + //constructs the main Tone object + function Main(func){ + Tone = func(); + } + //invokes each of the modules with the main Tone object as the argument + function Module(func){ + func(Tone); + } /** + * Tone.js + * @author Yotam Mann + * @license http://opensource.org/licenses/MIT MIT License + * @copyright 2014-2017 Yotam Mann + */ + Main(function () { + + /////////////////////////////////////////////////////////////////////////// + // TONE + /////////////////////////////////////////////////////////////////////////// + /** + * @class Tone is the base class of all other classes. It provides + * a lot of methods and functionality to all classes that extend + * it. + * + * @constructor + * @alias Tone + * @param {number} [inputs=1] the number of input nodes + * @param {number} [outputs=1] the number of output nodes + */ + var Tone = function (inputs, outputs) { + /** + * the input node(s) + * @type {GainNode|Array} + */ + if (this.isUndef(inputs) || inputs === 1) { + this.input = this.context.createGain(); + } else if (inputs > 1) { + this.input = new Array(inputs); + } + /** + * the output node(s) + * @type {GainNode|Array} + */ + if (this.isUndef(outputs) || outputs === 1) { + this.output = this.context.createGain(); + } else if (outputs > 1) { + this.output = new Array(inputs); + } + }; + /** + * Set the parameters at once. Either pass in an + * object mapping parameters to values, or to set a + * single parameter, by passing in a string and value. + * The last argument is an optional ramp time which + * will ramp any signal values to their destination value + * over the duration of the rampTime. + * @param {Object|string} params + * @param {number=} value + * @param {Time=} rampTime + * @returns {Tone} this + * @example + * //set values using an object + * filter.set({ + * "frequency" : 300, + * "type" : highpass + * }); + * @example + * filter.set("type", "highpass"); + * @example + * //ramp to the value 220 over 3 seconds. + * oscillator.set({ + * "frequency" : 220 + * }, 3); + */ + Tone.prototype.set = function (params, value, rampTime) { + if (this.isObject(params)) { + rampTime = value; + } else if (this.isString(params)) { + var tmpObj = {}; + tmpObj[params] = value; + params = tmpObj; + } + paramLoop: + for (var attr in params) { + value = params[attr]; + var parent = this; + if (attr.indexOf('.') !== -1) { + var attrSplit = attr.split('.'); + for (var i = 0; i < attrSplit.length - 1; i++) { + parent = parent[attrSplit[i]]; + if (parent instanceof Tone) { + attrSplit.splice(0, i + 1); + var innerParam = attrSplit.join('.'); + parent.set(innerParam, value); + continue paramLoop; + } + } + attr = attrSplit[attrSplit.length - 1]; + } + var param = parent[attr]; + if (this.isUndef(param)) { + continue; + } + if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { + if (param.value !== value) { + if (this.isUndef(rampTime)) { + param.value = value; + } else { + param.rampTo(value, rampTime); + } + } + } else if (param instanceof AudioParam) { + if (param.value !== value) { + param.value = value; + } + } else if (param instanceof Tone) { + param.set(value); + } else if (param !== value) { + parent[attr] = value; + } + } + return this; + }; + /** + * Get the object's attributes. Given no arguments get + * will return all available object properties and their corresponding + * values. Pass in a single attribute to retrieve or an array + * of attributes. The attribute strings can also include a "." + * to access deeper properties. + * @example + * osc.get(); + * //returns {"type" : "sine", "frequency" : 440, ...etc} + * @example + * osc.get("type"); + * //returns { "type" : "sine"} + * @example + * //use dot notation to access deep properties + * synth.get(["envelope.attack", "envelope.release"]); + * //returns {"envelope" : {"attack" : 0.2, "release" : 0.4}} + * @param {Array=|string|undefined} params the parameters to get, otherwise will return + * all available. + * @returns {Object} + */ + Tone.prototype.get = function (params) { + if (this.isUndef(params)) { + params = this._collectDefaults(this.constructor); + } else if (this.isString(params)) { + params = [params]; + } + var ret = {}; + for (var i = 0; i < params.length; i++) { + var attr = params[i]; + var parent = this; + var subRet = ret; + if (attr.indexOf('.') !== -1) { + var attrSplit = attr.split('.'); + for (var j = 0; j < attrSplit.length - 1; j++) { + var subAttr = attrSplit[j]; + subRet[subAttr] = subRet[subAttr] || {}; + subRet = subRet[subAttr]; + parent = parent[subAttr]; + } + attr = attrSplit[attrSplit.length - 1]; + } + var param = parent[attr]; + if (this.isObject(params[attr])) { + subRet[attr] = param.get(); + } else if (Tone.Signal && param instanceof Tone.Signal) { + subRet[attr] = param.value; + } else if (Tone.Param && param instanceof Tone.Param) { + subRet[attr] = param.value; + } else if (param instanceof AudioParam) { + subRet[attr] = param.value; + } else if (param instanceof Tone) { + subRet[attr] = param.get(); + } else if (!this.isFunction(param) && !this.isUndef(param)) { + subRet[attr] = param; + } + } + return ret; + }; + /** + * collect all of the default attributes in one + * @private + * @param {function} constr the constructor to find the defaults from + * @return {Array} all of the attributes which belong to the class + */ + Tone.prototype._collectDefaults = function (constr) { + var ret = []; + if (!this.isUndef(constr.defaults)) { + ret = Object.keys(constr.defaults); + } + if (!this.isUndef(constr._super)) { + var superDefs = this._collectDefaults(constr._super); + //filter out repeats + for (var i = 0; i < superDefs.length; i++) { + if (ret.indexOf(superDefs[i]) === -1) { + ret.push(superDefs[i]); + } + } + } + return ret; + }; + /** + * @returns {string} returns the name of the class as a string + */ + Tone.prototype.toString = function () { + for (var className in Tone) { + var isLetter = className[0].match(/^[A-Z]$/); + var sameConstructor = Tone[className] === this.constructor; + if (this.isFunction(Tone[className]) && isLetter && sameConstructor) { + return className; + } + } + return 'Tone'; + }; + /////////////////////////////////////////////////////////////////////////// + // CLASS VARS + /////////////////////////////////////////////////////////////////////////// + /** + * The number of inputs feeding into the AudioNode. + * For source nodes, this will be 0. + * @memberOf Tone# + * @name numberOfInputs + * @readOnly + */ + Object.defineProperty(Tone.prototype, 'numberOfInputs', { + get: function () { + if (this.input) { + if (this.isArray(this.input)) { + return this.input.length; + } else { + return 1; + } + } else { + return 0; + } + } + }); + /** + * The number of outputs coming out of the AudioNode. + * For source nodes, this will be 0. + * @memberOf Tone# + * @name numberOfInputs + * @readOnly + */ + Object.defineProperty(Tone.prototype, 'numberOfOutputs', { + get: function () { + if (this.output) { + if (this.isArray(this.output)) { + return this.output.length; + } else { + return 1; + } + } else { + return 0; + } + } + }); + /////////////////////////////////////////////////////////////////////////// + // CONNECTIONS + /////////////////////////////////////////////////////////////////////////// + /** + * disconnect and dispose + * @returns {Tone} this + */ + Tone.prototype.dispose = function () { + if (!this.isUndef(this.input)) { + if (this.input instanceof AudioNode) { + this.input.disconnect(); + } + this.input = null; + } + if (!this.isUndef(this.output)) { + if (this.output instanceof AudioNode) { + this.output.disconnect(); + } + this.output = null; + } + return this; + }; + /** + * connect the output of a ToneNode to an AudioParam, AudioNode, or ToneNode + * @param {Tone | AudioParam | AudioNode} unit + * @param {number} [outputNum=0] optionally which output to connect from + * @param {number} [inputNum=0] optionally which input to connect to + * @returns {Tone} this + */ + Tone.prototype.connect = function (unit, outputNum, inputNum) { + if (Array.isArray(this.output)) { + outputNum = this.defaultArg(outputNum, 0); + this.output[outputNum].connect(unit, 0, inputNum); + } else { + this.output.connect(unit, outputNum, inputNum); + } + return this; + }; + /** + * disconnect the output + * @param {Number|AudioNode} output Either the output index to disconnect + * if the output is an array, or the + * node to disconnect from. + * @returns {Tone} this + */ + Tone.prototype.disconnect = function (destination, outputNum, inputNum) { + if (this.isArray(this.output)) { + if (this.isNumber(destination)) { + this.output[destination].disconnect(); + } else { + outputNum = this.defaultArg(outputNum, 0); + this.output[outputNum].disconnect(destination, 0, inputNum); + } + } else { + this.output.disconnect.apply(this.output, arguments); + } + }; + /** + * connect together all of the arguments in series + * @param {...AudioParam|Tone|AudioNode} nodes + * @returns {Tone} this + */ + Tone.prototype.connectSeries = function () { + if (arguments.length > 1) { + var currentUnit = arguments[0]; + for (var i = 1; i < arguments.length; i++) { + var toUnit = arguments[i]; + currentUnit.connect(toUnit); + currentUnit = toUnit; + } + } + return this; + }; + /** + * Connect the output of this node to the rest of the nodes in series. + * @example + * //connect a node to an effect, panVol and then to the master output + * node.chain(effect, panVol, Tone.Master); + * @param {...AudioParam|Tone|AudioNode} nodes + * @returns {Tone} this + */ + Tone.prototype.chain = function () { + if (arguments.length > 0) { + var currentUnit = this; + for (var i = 0; i < arguments.length; i++) { + var toUnit = arguments[i]; + currentUnit.connect(toUnit); + currentUnit = toUnit; + } + } + return this; + }; + /** + * connect the output of this node to the rest of the nodes in parallel. + * @param {...AudioParam|Tone|AudioNode} nodes + * @returns {Tone} this + */ + Tone.prototype.fan = function () { + if (arguments.length > 0) { + for (var i = 0; i < arguments.length; i++) { + this.connect(arguments[i]); + } + } + return this; + }; + //give native nodes chain and fan methods + AudioNode.prototype.chain = Tone.prototype.chain; + AudioNode.prototype.fan = Tone.prototype.fan; + /////////////////////////////////////////////////////////////////////////// + // UTILITIES / HELPERS / MATHS + /////////////////////////////////////////////////////////////////////////// + /** + * If the `given` parameter is undefined, use the `fallback`. + * If both `given` and `fallback` are object literals, it will + * return a deep copy which includes all of the parameters from both + * objects. If a parameter is undefined in given, it will return + * the fallback property. + *

+ * WARNING: if object is self referential, it will go into an an + * infinite recursive loop. + * + * @param {*} given + * @param {*} fallback + * @return {*} + */ + Tone.prototype.defaultArg = function (given, fallback) { + if (this.isObject(given) && this.isObject(fallback)) { + var ret = {}; + //make a deep copy of the given object + for (var givenProp in given) { + ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); + } + for (var fallbackProp in fallback) { + ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); + } + return ret; + } else { + return this.isUndef(given) ? fallback : given; + } + }; + /** + * returns the args as an options object with given arguments + * mapped to the names provided. + * + * if the args given is an array containing only one object, it is assumed + * that that's already the options object and will just return it. + * + * @param {Array} values the 'arguments' object of the function + * @param {Array} keys the names of the arguments as they + * should appear in the options object + * @param {Object=} defaults optional defaults to mixin to the returned + * options object + * @return {Object} the options object with the names mapped to the arguments + */ + Tone.prototype.optionsObject = function (values, keys, defaults) { + var options = {}; + if (values.length === 1 && this.isObject(values[0])) { + options = values[0]; + } else { + for (var i = 0; i < keys.length; i++) { + options[keys[i]] = values[i]; + } + } + if (!this.isUndef(defaults)) { + return this.defaultArg(options, defaults); + } else { + return options; + } + }; + /////////////////////////////////////////////////////////////////////////// + // TYPE CHECKING + /////////////////////////////////////////////////////////////////////////// + /** + * test if the arg is undefined + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is undefined + * @function + */ + Tone.prototype.isUndef = function (val) { + return typeof val === 'undefined'; + }; + /** + * test if the arg is a function + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is a function + * @function + */ + Tone.prototype.isFunction = function (val) { + return typeof val === 'function'; + }; + /** + * Test if the argument is a number. + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is a number + */ + Tone.prototype.isNumber = function (arg) { + return typeof arg === 'number'; + }; + /** + * Test if the given argument is an object literal (i.e. `{}`); + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is an object literal. + */ + Tone.prototype.isObject = function (arg) { + return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; + }; + /** + * Test if the argument is a boolean. + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is a boolean + */ + Tone.prototype.isBoolean = function (arg) { + return typeof arg === 'boolean'; + }; + /** + * Test if the argument is an Array + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is an array + */ + Tone.prototype.isArray = function (arg) { + return Array.isArray(arg); + }; + /** + * Test if the argument is a string. + * @param {*} arg the argument to test + * @returns {boolean} true if the arg is a string + */ + Tone.prototype.isString = function (arg) { + return typeof arg === 'string'; + }; + /** + * An empty function. + * @static + */ + Tone.noOp = function () { + }; + /** + * Make the property not writable. Internal use only. + * @private + * @param {string} property the property to make not writable + */ + Tone.prototype._readOnly = function (property) { + if (Array.isArray(property)) { + for (var i = 0; i < property.length; i++) { + this._readOnly(property[i]); + } + } else { + Object.defineProperty(this, property, { + writable: false, + enumerable: true + }); + } + }; + /** + * Make an attribute writeable. Interal use only. + * @private + * @param {string} property the property to make writable + */ + Tone.prototype._writable = function (property) { + if (Array.isArray(property)) { + for (var i = 0; i < property.length; i++) { + this._writable(property[i]); + } + } else { + Object.defineProperty(this, property, { writable: true }); + } + }; + /** + * Possible play states. + * @enum {string} + */ + Tone.State = { + Started: 'started', + Stopped: 'stopped', + Paused: 'paused' + }; + /////////////////////////////////////////////////////////////////////////// + // CONVERSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Equal power gain scale. Good for cross-fading. + * @param {NormalRange} percent (0-1) + * @return {Number} output gain (0-1) + */ + Tone.prototype.equalPowerScale = function (percent) { + var piFactor = 0.5 * Math.PI; + return Math.sin(percent * piFactor); + }; + /** + * Convert decibels into gain. + * @param {Decibels} db + * @return {Number} + */ + Tone.prototype.dbToGain = function (db) { + return Math.pow(2, db / 6); + }; + /** + * Convert gain to decibels. + * @param {Number} gain (0-1) + * @return {Decibels} + */ + Tone.prototype.gainToDb = function (gain) { + return 20 * (Math.log(gain) / Math.LN10); + }; + /** + * Convert an interval (in semitones) to a frequency ratio. + * @param {Interval} interval the number of semitones above the base note + * @return {number} the frequency ratio + * @example + * tone.intervalToFrequencyRatio(0); // 1 + * tone.intervalToFrequencyRatio(12); // 2 + * tone.intervalToFrequencyRatio(-12); // 0.5 + */ + Tone.prototype.intervalToFrequencyRatio = function (interval) { + return Math.pow(2, interval / 12); + }; + /////////////////////////////////////////////////////////////////////////// + // TIMING + /////////////////////////////////////////////////////////////////////////// + /** + * Return the current time of the AudioContext clock. + * @return {Number} the currentTime from the AudioContext + */ + Tone.prototype.now = function () { + return Tone.context.now(); + }; + /** + * Return the current time of the AudioContext clock. + * @return {Number} the currentTime from the AudioContext + * @static + */ + Tone.now = function () { + return Tone.context.now(); + }; + /////////////////////////////////////////////////////////////////////////// + // INHERITANCE + /////////////////////////////////////////////////////////////////////////// + /** + * have a child inherit all of Tone's (or a parent's) prototype + * to inherit the parent's properties, make sure to call + * Parent.call(this) in the child's constructor + * + * based on closure library's inherit function + * + * @static + * @param {function} child + * @param {function=} parent (optional) parent to inherit from + * if no parent is supplied, the child + * will inherit from Tone + */ + Tone.extend = function (child, parent) { + if (Tone.prototype.isUndef(parent)) { + parent = Tone; + } + function TempConstructor() { + } + TempConstructor.prototype = parent.prototype; + child.prototype = new TempConstructor(); + /** @override */ + child.prototype.constructor = child; + child._super = parent; + }; + /////////////////////////////////////////////////////////////////////////// + // CONTEXT + /////////////////////////////////////////////////////////////////////////// + /** + * The private audio context shared by all Tone Nodes. + * @private + * @type {Tone.Context|undefined} + */ + var audioContext; + /** + * A static pointer to the audio context accessible as Tone.context. + * @type {Tone.Context} + * @name context + * @memberOf Tone + */ + Object.defineProperty(Tone, 'context', { + get: function () { + return audioContext; + }, + set: function (context) { + if (Tone.Context && context instanceof Tone.Context) { + audioContext = context; + } else { + audioContext = new Tone.Context(context); + } + //initialize the new audio context + if (Tone.Context) { + Tone.Context.emit('init', audioContext); + } + } + }); + /** + * The AudioContext + * @type {Tone.Context} + * @name context + * @memberOf Tone# + * @readOnly + */ + Object.defineProperty(Tone.prototype, 'context', { + get: function () { + return Tone.context; + } + }); + /** + * Tone automatically creates a context on init, but if you are working + * with other libraries which also create an AudioContext, it can be + * useful to set your own. If you are going to set your own context, + * be sure to do it at the start of your code, before creating any objects. + * @static + * @param {AudioContext} ctx The new audio context to set + */ + Tone.setContext = function (ctx) { + Tone.context = ctx; + }; + /** + * The number of seconds of 1 processing block (128 samples) + * @type {Number} + * @name blockTime + * @memberOf Tone# + * @readOnly + */ + Object.defineProperty(Tone.prototype, 'blockTime', { + get: function () { + return 128 / this.context.sampleRate; + } + }); + /** + * The duration in seconds of one sample. + * @type {Number} + * @name sampleTime + * @memberOf Tone# + * @readOnly + */ + Object.defineProperty(Tone.prototype, 'sampleTime', { + get: function () { + return 1 / this.context.sampleRate; + } + }); + /** + * Whether or not all the technologies that Tone.js relies on are supported by the current browser. + * @type {Boolean} + * @name supported + * @memberOf Tone + * @readOnly + */ + Object.defineProperty(Tone, 'supported', { + get: function () { + var hasAudioContext = window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext'); + var hasPromises = window.hasOwnProperty('Promise'); + var hasWorkers = window.hasOwnProperty('Worker'); + return hasAudioContext && hasPromises && hasWorkers; + } + }); + Tone.version = 'r10'; + // allow optional silencing of this log + if (!window.TONE_SILENCE_VERSION_LOGGING) { + console.log('%c * Tone.js ' + Tone.version + ' * ', 'background: #000; color: #fff'); + } + return Tone; + }); + Module(function (Tone) { + + /** + * @class Base class for all Signals. Used Internally. + * + * @constructor + * @extends {Tone} + */ + Tone.SignalBase = function () { + }; + Tone.extend(Tone.SignalBase); + /** + * When signals connect to other signals or AudioParams, + * they take over the output value of that signal or AudioParam. + * For all other nodes, the behavior is the same as a default connect. + * + * @override + * @param {AudioParam|AudioNode|Tone.Signal|Tone} node + * @param {number} [outputNumber=0] The output number to connect from. + * @param {number} [inputNumber=0] The input number to connect to. + * @returns {Tone.SignalBase} this + */ + Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { + //zero it out so that the signal can have full control + if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { + //cancel changes + node._param.cancelScheduledValues(0); + //reset the value + node._param.value = 0; + //mark the value as overridden + node.overridden = true; + } else if (node instanceof AudioParam) { + node.cancelScheduledValues(0); + node.value = 0; + } + Tone.prototype.connect.call(this, node, outputNumber, inputNumber); + return this; + }; + return Tone.SignalBase; + }); + Module(function (Tone) { + + /** + * @class Wraps the native Web Audio API + * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface). + * + * @extends {Tone.SignalBase} + * @constructor + * @param {function|Array|Number} mapping The function used to define the values. + * The mapping function should take two arguments: + * the first is the value at the current position + * and the second is the array position. + * If the argument is an array, that array will be + * set as the wave shaping function. The input + * signal is an AudioRange [-1, 1] value and the output + * signal can take on any numerical values. + * + * @param {Number} [bufferLen=1024] The length of the WaveShaperNode buffer. + * @example + * var timesTwo = new Tone.WaveShaper(function(val){ + * return val * 2; + * }, 2048); + * @example + * //a waveshaper can also be constructed with an array of values + * var invert = new Tone.WaveShaper([1, -1]); + */ + Tone.WaveShaper = function (mapping, bufferLen) { + /** + * the waveshaper + * @type {WaveShaperNode} + * @private + */ + this._shaper = this.input = this.output = this.context.createWaveShaper(); + /** + * the waveshapers curve + * @type {Float32Array} + * @private + */ + this._curve = null; + if (Array.isArray(mapping)) { + this.curve = mapping; + } else if (isFinite(mapping) || this.isUndef(mapping)) { + this._curve = new Float32Array(this.defaultArg(mapping, 1024)); + } else if (this.isFunction(mapping)) { + this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); + this.setMap(mapping); + } + }; + Tone.extend(Tone.WaveShaper, Tone.SignalBase); + /** + * Uses a mapping function to set the value of the curve. + * @param {function} mapping The function used to define the values. + * The mapping function take two arguments: + * the first is the value at the current position + * which goes from -1 to 1 over the number of elements + * in the curve array. The second argument is the array position. + * @returns {Tone.WaveShaper} this + * @example + * //map the input signal from [-1, 1] to [0, 10] + * shaper.setMap(function(val, index){ + * return (val + 1) * 5; + * }) + */ + Tone.WaveShaper.prototype.setMap = function (mapping) { + for (var i = 0, len = this._curve.length; i < len; i++) { + var normalized = i / (len - 1) * 2 - 1; + this._curve[i] = mapping(normalized, i); + } + this._shaper.curve = this._curve; + return this; + }; + /** + * The array to set as the waveshaper curve. For linear curves + * array length does not make much difference, but for complex curves + * longer arrays will provide smoother interpolation. + * @memberOf Tone.WaveShaper# + * @type {Array} + * @name curve + */ + Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { + get: function () { + return this._shaper.curve; + }, + set: function (mapping) { + this._curve = new Float32Array(mapping); + this._shaper.curve = this._curve; + } + }); + /** + * Specifies what type of oversampling (if any) should be used when + * applying the shaping curve. Can either be "none", "2x" or "4x". + * @memberOf Tone.WaveShaper# + * @type {string} + * @name oversample + */ + Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { + get: function () { + return this._shaper.oversample; + }, + set: function (oversampling) { + if ([ + 'none', + '2x', + '4x' + ].indexOf(oversampling) !== -1) { + this._shaper.oversample = oversampling; + } else { + throw new RangeError('Tone.WaveShaper: oversampling must be either \'none\', \'2x\', or \'4x\''); + } + } + }); + /** + * Clean up. + * @returns {Tone.WaveShaper} this + */ + Tone.WaveShaper.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._shaper.disconnect(); + this._shaper = null; + this._curve = null; + return this; + }; + return Tone.WaveShaper; + }); + Module(function (Tone) { + /** + * @class Tone.TimeBase is a flexible encoding of time + * which can be evaluated to and from a string. + * Parsing code modified from https://code.google.com/p/tapdigit/ + * Copyright 2011 2012 Ariya Hidayat, New BSD License + * @extends {Tone} + * @param {Time} val The time value as a number or string + * @param {String=} units Unit values + * @example + * Tone.TimeBase(4, "n") + * Tone.TimeBase(2, "t") + * Tone.TimeBase("2t").add("1m") + * Tone.TimeBase("2t + 1m"); + */ + Tone.TimeBase = function (val, units) { + //allows it to be constructed with or without 'new' + if (this instanceof Tone.TimeBase) { + /** + * Any expressions parsed from the Time + * @type {Array} + * @private + */ + this._expr = this._noOp; + if (val instanceof Tone.TimeBase) { + this.copy(val); + } else if (!this.isUndef(units) || this.isNumber(val)) { + //default units + units = this.defaultArg(units, this._defaultUnits); + var method = this._primaryExpressions[units].method; + this._expr = method.bind(this, val); + } else if (this.isString(val)) { + this.set(val); + } else if (this.isUndef(val)) { + //default expression + this._expr = this._defaultExpr(); + } + } else { + return new Tone.TimeBase(val, units); + } + }; + Tone.extend(Tone.TimeBase); + /** + * Repalce the current time value with the value + * given by the expression string. + * @param {String} exprString + * @return {Tone.TimeBase} this + */ + Tone.TimeBase.prototype.set = function (exprString) { + this._expr = this._parseExprString(exprString); + return this; + }; + /** + * Return a clone of the TimeBase object. + * @return {Tone.TimeBase} The new cloned Tone.TimeBase + */ + Tone.TimeBase.prototype.clone = function () { + var instance = new this.constructor(); + instance.copy(this); + return instance; + }; + /** + * Copies the value of time to this Time + * @param {Tone.TimeBase} time + * @return {TimeBase} + */ + Tone.TimeBase.prototype.copy = function (time) { + var val = time._expr(); + return this.set(val); + }; + /////////////////////////////////////////////////////////////////////////// + // ABSTRACT SYNTAX TREE PARSER + /////////////////////////////////////////////////////////////////////////// + /** + * All the primary expressions. + * @private + * @type {Object} + */ + Tone.TimeBase.prototype._primaryExpressions = { + 'n': { + regexp: /^(\d+)n/i, + method: function (value) { + value = parseInt(value); + if (value === 1) { + return this._beatsToUnits(this._timeSignature()); + } else { + return this._beatsToUnits(4 / value); + } + } + }, + 't': { + regexp: /^(\d+)t/i, + method: function (value) { + value = parseInt(value); + return this._beatsToUnits(8 / (parseInt(value) * 3)); + } + }, + 'm': { + regexp: /^(\d+)m/i, + method: function (value) { + return this._beatsToUnits(parseInt(value) * this._timeSignature()); + } + }, + 'i': { + regexp: /^(\d+)i/i, + method: function (value) { + return this._ticksToUnits(parseInt(value)); + } + }, + 'hz': { + regexp: /^(\d+(?:\.\d+)?)hz/i, + method: function (value) { + return this._frequencyToUnits(parseFloat(value)); + } + }, + 'tr': { + regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, + method: function (m, q, s) { + var total = 0; + if (m && m !== '0') { + total += this._beatsToUnits(this._timeSignature() * parseFloat(m)); + } + if (q && q !== '0') { + total += this._beatsToUnits(parseFloat(q)); + } + if (s && s !== '0') { + total += this._beatsToUnits(parseFloat(s) / 4); + } + return total; + } + }, + 's': { + regexp: /^(\d+(?:\.\d+)?s)/, + method: function (value) { + return this._secondsToUnits(parseFloat(value)); + } + }, + 'samples': { + regexp: /^(\d+)samples/, + method: function (value) { + return parseInt(value) / this.context.sampleRate; + } + }, + 'default': { + regexp: /^(\d+(?:\.\d+)?)/, + method: function (value) { + return this._primaryExpressions[this._defaultUnits].method.call(this, value); + } + } + }; + /** + * All the binary expressions that TimeBase can accept. + * @private + * @type {Object} + */ + Tone.TimeBase.prototype._binaryExpressions = { + '+': { + regexp: /^\+/, + precedence: 2, + method: function (lh, rh) { + return lh() + rh(); + } + }, + '-': { + regexp: /^\-/, + precedence: 2, + method: function (lh, rh) { + return lh() - rh(); + } + }, + '*': { + regexp: /^\*/, + precedence: 1, + method: function (lh, rh) { + return lh() * rh(); + } + }, + '/': { + regexp: /^\//, + precedence: 1, + method: function (lh, rh) { + return lh() / rh(); + } + } + }; + /** + * All the unary expressions. + * @private + * @type {Object} + */ + Tone.TimeBase.prototype._unaryExpressions = { + 'neg': { + regexp: /^\-/, + method: function (lh) { + return -lh(); + } + } + }; + /** + * Syntactic glue which holds expressions together + * @private + * @type {Object} + */ + Tone.TimeBase.prototype._syntaxGlue = { + '(': { regexp: /^\(/ }, + ')': { regexp: /^\)/ } + }; + /** + * tokenize the expression based on the Expressions object + * @param {string} expr + * @return {Object} returns two methods on the tokenized list, next and peek + * @private + */ + Tone.TimeBase.prototype._tokenize = function (expr) { + var position = -1; + var tokens = []; + while (expr.length > 0) { + expr = expr.trim(); + var token = getNextToken(expr, this); + tokens.push(token); + expr = expr.substr(token.value.length); + } + function getNextToken(expr, context) { + var expressions = [ + '_binaryExpressions', + '_unaryExpressions', + '_primaryExpressions', + '_syntaxGlue' + ]; + for (var i = 0; i < expressions.length; i++) { + var group = context[expressions[i]]; + for (var opName in group) { + var op = group[opName]; + var reg = op.regexp; + var match = expr.match(reg); + if (match !== null) { + return { + method: op.method, + precedence: op.precedence, + regexp: op.regexp, + value: match[0] + }; + } + } + } + throw new SyntaxError('Tone.TimeBase: Unexpected token ' + expr); + } + return { + next: function () { + return tokens[++position]; + }, + peek: function () { + return tokens[position + 1]; + } + }; + }; + /** + * Given a token, find the value within the groupName + * @param {Object} token + * @param {String} groupName + * @param {Number} precedence + * @private + */ + Tone.TimeBase.prototype._matchGroup = function (token, group, prec) { + var ret = false; + if (!this.isUndef(token)) { + for (var opName in group) { + var op = group[opName]; + if (op.regexp.test(token.value)) { + if (!this.isUndef(prec)) { + if (op.precedence === prec) { + return op; + } + } else { + return op; + } + } + } + } + return ret; + }; + /** + * Match a binary expression given the token and the precedence + * @param {Lexer} lexer + * @param {Number} precedence + * @private + */ + Tone.TimeBase.prototype._parseBinary = function (lexer, precedence) { + if (this.isUndef(precedence)) { + precedence = 2; + } + var expr; + if (precedence < 0) { + expr = this._parseUnary(lexer); + } else { + expr = this._parseBinary(lexer, precedence - 1); + } + var token = lexer.peek(); + while (token && this._matchGroup(token, this._binaryExpressions, precedence)) { + token = lexer.next(); + expr = token.method.bind(this, expr, this._parseBinary(lexer, precedence - 1)); + token = lexer.peek(); + } + return expr; + }; + /** + * Match a unary expression. + * @param {Lexer} lexer + * @private + */ + Tone.TimeBase.prototype._parseUnary = function (lexer) { + var token, expr; + token = lexer.peek(); + var op = this._matchGroup(token, this._unaryExpressions); + if (op) { + token = lexer.next(); + expr = this._parseUnary(lexer); + return op.method.bind(this, expr); + } + return this._parsePrimary(lexer); + }; + /** + * Match a primary expression (a value). + * @param {Lexer} lexer + * @private + */ + Tone.TimeBase.prototype._parsePrimary = function (lexer) { + var token, expr; + token = lexer.peek(); + if (this.isUndef(token)) { + throw new SyntaxError('Tone.TimeBase: Unexpected end of expression'); + } + if (this._matchGroup(token, this._primaryExpressions)) { + token = lexer.next(); + var matching = token.value.match(token.regexp); + return token.method.bind(this, matching[1], matching[2], matching[3]); + } + if (token && token.value === '(') { + lexer.next(); + expr = this._parseBinary(lexer); + token = lexer.next(); + if (!(token && token.value === ')')) { + throw new SyntaxError('Expected )'); + } + return expr; + } + throw new SyntaxError('Tone.TimeBase: Cannot process token ' + token.value); + }; + /** + * Recursively parse the string expression into a syntax tree. + * @param {string} expr + * @return {Function} the bound method to be evaluated later + * @private + */ + Tone.TimeBase.prototype._parseExprString = function (exprString) { + if (!this.isString(exprString)) { + exprString = exprString.toString(); + } + var lexer = this._tokenize(exprString); + var tree = this._parseBinary(lexer); + return tree; + }; + /////////////////////////////////////////////////////////////////////////// + // DEFAULTS + /////////////////////////////////////////////////////////////////////////// + /** + * The initial expression value + * @return {Number} The initial value 0 + * @private + */ + Tone.TimeBase.prototype._noOp = function () { + return 0; + }; + /** + * The default expression value if no arguments are given + * @private + */ + Tone.TimeBase.prototype._defaultExpr = function () { + return this._noOp; + }; + /** + * The default units if none are given. + * @private + */ + Tone.TimeBase.prototype._defaultUnits = 's'; + /////////////////////////////////////////////////////////////////////////// + // UNIT CONVERSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Returns the value of a frequency in the current units + * @param {Frequency} freq + * @return {Number} + * @private + */ + Tone.TimeBase.prototype._frequencyToUnits = function (freq) { + return 1 / freq; + }; + /** + * Return the value of the beats in the current units + * @param {Number} beats + * @return {Number} + * @private + */ + Tone.TimeBase.prototype._beatsToUnits = function (beats) { + return 60 / Tone.Transport.bpm.value * beats; + }; + /** + * Returns the value of a second in the current units + * @param {Seconds} seconds + * @return {Number} + * @private + */ + Tone.TimeBase.prototype._secondsToUnits = function (seconds) { + return seconds; + }; + /** + * Returns the value of a tick in the current time units + * @param {Ticks} ticks + * @return {Number} + * @private + */ + Tone.TimeBase.prototype._ticksToUnits = function (ticks) { + return ticks * (this._beatsToUnits(1) / Tone.Transport.PPQ); + }; + /** + * Return the time signature. + * @return {Number} + * @private + */ + Tone.TimeBase.prototype._timeSignature = function () { + return Tone.Transport.timeSignature; + }; + /////////////////////////////////////////////////////////////////////////// + // EXPRESSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Push an expression onto the expression list + * @param {Time} val + * @param {String} type + * @param {String} units + * @return {Tone.TimeBase} + * @private + */ + Tone.TimeBase.prototype._pushExpr = function (val, name, units) { + //create the expression + if (!(val instanceof Tone.TimeBase)) { + val = new this.constructor(val, units); + } + this._expr = this._binaryExpressions[name].method.bind(this, this._expr, val._expr); + return this; + }; + /** + * Add to the current value. + * @param {Time} val The value to add + * @param {String=} units Optional units to use with the value. + * @return {Tone.TimeBase} this + * @example + * Tone.TimeBase("2m").add("1m"); //"3m" + */ + Tone.TimeBase.prototype.add = function (val, units) { + return this._pushExpr(val, '+', units); + }; + /** + * Subtract the value from the current time. + * @param {Time} val The value to subtract + * @param {String=} units Optional units to use with the value. + * @return {Tone.TimeBase} this + * @example + * Tone.TimeBase("2m").sub("1m"); //"1m" + */ + Tone.TimeBase.prototype.sub = function (val, units) { + return this._pushExpr(val, '-', units); + }; + /** + * Multiply the current value by the given time. + * @param {Time} val The value to multiply + * @param {String=} units Optional units to use with the value. + * @return {Tone.TimeBase} this + * @example + * Tone.TimeBase("2m").mult("2"); //"4m" + */ + Tone.TimeBase.prototype.mult = function (val, units) { + return this._pushExpr(val, '*', units); + }; + /** + * Divide the current value by the given time. + * @param {Time} val The value to divide by + * @param {String=} units Optional units to use with the value. + * @return {Tone.TimeBase} this + * @example + * Tone.TimeBase("2m").div(2); //"1m" + */ + Tone.TimeBase.prototype.div = function (val, units) { + return this._pushExpr(val, '/', units); + }; + /** + * Evaluate the time value. Returns the time + * in seconds. + * @return {Seconds} + */ + Tone.TimeBase.prototype.valueOf = function () { + return this._expr(); + }; + /** + * Clean up + * @return {Tone.TimeBase} this + */ + Tone.TimeBase.prototype.dispose = function () { + this._expr = null; + }; + return Tone.TimeBase; + }); + Module(function (Tone) { + /** + * @class Tone.Time is a primitive type for encoding Time values. + * Eventually all time values are evaluated to seconds + * using the `eval` method. Tone.Time can be constructed + * with or without the `new` keyword. Tone.Time can be passed + * into the parameter of any method which takes time as an argument. + * @constructor + * @extends {Tone.TimeBase} + * @param {String|Number} val The time value. + * @param {String=} units The units of the value. + * @example + * var t = Tone.Time("4n");//encodes a quarter note + * t.mult(4); // multiply that value by 4 + * t.toNotation(); //returns "1m" + */ + Tone.Time = function (val, units) { + if (this instanceof Tone.Time) { + /** + * If the current clock time should + * be added to the output + * @type {Boolean} + * @private + */ + this._plusNow = false; + Tone.TimeBase.call(this, val, units); + } else { + return new Tone.Time(val, units); + } + }; + Tone.extend(Tone.Time, Tone.TimeBase); + //clone the expressions so that + //we can add more without modifying the original + Tone.Time.prototype._unaryExpressions = Object.create(Tone.TimeBase.prototype._unaryExpressions); + /* + * Adds an additional unary expression + * which quantizes values to the next subdivision + * @type {Object} + * @private + */ + Tone.Time.prototype._unaryExpressions.quantize = { + regexp: /^@/, + method: function (rh) { + return Tone.Transport.nextSubdivision(rh()); + } + }; + /* + * Adds an additional unary expression + * which adds the current clock time. + * @type {Object} + * @private + */ + Tone.Time.prototype._unaryExpressions.now = { + regexp: /^\+/, + method: function (lh) { + this._plusNow = true; + return lh(); + } + }; + /** + * Quantize the time by the given subdivision. Optionally add a + * percentage which will move the time value towards the ideal + * quantized value by that percentage. + * @param {Number|Time} val The subdivision to quantize to + * @param {NormalRange} [percent=1] Move the time value + * towards the quantized value by + * a percentage. + * @return {Tone.Time} this + * @example + * Tone.Time(21).quantize(2) //returns 22 + * Tone.Time(0.6).quantize("4n", 0.5) //returns 0.55 + */ + Tone.Time.prototype.quantize = function (subdiv, percent) { + percent = this.defaultArg(percent, 1); + this._expr = function (expr, subdivision, percent) { + expr = expr(); + subdivision = subdivision.toSeconds(); + var multiple = Math.round(expr / subdivision); + var ideal = multiple * subdivision; + var diff = ideal - expr; + return expr + diff * percent; + }.bind(this, this._expr, new this.constructor(subdiv), percent); + return this; + }; + /** + * Adds the clock time to the time expression at the + * moment of evaluation. + * @return {Tone.Time} this + */ + Tone.Time.prototype.addNow = function () { + this._plusNow = true; + return this; + }; + /** + * @override + * Override the default value return when no arguments are passed in. + * The default value is 'now' + * @private + */ + Tone.Time.prototype._defaultExpr = function () { + this._plusNow = true; + return this._noOp; + }; + /** + * Copies the value of time to this Time + * @param {Tone.Time} time + * @return {Time} + */ + Tone.Time.prototype.copy = function (time) { + Tone.TimeBase.prototype.copy.call(this, time); + this._plusNow = time._plusNow; + return this; + }; + //CONVERSIONS////////////////////////////////////////////////////////////// + /** + * Convert a Time to Notation. Values will be thresholded to the nearest 128th note. + * @return {Notation} + * @example + * //if the Transport is at 120bpm: + * Tone.Time(2).toNotation();//returns "1m" + */ + Tone.Time.prototype.toNotation = function () { + var time = this.toSeconds(); + var testNotations = [ + '1m', + '2n', + '4n', + '8n', + '16n', + '32n', + '64n', + '128n' + ]; + var retNotation = this._toNotationHelper(time, testNotations); + //try the same thing but with tripelets + var testTripletNotations = [ + '1m', + '2n', + '2t', + '4n', + '4t', + '8n', + '8t', + '16n', + '16t', + '32n', + '32t', + '64n', + '64t', + '128n' + ]; + var retTripletNotation = this._toNotationHelper(time, testTripletNotations); + //choose the simpler expression of the two + if (retTripletNotation.split('+').length < retNotation.split('+').length) { + return retTripletNotation; + } else { + return retNotation; + } + }; + /** + * Helper method for Tone.toNotation + * @param {Number} units + * @param {Array} testNotations + * @return {String} + * @private + */ + Tone.Time.prototype._toNotationHelper = function (units, testNotations) { + //the threshold is the last value in the array + var threshold = this._notationToUnits(testNotations[testNotations.length - 1]); + var retNotation = ''; + for (var i = 0; i < testNotations.length; i++) { + var notationTime = this._notationToUnits(testNotations[i]); + //account for floating point errors (i.e. round up if the value is 0.999999) + var multiple = units / notationTime; + var floatingPointError = 0.000001; + if (1 - multiple % 1 < floatingPointError) { + multiple += floatingPointError; + } + multiple = Math.floor(multiple); + if (multiple > 0) { + if (multiple === 1) { + retNotation += testNotations[i]; + } else { + retNotation += multiple.toString() + '*' + testNotations[i]; + } + units -= multiple * notationTime; + if (units < threshold) { + break; + } else { + retNotation += ' + '; + } + } + } + if (retNotation === '') { + retNotation = '0'; + } + return retNotation; + }; + /** + * Convert a notation value to the current units + * @param {Notation} notation + * @return {Number} + * @private + */ + Tone.Time.prototype._notationToUnits = function (notation) { + var primaryExprs = this._primaryExpressions; + var notationExprs = [ + primaryExprs.n, + primaryExprs.t, + primaryExprs.m + ]; + for (var i = 0; i < notationExprs.length; i++) { + var expr = notationExprs[i]; + var match = notation.match(expr.regexp); + if (match) { + return expr.method.call(this, match[1]); + } + } + }; + /** + * Return the time encoded as Bars:Beats:Sixteenths. + * @return {BarsBeatsSixteenths} + */ + Tone.Time.prototype.toBarsBeatsSixteenths = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.toSeconds() / quarterTime; + var measures = Math.floor(quarters / this._timeSignature()); + var sixteenths = quarters % 1 * 4; + quarters = Math.floor(quarters) % this._timeSignature(); + sixteenths = sixteenths.toString(); + if (sixteenths.length > 3) { + sixteenths = parseFloat(sixteenths).toFixed(3); + } + var progress = [ + measures, + quarters, + sixteenths + ]; + return progress.join(':'); + }; + /** + * Return the time in ticks. + * @return {Ticks} + */ + Tone.Time.prototype.toTicks = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.valueOf() / quarterTime; + return Math.floor(quarters * Tone.Transport.PPQ); + }; + /** + * Return the time in samples + * @return {Samples} + */ + Tone.Time.prototype.toSamples = function () { + return this.toSeconds() * this.context.sampleRate; + }; + /** + * Return the time as a frequency value + * @return {Frequency} + * @example + * Tone.Time(2).toFrequency(); //0.5 + */ + Tone.Time.prototype.toFrequency = function () { + return 1 / this.toSeconds(); + }; + /** + * Return the time in seconds. + * @return {Seconds} + */ + Tone.Time.prototype.toSeconds = function () { + return this.valueOf(); + }; + /** + * Return the time in milliseconds. + * @return {Milliseconds} + */ + Tone.Time.prototype.toMilliseconds = function () { + return this.toSeconds() * 1000; + }; + /** + * Return the time in seconds. + * @return {Seconds} + */ + Tone.Time.prototype.valueOf = function () { + var val = this._expr(); + return val + (this._plusNow ? this.now() : 0); + }; + return Tone.Time; + }); + Module(function (Tone) { + /** + * @class Tone.Frequency is a primitive type for encoding Frequency values. + * Eventually all time values are evaluated to hertz + * using the `eval` method. + * @constructor + * @extends {Tone.TimeBase} + * @param {String|Number} val The time value. + * @param {String=} units The units of the value. + * @example + * Tone.Frequency("C3") // 261 + * Tone.Frequency(38, "midi") // + * Tone.Frequency("C3").transpose(4); + */ + Tone.Frequency = function (val, units) { + if (this instanceof Tone.Frequency) { + Tone.TimeBase.call(this, val, units); + } else { + return new Tone.Frequency(val, units); + } + }; + Tone.extend(Tone.Frequency, Tone.TimeBase); + /////////////////////////////////////////////////////////////////////////// + // AUGMENT BASE EXPRESSIONS + /////////////////////////////////////////////////////////////////////////// + //clone the expressions so that + //we can add more without modifying the original + Tone.Frequency.prototype._primaryExpressions = Object.create(Tone.TimeBase.prototype._primaryExpressions); + /* + * midi type primary expression + * @type {Object} + * @private + */ + Tone.Frequency.prototype._primaryExpressions.midi = { + regexp: /^(\d+(?:\.\d+)?midi)/, + method: function (value) { + return this.midiToFrequency(value); + } + }; + /* + * note type primary expression + * @type {Object} + * @private + */ + Tone.Frequency.prototype._primaryExpressions.note = { + regexp: /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i, + method: function (pitch, octave) { + var index = noteToScaleIndex[pitch.toLowerCase()]; + var noteNumber = index + (parseInt(octave) + 1) * 12; + return this.midiToFrequency(noteNumber); + } + }; + /* + * BeatsBarsSixteenths type primary expression + * @type {Object} + * @private + */ + Tone.Frequency.prototype._primaryExpressions.tr = { + regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, + method: function (m, q, s) { + var total = 1; + if (m && m !== '0') { + total *= this._beatsToUnits(this._timeSignature() * parseFloat(m)); + } + if (q && q !== '0') { + total *= this._beatsToUnits(parseFloat(q)); + } + if (s && s !== '0') { + total *= this._beatsToUnits(parseFloat(s) / 4); + } + return total; + } + }; + /////////////////////////////////////////////////////////////////////////// + // EXPRESSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Transposes the frequency by the given number of semitones. + * @param {Interval} interval + * @return {Tone.Frequency} this + * @example + * Tone.Frequency("A4").transpose(3); //"C5" + */ + Tone.Frequency.prototype.transpose = function (interval) { + this._expr = function (expr, interval) { + var val = expr(); + return val * this.intervalToFrequencyRatio(interval); + }.bind(this, this._expr, interval); + return this; + }; + /** + * Takes an array of semitone intervals and returns + * an array of frequencies transposed by those intervals. + * @param {Array} intervals + * @return {Tone.Frequency} this + * @example + * Tone.Frequency("A4").harmonize([0, 3, 7]); //["A4", "C5", "E5"] + */ + Tone.Frequency.prototype.harmonize = function (intervals) { + this._expr = function (expr, intervals) { + var val = expr(); + var ret = []; + for (var i = 0; i < intervals.length; i++) { + ret[i] = val * this.intervalToFrequencyRatio(intervals[i]); + } + return ret; + }.bind(this, this._expr, intervals); + return this; + }; + /////////////////////////////////////////////////////////////////////////// + // UNIT CONVERSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Return the value of the frequency as a MIDI note + * @return {MIDI} + * @example + * Tone.Frequency("C4").toMidi(); //60 + */ + Tone.Frequency.prototype.toMidi = function () { + return this.frequencyToMidi(this.valueOf()); + }; + /** + * Return the value of the frequency in Scientific Pitch Notation + * @return {Note} + * @example + * Tone.Frequency(69, "midi").toNote(); //"A4" + */ + Tone.Frequency.prototype.toNote = function () { + var freq = this.valueOf(); + var log = Math.log(freq / Tone.Frequency.A4) / Math.LN2; + var noteNumber = Math.round(12 * log) + 57; + var octave = Math.floor(noteNumber / 12); + if (octave < 0) { + noteNumber += -12 * octave; + } + var noteName = scaleIndexToNote[noteNumber % 12]; + return noteName + octave.toString(); + }; + /** + * Return the duration of one cycle in seconds. + * @return {Seconds} + */ + Tone.Frequency.prototype.toSeconds = function () { + return 1 / this.valueOf(); + }; + /** + * Return the value in Hertz + * @return {Frequency} + */ + Tone.Frequency.prototype.toFrequency = function () { + return this.valueOf(); + }; + /** + * Return the duration of one cycle in ticks + * @return {Ticks} + */ + Tone.Frequency.prototype.toTicks = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.valueOf() / quarterTime; + return Math.floor(quarters * Tone.Transport.PPQ); + }; + /////////////////////////////////////////////////////////////////////////// + // UNIT CONVERSIONS HELPERS + /////////////////////////////////////////////////////////////////////////// + /** + * Returns the value of a frequency in the current units + * @param {Frequency} freq + * @return {Number} + * @private + */ + Tone.Frequency.prototype._frequencyToUnits = function (freq) { + return freq; + }; + /** + * Returns the value of a tick in the current time units + * @param {Ticks} ticks + * @return {Number} + * @private + */ + Tone.Frequency.prototype._ticksToUnits = function (ticks) { + return 1 / (ticks * 60 / (Tone.Transport.bpm.value * Tone.Transport.PPQ)); + }; + /** + * Return the value of the beats in the current units + * @param {Number} beats + * @return {Number} + * @private + */ + Tone.Frequency.prototype._beatsToUnits = function (beats) { + return 1 / Tone.TimeBase.prototype._beatsToUnits.call(this, beats); + }; + /** + * Returns the value of a second in the current units + * @param {Seconds} seconds + * @return {Number} + * @private + */ + Tone.Frequency.prototype._secondsToUnits = function (seconds) { + return 1 / seconds; + }; + /** + * The default units if none are given. + * @private + */ + Tone.Frequency.prototype._defaultUnits = 'hz'; + /////////////////////////////////////////////////////////////////////////// + // FREQUENCY CONVERSIONS + /////////////////////////////////////////////////////////////////////////// + /** + * Note to scale index + * @type {Object} + */ + var noteToScaleIndex = { + 'cbb': -2, + 'cb': -1, + 'c': 0, + 'c#': 1, + 'cx': 2, + 'dbb': 0, + 'db': 1, + 'd': 2, + 'd#': 3, + 'dx': 4, + 'ebb': 2, + 'eb': 3, + 'e': 4, + 'e#': 5, + 'ex': 6, + 'fbb': 3, + 'fb': 4, + 'f': 5, + 'f#': 6, + 'fx': 7, + 'gbb': 5, + 'gb': 6, + 'g': 7, + 'g#': 8, + 'gx': 9, + 'abb': 7, + 'ab': 8, + 'a': 9, + 'a#': 10, + 'ax': 11, + 'bbb': 9, + 'bb': 10, + 'b': 11, + 'b#': 12, + 'bx': 13 + }; + /** + * scale index to note (sharps) + * @type {Array} + */ + var scaleIndexToNote = [ + 'C', + 'C#', + 'D', + 'D#', + 'E', + 'F', + 'F#', + 'G', + 'G#', + 'A', + 'A#', + 'B' + ]; + /** + * The [concert pitch](https://en.wikipedia.org/wiki/Concert_pitch) + * A4's values in Hertz. + * @type {Frequency} + * @static + */ + Tone.Frequency.A4 = 440; + /** + * Convert a MIDI note to frequency value. + * @param {MIDI} midi The midi number to convert. + * @return {Frequency} the corresponding frequency value + * @example + * tone.midiToFrequency(69); // returns 440 + */ + Tone.Frequency.prototype.midiToFrequency = function (midi) { + return Tone.Frequency.A4 * Math.pow(2, (midi - 69) / 12); + }; + /** + * Convert a frequency value to a MIDI note. + * @param {Frequency} frequency The value to frequency value to convert. + * @returns {MIDI} + * @example + * tone.midiToFrequency(440); // returns 69 + */ + Tone.Frequency.prototype.frequencyToMidi = function (frequency) { + return 69 + 12 * Math.log(frequency / Tone.Frequency.A4) / Math.LN2; + }; + return Tone.Frequency; + }); + Module(function (Tone) { + /** + * @class Tone.TransportTime is a the time along the Transport's + * timeline. It is similar to Tone.Time, but instead of evaluating + * against the AudioContext's clock, it is evaluated against + * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime). + * @constructor + * @param {Time} val The time value as a number or string + * @param {String=} units Unit values + * @extends {Tone.Time} + */ + Tone.TransportTime = function (val, units) { + if (this instanceof Tone.TransportTime) { + Tone.Time.call(this, val, units); + } else { + return new Tone.TransportTime(val, units); + } + }; + Tone.extend(Tone.TransportTime, Tone.Time); + //clone the expressions so that + //we can add more without modifying the original + Tone.TransportTime.prototype._unaryExpressions = Object.create(Tone.Time.prototype._unaryExpressions); + /** + * Adds an additional unary expression + * which quantizes values to the next subdivision + * @type {Object} + * @private + */ + Tone.TransportTime.prototype._unaryExpressions.quantize = { + regexp: /^@/, + method: function (rh) { + var subdivision = this._secondsToTicks(rh()); + var multiple = Math.ceil(Tone.Transport.ticks / subdivision); + return this._ticksToUnits(multiple * subdivision); + } + }; + /** + * Convert seconds into ticks + * @param {Seconds} seconds + * @return {Ticks} + * @private + */ + Tone.TransportTime.prototype._secondsToTicks = function (seconds) { + var quarterTime = this._beatsToUnits(1); + var quarters = seconds / quarterTime; + return Math.round(quarters * Tone.Transport.PPQ); + }; + /** + * Evaluate the time expression. Returns values in ticks + * @return {Ticks} + */ + Tone.TransportTime.prototype.valueOf = function () { + var val = this._secondsToTicks(this._expr()); + return val + (this._plusNow ? Tone.Transport.ticks : 0); + }; + /** + * Return the time in ticks. + * @return {Ticks} + */ + Tone.TransportTime.prototype.toTicks = function () { + return this.valueOf(); + }; + /** + * Return the time in seconds. + * @return {Seconds} + */ + Tone.TransportTime.prototype.toSeconds = function () { + var val = this._expr(); + return val + (this._plusNow ? Tone.Transport.seconds : 0); + }; + /** + * Return the time as a frequency value + * @return {Frequency} + */ + Tone.TransportTime.prototype.toFrequency = function () { + return 1 / this.toSeconds(); + }; + return Tone.TransportTime; + }); + Module(function (Tone) { + + /** + * @class Tone.Emitter gives classes which extend it + * the ability to listen for and emit events. + * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js). + * MIT (c) 2011 Jerome Etienne. + * + * @extends {Tone} + */ + Tone.Emitter = function () { + /** + * Contains all of the events. + * @private + * @type {Object} + */ + this._events = {}; + }; + Tone.extend(Tone.Emitter); + /** + * Bind a callback to a specific event. + * @param {String} event The name of the event to listen for. + * @param {Function} callback The callback to invoke when the + * event is emitted + * @return {Tone.Emitter} this + */ + Tone.Emitter.prototype.on = function (event, callback) { + //split the event + var events = event.split(/\W+/); + for (var i = 0; i < events.length; i++) { + var eventName = events[i]; + if (!this._events.hasOwnProperty(eventName)) { + this._events[eventName] = []; + } + this._events[eventName].push(callback); + } + return this; + }; + /** + * Remove the event listener. + * @param {String} event The event to stop listening to. + * @param {Function=} callback The callback which was bound to + * the event with Tone.Emitter.on. + * If no callback is given, all callbacks + * events are removed. + * @return {Tone.Emitter} this + */ + Tone.Emitter.prototype.off = function (event, callback) { + var events = event.split(/\W+/); + for (var ev = 0; ev < events.length; ev++) { + event = events[ev]; + if (this._events.hasOwnProperty(event)) { + if (Tone.prototype.isUndef(callback)) { + this._events[event] = []; + } else { + var eventList = this._events[event]; + for (var i = 0; i < eventList.length; i++) { + if (eventList[i] === callback) { + eventList.splice(i, 1); + } + } + } + } + } + return this; + }; + /** + * Invoke all of the callbacks bound to the event + * with any arguments passed in. + * @param {String} event The name of the event. + * @param {*...} args The arguments to pass to the functions listening. + * @return {Tone.Emitter} this + */ + Tone.Emitter.prototype.emit = function (event) { + if (this._events) { + var args = Array.apply(null, arguments).slice(1); + if (this._events.hasOwnProperty(event)) { + var eventList = this._events[event]; + for (var i = 0, len = eventList.length; i < len; i++) { + eventList[i].apply(this, args); + } + } + } + return this; + }; + /** + * Add Emitter functions (on/off/emit) to the object + * @param {Object|Function} object The object or class to extend. + */ + Tone.Emitter.mixin = function (object) { + var functions = [ + 'on', + 'off', + 'emit' + ]; + object._events = {}; + for (var i = 0; i < functions.length; i++) { + var func = functions[i]; + var emitterFunc = Tone.Emitter.prototype[func]; + object[func] = emitterFunc; + } + }; + /** + * Clean up + * @return {Tone.Emitter} this + */ + Tone.Emitter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._events = null; + return this; + }; + return Tone.Emitter; + }); + Module(function (Tone) { + /** + * shim + * @private + */ + if (!window.hasOwnProperty('AudioContext') && window.hasOwnProperty('webkitAudioContext')) { + window.AudioContext = window.webkitAudioContext; + } + /** + * @class Wrapper around the native AudioContext. + * @extends {Tone.Emitter} + * @param {AudioContext=} context optionally pass in a context + */ + Tone.Context = function (context) { + Tone.Emitter.call(this); + if (!context) { + context = new window.AudioContext(); + } + this._context = context; + // extend all of the methods + for (var prop in this._context) { + this._defineProperty(this._context, prop); + } + /////////////////////////////////////////////////////////////////////// + // WORKER + /////////////////////////////////////////////////////////////////////// + /** + * The default latency hint + * @type {String} + * @private + */ + this._latencyHint = 'interactive'; + /** + * The amount of time events are scheduled + * into the future + * @type {Number} + * @private + */ + this._lookAhead = 0.1; + /** + * How often the update look runs + * @type {Number} + * @private + */ + this._updateInterval = this._lookAhead / 3; + /** + * A reference to the actual computed update interval + * @type {Number} + * @private + */ + this._computedUpdateInterval = 0; + /** + * The web worker which is used to update Tone.Clock + * @private + * @type {WebWorker} + */ + this._worker = this._createWorker(); + /** + * An object containing all of the constants AudioBufferSourceNodes + * @type {Object} + * @private + */ + this._constants = {}; + }; + Tone.extend(Tone.Context, Tone.Emitter); + Tone.Emitter.mixin(Tone.Context); + /** + * Define a property on this Tone.Context. + * This is used to extend the native AudioContext + * @param {AudioContext} context + * @param {String} prop + * @private + */ + Tone.Context.prototype._defineProperty = function (context, prop) { + if (this.isUndef(this[prop])) { + Object.defineProperty(this, prop, { + get: function () { + if (typeof context[prop] === 'function') { + return context[prop].bind(context); + } else { + return context[prop]; + } + }, + set: function (val) { + context[prop] = val; + } + }); + } + }; + /** + * The current audio context time + * @return {Number} + */ + Tone.Context.prototype.now = function () { + return this._context.currentTime; + }; + /** + * Generate a web worker + * @return {WebWorker} + * @private + */ + Tone.Context.prototype._createWorker = function () { + //URL Shim + window.URL = window.URL || window.webkitURL; + var blob = new Blob([//the initial timeout time + 'var timeoutTime = ' + (this._updateInterval * 1000).toFixed(1) + ';' + //onmessage callback + 'self.onmessage = function(msg){' + '\ttimeoutTime = parseInt(msg.data);' + '};' + //the tick function which posts a message + //and schedules a new tick + 'function tick(){' + '\tsetTimeout(tick, timeoutTime);' + '\tself.postMessage(\'tick\');' + '}' + //call tick initially + 'tick();']); + var blobUrl = URL.createObjectURL(blob); + var worker = new Worker(blobUrl); + worker.addEventListener('message', function () { + // tick the clock + this.emit('tick'); + }.bind(this)); + //lag compensation + worker.addEventListener('message', function () { + var now = this.now(); + if (this.isNumber(this._lastUpdate)) { + var diff = now - this._lastUpdate; + this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97); + } + this._lastUpdate = now; + }.bind(this)); + return worker; + }; + /** + * Generate a looped buffer at some constant value. + * @param {Number} val + * @return {BufferSourceNode} + */ + Tone.Context.prototype.getConstant = function (val) { + if (this._constants[val]) { + return this._constants[val]; + } else { + var buffer = this._context.createBuffer(1, 128, this._context.sampleRate); + var arr = buffer.getChannelData(0); + for (var i = 0; i < arr.length; i++) { + arr[i] = val; + } + var constant = this._context.createBufferSource(); + constant.channelCount = 1; + constant.channelCountMode = 'explicit'; + constant.buffer = buffer; + constant.loop = true; + constant.start(0); + this._constants[val] = constant; + return constant; + } + }; + /** + * This is the time that the clock is falling behind + * the scheduled update interval. The Context automatically + * adjusts for the lag and schedules further in advance. + * @type {Number} + * @memberOf Tone.Context + * @name lag + * @static + * @readOnly + */ + Object.defineProperty(Tone.Context.prototype, 'lag', { + get: function () { + var diff = this._computedUpdateInterval - this._updateInterval; + diff = Math.max(diff, 0); + return diff; + } + }); + /** + * The amount of time in advance that events are scheduled. + * The lookAhead will adjust slightly in response to the + * measured update time to try to avoid clicks. + * @type {Number} + * @memberOf Tone.Context + * @name lookAhead + * @static + */ + Object.defineProperty(Tone.Context.prototype, 'lookAhead', { + get: function () { + return this._lookAhead; + }, + set: function (lA) { + this._lookAhead = lA; + } + }); + /** + * How often the Web Worker callback is invoked. + * This number corresponds to how responsive the scheduling + * can be. Context.updateInterval + Context.lookAhead gives you the + * total latency between scheduling an event and hearing it. + * @type {Number} + * @memberOf Tone.Context + * @name updateInterval + * @static + */ + Object.defineProperty(Tone.Context.prototype, 'updateInterval', { + get: function () { + return this._updateInterval; + }, + set: function (interval) { + this._updateInterval = Math.max(interval, Tone.prototype.blockTime); + this._worker.postMessage(Math.max(interval * 1000, 1)); + } + }); + /** + * The type of playback, which affects tradeoffs between audio + * output latency and responsiveness. + * + * In addition to setting the value in seconds, the latencyHint also + * accepts the strings "interactive" (prioritizes low latency), + * "playback" (prioritizes sustained playback), "balanced" (balances + * latency and performance), and "fastest" (lowest latency, might glitch more often). + * @type {String|Seconds} + * @memberOf Tone.Context# + * @name latencyHint + * @static + * @example + * //set the lookAhead to 0.3 seconds + * Tone.context.latencyHint = 0.3; + */ + Object.defineProperty(Tone.Context.prototype, 'latencyHint', { + get: function () { + return this._latencyHint; + }, + set: function (hint) { + var lookAhead = hint; + this._latencyHint = hint; + if (this.isString(hint)) { + switch (hint) { + case 'interactive': + lookAhead = 0.1; + this._context.latencyHint = hint; + break; + case 'playback': + lookAhead = 0.8; + this._context.latencyHint = hint; + break; + case 'balanced': + lookAhead = 0.25; + this._context.latencyHint = hint; + break; + case 'fastest': + lookAhead = 0.01; + break; + } + } + this.lookAhead = lookAhead; + this.updateInterval = lookAhead / 3; + } + }); + /** + * Shim all connect/disconnect and some deprecated methods which are still in + * some older implementations. + * @private + */ + function shimConnect() { + var nativeConnect = AudioNode.prototype.connect; + var nativeDisconnect = AudioNode.prototype.disconnect; + //replace the old connect method + function toneConnect(B, outNum, inNum) { + if (B.input) { + if (Array.isArray(B.input)) { + if (Tone.prototype.isUndef(inNum)) { + inNum = 0; + } + this.connect(B.input[inNum]); + } else { + this.connect(B.input, outNum, inNum); + } + } else { + try { + if (B instanceof AudioNode) { + nativeConnect.call(this, B, outNum, inNum); + } else { + nativeConnect.call(this, B, outNum); + } + } catch (e) { + throw new Error('error connecting to node: ' + B + '\n' + e); + } + } + } + //replace the old disconnect method + function toneDisconnect(B, outNum, inNum) { + if (B && B.input && Array.isArray(B.input)) { + if (Tone.prototype.isUndef(inNum)) { + inNum = 0; + } + this.disconnect(B.input[inNum], outNum, inNum); + } else if (B && B.input) { + this.disconnect(B.input, outNum, inNum); + } else { + try { + nativeDisconnect.apply(this, arguments); + } catch (e) { + throw new Error('error disconnecting node: ' + B + '\n' + e); + } + } + } + if (AudioNode.prototype.connect !== toneConnect) { + AudioNode.prototype.connect = toneConnect; + AudioNode.prototype.disconnect = toneDisconnect; + } + } + // set the audio context initially + if (Tone.supported) { + shimConnect(); + Tone.context = new Tone.Context(); + } else { + console.warn('This browser does not support Tone.js'); + } + return Tone.Context; + }); + Module(function (Tone) { + /////////////////////////////////////////////////////////////////////////// + // TYPES + /////////////////////////////////////////////////////////////////////////// + /** + * Units which a value can take on. + * @enum {String} + */ + Tone.Type = { + /** + * Default units + * @typedef {Default} + */ + Default: 'number', + /** + * Time can be described in a number of ways. Read more [Time](https://github.com/Tonejs/Tone.js/wiki/Time). + * + *
    + *
  • Numbers, which will be taken literally as the time (in seconds).
  • + *
  • Notation, ("4n", "8t") describes time in BPM and time signature relative values.
  • + *
  • TransportTime, ("4:3:2") will also provide tempo and time signature relative times + * in the form BARS:QUARTERS:SIXTEENTHS.
  • + *
  • Frequency, ("8hz") is converted to the length of the cycle in seconds.
  • + *
  • Now-Relative, ("+1") prefix any of the above with "+" and it will be interpreted as + * "the current time plus whatever expression follows".
  • + *
  • Expressions, ("3:0 + 2 - (1m / 7)") any of the above can also be combined + * into a mathematical expression which will be evaluated to compute the desired time.
  • + *
  • No Argument, for methods which accept time, no argument will be interpreted as + * "now" (i.e. the currentTime).
  • + *
+ * + * @typedef {Time} + */ + Time: 'time', + /** + * Frequency can be described similar to time, except ultimately the + * values are converted to frequency instead of seconds. A number + * is taken literally as the value in hertz. Additionally any of the + * Time encodings can be used. Note names in the form + * of NOTE OCTAVE (i.e. C4) are also accepted and converted to their + * frequency value. + * @typedef {Frequency} + */ + Frequency: 'frequency', + /** + * TransportTime describes a position along the Transport's timeline. It is + * similar to Time in that it uses all the same encodings, but TransportTime specifically + * pertains to the Transport's timeline, which is startable, stoppable, loopable, and seekable. + * [Read more](https://github.com/Tonejs/Tone.js/wiki/TransportTime) + * @typedef {TransportTime} + */ + TransportTime: 'transportTime', + /** + * Ticks are the basic subunit of the Transport. They are + * the smallest unit of time that the Transport supports. + * @typedef {Ticks} + */ + Ticks: 'ticks', + /** + * Normal values are within the range [0, 1]. + * @typedef {NormalRange} + */ + NormalRange: 'normalRange', + /** + * AudioRange values are between [-1, 1]. + * @typedef {AudioRange} + */ + AudioRange: 'audioRange', + /** + * Decibels are a logarithmic unit of measurement which is useful for volume + * because of the logarithmic way that we perceive loudness. 0 decibels + * means no change in volume. -10db is approximately half as loud and 10db + * is twice is loud. + * @typedef {Decibels} + */ + Decibels: 'db', + /** + * Half-step note increments, i.e. 12 is an octave above the root. and 1 is a half-step up. + * @typedef {Interval} + */ + Interval: 'interval', + /** + * Beats per minute. + * @typedef {BPM} + */ + BPM: 'bpm', + /** + * The value must be greater than or equal to 0. + * @typedef {Positive} + */ + Positive: 'positive', + /** + * A cent is a hundredth of a semitone. + * @typedef {Cents} + */ + Cents: 'cents', + /** + * Angle between 0 and 360. + * @typedef {Degrees} + */ + Degrees: 'degrees', + /** + * A number representing a midi note. + * @typedef {MIDI} + */ + MIDI: 'midi', + /** + * A colon-separated representation of time in the form of + * Bars:Beats:Sixteenths. + * @typedef {BarsBeatsSixteenths} + */ + BarsBeatsSixteenths: 'barsBeatsSixteenths', + /** + * Sampling is the reduction of a continuous signal to a discrete signal. + * Audio is typically sampled 44100 times per second. + * @typedef {Samples} + */ + Samples: 'samples', + /** + * Hertz are a frequency representation defined as one cycle per second. + * @typedef {Hertz} + */ + Hertz: 'hertz', + /** + * A frequency represented by a letter name, + * accidental and octave. This system is known as + * [Scientific Pitch Notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation). + * @typedef {Note} + */ + Note: 'note', + /** + * One millisecond is a thousandth of a second. + * @typedef {Milliseconds} + */ + Milliseconds: 'milliseconds', + /** + * Seconds are the time unit of the AudioContext. In the end, + * all values need to be evaluated to seconds. + * @typedef {Seconds} + */ + Seconds: 'seconds', + /** + * A string representing a duration relative to a measure. + *
    + *
  • "4n" = quarter note
  • + *
  • "2m" = two measures
  • + *
  • "8t" = eighth-note triplet
  • + *
+ * @typedef {Notation} + */ + Notation: 'notation' + }; + /////////////////////////////////////////////////////////////////////////// + // AUGMENT TONE's PROTOTYPE + /////////////////////////////////////////////////////////////////////////// + /** + * Convert Time into seconds. + * + * Unlike the method which it overrides, this takes into account + * transporttime and musical notation. + * + * Time : 1.40 + * Notation: 4n|1m|2t + * Now Relative: +3n + * Math: 3n+16n or even complicated expressions ((3n*2)/6 + 1) + * + * @param {Time} time + * @return {Seconds} + */ + Tone.prototype.toSeconds = function (time) { + if (this.isNumber(time)) { + return time; + } else if (this.isUndef(time)) { + return this.now(); + } else if (this.isString(time)) { + return new Tone.Time(time).toSeconds(); + } else if (time instanceof Tone.TimeBase) { + return time.toSeconds(); + } + }; + /** + * Convert a frequency representation into a number. + * @param {Frequency} freq + * @return {Hertz} the frequency in hertz + */ + Tone.prototype.toFrequency = function (freq) { + if (this.isNumber(freq)) { + return freq; + } else if (this.isString(freq) || this.isUndef(freq)) { + return new Tone.Frequency(freq).valueOf(); + } else if (freq instanceof Tone.TimeBase) { + return freq.toFrequency(); + } + }; + /** + * Convert a time representation into ticks. + * @param {Time} time + * @return {Ticks} the time in ticks + */ + Tone.prototype.toTicks = function (time) { + if (this.isNumber(time) || this.isString(time)) { + return new Tone.TransportTime(time).toTicks(); + } else if (this.isUndef(time)) { + return Tone.Transport.ticks; + } else if (time instanceof Tone.TimeBase) { + return time.toTicks(); + } + }; + return Tone; + }); + Module(function (Tone) { + + /** + * @class Tone.Param wraps the native Web Audio's AudioParam to provide + * additional unit conversion functionality. It also + * serves as a base-class for classes which have a single, + * automatable parameter. + * @extends {Tone} + * @param {AudioParam} param The parameter to wrap. + * @param {Tone.Type} units The units of the audio param. + * @param {Boolean} convert If the param should be converted. + */ + Tone.Param = function () { + var options = this.optionsObject(arguments, [ + 'param', + 'units', + 'convert' + ], Tone.Param.defaults); + /** + * The native parameter to control + * @type {AudioParam} + * @private + */ + this._param = this.input = options.param; + /** + * The units of the parameter + * @type {Tone.Type} + */ + this.units = options.units; + /** + * If the value should be converted or not + * @type {Boolean} + */ + this.convert = options.convert; + /** + * True if the signal value is being overridden by + * a connected signal. + * @readOnly + * @type {boolean} + * @private + */ + this.overridden = false; + /** + * If there is an LFO, this is where it is held. + * @type {Tone.LFO} + * @private + */ + this._lfo = null; + if (this.isObject(options.lfo)) { + this.value = options.lfo; + } else if (!this.isUndef(options.value)) { + this.value = options.value; + } + }; + Tone.extend(Tone.Param); + /** + * Defaults + * @type {Object} + * @const + */ + Tone.Param.defaults = { + 'units': Tone.Type.Default, + 'convert': true, + 'param': undefined + }; + /** + * The current value of the parameter. + * @memberOf Tone.Param# + * @type {Number} + * @name value + */ + Object.defineProperty(Tone.Param.prototype, 'value', { + get: function () { + return this._toUnits(this._param.value); + }, + set: function (value) { + if (this.isObject(value)) { + //throw an error if the LFO needs to be included + if (this.isUndef(Tone.LFO)) { + throw new Error('Include \'Tone.LFO\' to use an LFO as a Param value.'); + } + //remove the old one + if (this._lfo) { + this._lfo.dispose(); + } + this._lfo = new Tone.LFO(value).start(); + this._lfo.connect(this.input); + } else { + var convertedVal = this._fromUnits(value); + this._param.cancelScheduledValues(0); + this._param.value = convertedVal; + } + } + }); + /** + * Convert the given value from the type specified by Tone.Param.units + * into the destination value (such as Gain or Frequency). + * @private + * @param {*} val the value to convert + * @return {number} the number which the value should be set to + */ + Tone.Param.prototype._fromUnits = function (val) { + if (this.convert || this.isUndef(this.convert)) { + switch (this.units) { + case Tone.Type.Time: + return this.toSeconds(val); + case Tone.Type.Frequency: + return this.toFrequency(val); + case Tone.Type.Decibels: + return this.dbToGain(val); + case Tone.Type.NormalRange: + return Math.min(Math.max(val, 0), 1); + case Tone.Type.AudioRange: + return Math.min(Math.max(val, -1), 1); + case Tone.Type.Positive: + return Math.max(val, 0); + default: + return val; + } + } else { + return val; + } + }; + /** + * Convert the parameters value into the units specified by Tone.Param.units. + * @private + * @param {number} val the value to convert + * @return {number} + */ + Tone.Param.prototype._toUnits = function (val) { + if (this.convert || this.isUndef(this.convert)) { + switch (this.units) { + case Tone.Type.Decibels: + return this.gainToDb(val); + default: + return val; + } + } else { + return val; + } + }; + /** + * the minimum output value + * @type {Number} + * @private + */ + Tone.Param.prototype._minOutput = 0.00001; + /** + * Schedules a parameter value change at the given time. + * @param {*} value The value to set the signal. + * @param {Time} time The time when the change should occur. + * @returns {Tone.Param} this + * @example + * //set the frequency to "G4" in exactly 1 second from now. + * freq.setValueAtTime("G4", "+1"); + */ + Tone.Param.prototype.setValueAtTime = function (value, time) { + value = this._fromUnits(value); + time = this.toSeconds(time); + if (time <= this.now() + this.blockTime) { + this._param.value = value; + } else { + this._param.setValueAtTime(value, time); + } + return this; + }; + /** + * Creates a schedule point with the current value at the current time. + * This is useful for creating an automation anchor point in order to + * schedule changes from the current value. + * + * @param {number=} now (Optionally) pass the now value in. + * @returns {Tone.Param} this + */ + Tone.Param.prototype.setRampPoint = function (now) { + now = this.defaultArg(now, this.now()); + var currentVal = this._param.value; + // exponentialRampToValueAt cannot ever ramp from or to 0 + // More info: https://bugzilla.mozilla.org/show_bug.cgi?id=1125600#c2 + if (currentVal === 0) { + currentVal = this._minOutput; + } + this._param.setValueAtTime(currentVal, now); + return this; + }; + /** + * Schedules a linear continuous change in parameter value from the + * previous scheduled parameter value to the given value. + * + * @param {number} value + * @param {Time} endTime + * @returns {Tone.Param} this + */ + Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); + return this; + }; + /** + * Schedules an exponential continuous change in parameter value from + * the previous scheduled parameter value to the given value. + * + * @param {number} value + * @param {Time} endTime + * @returns {Tone.Param} this + */ + Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + value = Math.max(this._minOutput, value); + this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); + return this; + }; + /** + * Schedules an exponential continuous change in parameter value from + * the current time and current value to the given value over the + * duration of the rampTime. + * + * @param {number} value The value to ramp to. + * @param {Time} rampTime the time that it takes the + * value to ramp from it's current value + * @param {Time} [startTime=now] When the ramp should start. + * @returns {Tone.Param} this + * @example + * //exponentially ramp to the value 2 over 4 seconds. + * signal.exponentialRampToValue(2, 4); + */ + Tone.Param.prototype.exponentialRampToValue = function (value, rampTime, startTime) { + startTime = this.toSeconds(startTime); + this.setRampPoint(startTime); + this.exponentialRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); + return this; + }; + /** + * Schedules an linear continuous change in parameter value from + * the current time and current value to the given value over the + * duration of the rampTime. + * + * @param {number} value The value to ramp to. + * @param {Time} rampTime the time that it takes the + * value to ramp from it's current value + * @param {Time} [startTime=now] When the ramp should start. + * @returns {Tone.Param} this + * @example + * //linearly ramp to the value 4 over 3 seconds. + * signal.linearRampToValue(4, 3); + */ + Tone.Param.prototype.linearRampToValue = function (value, rampTime, startTime) { + startTime = this.toSeconds(startTime); + this.setRampPoint(startTime); + this.linearRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); + return this; + }; + /** + * Start exponentially approaching the target value at the given time with + * a rate having the given time constant. + * @param {number} value + * @param {Time} startTime + * @param {number} timeConstant + * @returns {Tone.Param} this + */ + Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { + value = this._fromUnits(value); + // The value will never be able to approach without timeConstant > 0. + // http://www.w3.org/TR/webaudio/#dfn-setTargetAtTime, where the equation + // is described. 0 results in a division by 0. + value = Math.max(this._minOutput, value); + timeConstant = Math.max(this._minOutput, timeConstant); + this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); + return this; + }; + /** + * Sets an array of arbitrary parameter values starting at the given time + * for the given duration. + * + * @param {Array} values + * @param {Time} startTime + * @param {Time} duration + * @returns {Tone.Param} this + */ + Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { + for (var i = 0; i < values.length; i++) { + values[i] = this._fromUnits(values[i]); + } + this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); + return this; + }; + /** + * Cancels all scheduled parameter changes with times greater than or + * equal to startTime. + * + * @param {Time} startTime + * @returns {Tone.Param} this + */ + Tone.Param.prototype.cancelScheduledValues = function (startTime) { + this._param.cancelScheduledValues(this.toSeconds(startTime)); + return this; + }; + /** + * Ramps to the given value over the duration of the rampTime. + * Automatically selects the best ramp type (exponential or linear) + * depending on the `units` of the signal + * + * @param {number} value + * @param {Time} rampTime The time that it takes the + * value to ramp from it's current value + * @param {Time} [startTime=now] When the ramp should start. + * @returns {Tone.Param} this + * @example + * //ramp to the value either linearly or exponentially + * //depending on the "units" value of the signal + * signal.rampTo(0, 10); + * @example + * //schedule it to ramp starting at a specific time + * signal.rampTo(0, 10, 5) + */ + Tone.Param.prototype.rampTo = function (value, rampTime, startTime) { + rampTime = this.defaultArg(rampTime, 0); + if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM || this.units === Tone.Type.Decibels) { + this.exponentialRampToValue(value, rampTime, startTime); + } else { + this.linearRampToValue(value, rampTime, startTime); + } + return this; + }; + /** + * The LFO created by the signal instance. If none + * was created, this is null. + * @type {Tone.LFO} + * @readOnly + * @memberOf Tone.Param# + * @name lfo + */ + Object.defineProperty(Tone.Param.prototype, 'lfo', { + get: function () { + return this._lfo; + } + }); + /** + * Clean up + * @returns {Tone.Param} this + */ + Tone.Param.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._param = null; + if (this._lfo) { + this._lfo.dispose(); + this._lfo = null; + } + return this; + }; + return Tone.Param; + }); + Module(function (Tone) { + + /** + * createGain shim + * @private + */ + if (window.GainNode && !AudioContext.prototype.createGain) { + AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; + } + /** + * @class A thin wrapper around the Native Web Audio GainNode. + * The GainNode is a basic building block of the Web Audio + * API and is useful for routing audio and adjusting gains. + * @extends {Tone} + * @param {Number=} gain The initial gain of the GainNode + * @param {Tone.Type=} units The units of the gain parameter. + */ + Tone.Gain = function () { + var options = this.optionsObject(arguments, [ + 'gain', + 'units' + ], Tone.Gain.defaults); + /** + * The GainNode + * @type {GainNode} + * @private + */ + this.input = this.output = this._gainNode = this.context.createGain(); + /** + * The gain parameter of the gain node. + * @type {Tone.Param} + * @signal + */ + this.gain = new Tone.Param({ + 'param': this._gainNode.gain, + 'units': options.units, + 'value': options.gain, + 'convert': options.convert + }); + this._readOnly('gain'); + }; + Tone.extend(Tone.Gain); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.Gain.defaults = { + 'gain': 1, + 'convert': true + }; + /** + * Clean up. + * @return {Tone.Gain} this + */ + Tone.Gain.prototype.dispose = function () { + Tone.Param.prototype.dispose.call(this); + this._gainNode.disconnect(); + this._gainNode = null; + this._writable('gain'); + this.gain.dispose(); + this.gain = null; + }; + //STATIC/////////////////////////////////////////////////////////////////// + /** + * Create input and outputs for this object. + * @param {Number} input The number of inputs + * @param {Number=} outputs The number of outputs + * @return {Tone} this + * @internal + */ + Tone.prototype.createInsOuts = function (inputs, outputs) { + if (inputs === 1) { + this.input = new Tone.Gain(); + } else if (inputs > 1) { + this.input = new Array(inputs); + } + if (outputs === 1) { + this.output = new Tone.Gain(); + } else if (outputs > 1) { + this.output = new Array(inputs); + } + }; + /////////////////////////////////////////////////////////////////////////// + return Tone.Gain; + }); + Module(function (Tone) { + + /** + * @class A signal is an audio-rate value. Tone.Signal is a core component of the library. + * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal + * has all of the methods available to native Web Audio + * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface) + * as well as additional conveniences. Read more about working with signals + * [here](https://github.com/Tonejs/Tone.js/wiki/Signals). + * + * @constructor + * @extends {Tone.Param} + * @param {Number|AudioParam} [value] Initial value of the signal. If an AudioParam + * is passed in, that parameter will be wrapped + * and controlled by the Signal. + * @param {string} [units=Number] unit The units the signal is in. + * @example + * var signal = new Tone.Signal(10); + */ + Tone.Signal = function () { + var options = this.optionsObject(arguments, [ + 'value', + 'units' + ], Tone.Signal.defaults); + /** + * The node where the constant signal value is scaled. + * @type {GainNode} + * @private + */ + this.output = this._gain = this.context.createGain(); + options.param = this._gain.gain; + Tone.Param.call(this, options); + /** + * The node where the value is set. + * @type {Tone.Param} + * @private + */ + this.input = this._param = this._gain.gain; + //connect the const output to the node output + this.context.getConstant(1).chain(this._gain); + }; + Tone.extend(Tone.Signal, Tone.Param); + /** + * The default values + * @type {Object} + * @static + * @const + */ + Tone.Signal.defaults = { + 'value': 0, + 'units': Tone.Type.Default, + 'convert': true + }; + /** + * When signals connect to other signals or AudioParams, + * they take over the output value of that signal or AudioParam. + * For all other nodes, the behavior is the same as a default connect. + * + * @override + * @param {AudioParam|AudioNode|Tone.Signal|Tone} node + * @param {number} [outputNumber=0] The output number to connect from. + * @param {number} [inputNumber=0] The input number to connect to. + * @returns {Tone.SignalBase} this + * @method + */ + Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; + /** + * dispose and disconnect + * @returns {Tone.Signal} this + */ + Tone.Signal.prototype.dispose = function () { + Tone.Param.prototype.dispose.call(this); + this._param = null; + this._gain.disconnect(); + this._gain = null; + return this; + }; + return Tone.Signal; + }); + Module(function (Tone) { + + /** + * @class A Timeline class for scheduling and maintaining state + * along a timeline. All events must have a "time" property. + * Internally, events are stored in time order for fast + * retrieval. + * @extends {Tone} + * @param {Positive} [memory=Infinity] The number of previous events that are retained. + */ + Tone.Timeline = function () { + var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); + /** + * The array of scheduled timeline events + * @type {Array} + * @private + */ + this._timeline = []; + /** + * An array of items to remove from the list. + * @type {Array} + * @private + */ + this._toRemove = []; + /** + * Flag if the tieline is mid iteration + * @private + * @type {Boolean} + */ + this._iterating = false; + /** + * The memory of the timeline, i.e. + * how many events in the past it will retain + * @type {Positive} + */ + this.memory = options.memory; + }; + Tone.extend(Tone.Timeline); + /** + * the default parameters + * @static + * @const + */ + Tone.Timeline.defaults = { 'memory': Infinity }; + /** + * The number of items in the timeline. + * @type {Number} + * @memberOf Tone.Timeline# + * @name length + * @readOnly + */ + Object.defineProperty(Tone.Timeline.prototype, 'length', { + get: function () { + return this._timeline.length; + } + }); + /** + * Insert an event object onto the timeline. Events must have a "time" attribute. + * @param {Object} event The event object to insert into the + * timeline. + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.add = function (event) { + //the event needs to have a time attribute + if (this.isUndef(event.time)) { + throw new Error('Tone.Timeline: events must have a time attribute'); + } + if (this._timeline.length) { + var index = this._search(event.time); + this._timeline.splice(index + 1, 0, event); + } else { + this._timeline.push(event); + } + //if the length is more than the memory, remove the previous ones + if (this.length > this.memory) { + var diff = this.length - this.memory; + this._timeline.splice(0, diff); + } + return this; + }; + /** + * Remove an event from the timeline. + * @param {Object} event The event object to remove from the list. + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.remove = function (event) { + if (this._iterating) { + this._toRemove.push(event); + } else { + var index = this._timeline.indexOf(event); + if (index !== -1) { + this._timeline.splice(index, 1); + } + } + return this; + }; + /** + * Get the nearest event whose time is less than or equal to the given time. + * @param {Number} time The time to query. + * @returns {Object} The event object set after that time. + */ + Tone.Timeline.prototype.get = function (time) { + var index = this._search(time); + if (index !== -1) { + return this._timeline[index]; + } else { + return null; + } + }; + /** + * Return the first event in the timeline without removing it + * @returns {Object} The first event object + */ + Tone.Timeline.prototype.peek = function () { + return this._timeline[0]; + }; + /** + * Return the first event in the timeline and remove it + * @returns {Object} The first event object + */ + Tone.Timeline.prototype.shift = function () { + return this._timeline.shift(); + }; + /** + * Get the event which is scheduled after the given time. + * @param {Number} time The time to query. + * @returns {Object} The event object after the given time + */ + Tone.Timeline.prototype.getAfter = function (time) { + var index = this._search(time); + if (index + 1 < this._timeline.length) { + return this._timeline[index + 1]; + } else { + return null; + } + }; + /** + * Get the event before the event at the given time. + * @param {Number} time The time to query. + * @returns {Object} The event object before the given time + */ + Tone.Timeline.prototype.getBefore = function (time) { + var len = this._timeline.length; + //if it's after the last item, return the last item + if (len > 0 && this._timeline[len - 1].time < time) { + return this._timeline[len - 1]; + } + var index = this._search(time); + if (index - 1 >= 0) { + return this._timeline[index - 1]; + } else { + return null; + } + }; + /** + * Cancel events after the given time + * @param {Number} time The time to query. + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.cancel = function (after) { + if (this._timeline.length > 1) { + var index = this._search(after); + if (index >= 0) { + if (this._timeline[index].time === after) { + //get the first item with that time + for (var i = index; i >= 0; i--) { + if (this._timeline[i].time === after) { + index = i; + } else { + break; + } + } + this._timeline = this._timeline.slice(0, index); + } else { + this._timeline = this._timeline.slice(0, index + 1); + } + } else { + this._timeline = []; + } + } else if (this._timeline.length === 1) { + //the first item's time + if (this._timeline[0].time >= after) { + this._timeline = []; + } + } + return this; + }; + /** + * Cancel events before or equal to the given time. + * @param {Number} time The time to cancel before. + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.cancelBefore = function (time) { + if (this._timeline.length) { + var index = this._search(time); + if (index >= 0) { + this._timeline = this._timeline.slice(index + 1); + } + } + return this; + }; + /** + * Does a binary serach on the timeline array and returns the + * nearest event index whose time is after or equal to the given time. + * If a time is searched before the first index in the timeline, -1 is returned. + * If the time is after the end, the index of the last item is returned. + * @param {Number} time + * @return {Number} the index in the timeline array + * @private + */ + Tone.Timeline.prototype._search = function (time) { + var beginning = 0; + var len = this._timeline.length; + var end = len; + if (len > 0 && this._timeline[len - 1].time <= time) { + return len - 1; + } + while (beginning < end) { + // calculate the midpoint for roughly equal partition + var midPoint = Math.floor(beginning + (end - beginning) / 2); + var event = this._timeline[midPoint]; + var nextEvent = this._timeline[midPoint + 1]; + if (event.time === time) { + //choose the last one that has the same time + for (var i = midPoint; i < this._timeline.length; i++) { + var testEvent = this._timeline[i]; + if (testEvent.time === time) { + midPoint = i; + } + } + return midPoint; + } else if (event.time < time && nextEvent.time > time) { + return midPoint; + } else if (event.time > time) { + //search lower + end = midPoint; + } else if (event.time < time) { + //search upper + beginning = midPoint + 1; + } + } + return -1; + }; + /** + * Internal iterator. Applies extra safety checks for + * removing items from the array. + * @param {Function} callback + * @param {Number=} lowerBound + * @param {Number=} upperBound + * @private + */ + Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { + this._iterating = true; + lowerBound = this.defaultArg(lowerBound, 0); + upperBound = this.defaultArg(upperBound, this._timeline.length - 1); + for (var i = lowerBound; i <= upperBound; i++) { + callback(this._timeline[i]); + } + this._iterating = false; + if (this._toRemove.length > 0) { + for (var j = 0; j < this._toRemove.length; j++) { + var index = this._timeline.indexOf(this._toRemove[j]); + if (index !== -1) { + this._timeline.splice(index, 1); + } + } + this._toRemove = []; + } + }; + /** + * Iterate over everything in the array + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.forEach = function (callback) { + this._iterate(callback); + return this; + }; + /** + * Iterate over everything in the array at or before the given time. + * @param {Number} time The time to check if items are before + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.forEachBefore = function (time, callback) { + //iterate over the items in reverse so that removing an item doesn't break things + var upperBound = this._search(time); + if (upperBound !== -1) { + this._iterate(callback, 0, upperBound); + } + return this; + }; + /** + * Iterate over everything in the array after the given time. + * @param {Number} time The time to check if items are before + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.forEachAfter = function (time, callback) { + //iterate over the items in reverse so that removing an item doesn't break things + var lowerBound = this._search(time); + this._iterate(callback, lowerBound + 1); + return this; + }; + /** + * Iterate over everything in the array at or after the given time. Similar to + * forEachAfter, but includes the item(s) at the given time. + * @param {Number} time The time to check if items are before + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.forEachFrom = function (time, callback) { + //iterate over the items in reverse so that removing an item doesn't break things + var lowerBound = this._search(time); + //work backwards until the event time is less than time + while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { + lowerBound--; + } + this._iterate(callback, lowerBound + 1); + return this; + }; + /** + * Iterate over everything in the array at the given time + * @param {Number} time The time to check if items are before + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.Timeline} this + */ + Tone.Timeline.prototype.forEachAtTime = function (time, callback) { + //iterate over the items in reverse so that removing an item doesn't break things + var upperBound = this._search(time); + if (upperBound !== -1) { + this._iterate(function (event) { + if (event.time === time) { + callback(event); + } + }, 0, upperBound); + } + return this; + }; + /** + * Clean up. + * @return {Tone.Timeline} this + */ + Tone.Timeline.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._timeline = null; + this._toRemove = null; + }; + return Tone.Timeline; + }); + Module(function (Tone) { + + /** + * @class A signal which adds the method getValueAtTime. + * Code and inspiration from https://github.com/jsantell/web-audio-automation-timeline + * @extends {Tone.Param} + * @param {Number=} value The initial value of the signal + * @param {String=} units The conversion units of the signal. + */ + Tone.TimelineSignal = function () { + var options = this.optionsObject(arguments, [ + 'value', + 'units' + ], Tone.Signal.defaults); + /** + * The scheduled events + * @type {Tone.Timeline} + * @private + */ + this._events = new Tone.Timeline(10); + //constructors + Tone.Signal.apply(this, options); + options.param = this._param; + Tone.Param.call(this, options); + /** + * The initial scheduled value + * @type {Number} + * @private + */ + this._initial = this._fromUnits(this._param.value); + }; + Tone.extend(Tone.TimelineSignal, Tone.Param); + /** + * The event types of a schedulable signal. + * @enum {String} + * @private + */ + Tone.TimelineSignal.Type = { + Linear: 'linear', + Exponential: 'exponential', + Target: 'target', + Curve: 'curve', + Set: 'set' + }; + /** + * The current value of the signal. + * @memberOf Tone.TimelineSignal# + * @type {Number} + * @name value + */ + Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { + get: function () { + var now = this.now(); + var val = this.getValueAtTime(now); + return this._toUnits(val); + }, + set: function (value) { + var convertedVal = this._fromUnits(value); + this._initial = convertedVal; + this.cancelScheduledValues(); + this._param.value = convertedVal; + } + }); + /////////////////////////////////////////////////////////////////////////// + // SCHEDULING + /////////////////////////////////////////////////////////////////////////// + /** + * Schedules a parameter value change at the given time. + * @param {*} value The value to set the signal. + * @param {Time} time The time when the change should occur. + * @returns {Tone.TimelineSignal} this + * @example + * //set the frequency to "G4" in exactly 1 second from now. + * freq.setValueAtTime("G4", "+1"); + */ + Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { + value = this._fromUnits(value); + startTime = this.toSeconds(startTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Set, + 'value': value, + 'time': startTime + }); + //invoke the original event + this._param.setValueAtTime(value, startTime); + return this; + }; + /** + * Schedules a linear continuous change in parameter value from the + * previous scheduled parameter value to the given value. + * + * @param {number} value + * @param {Time} endTime + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + endTime = this.toSeconds(endTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Linear, + 'value': value, + 'time': endTime + }); + this._param.linearRampToValueAtTime(value, endTime); + return this; + }; + /** + * Schedules an exponential continuous change in parameter value from + * the previous scheduled parameter value to the given value. + * + * @param {number} value + * @param {Time} endTime + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { + //get the previous event and make sure it's not starting from 0 + endTime = this.toSeconds(endTime); + var beforeEvent = this._searchBefore(endTime); + if (beforeEvent && beforeEvent.value === 0) { + //reschedule that event + this.setValueAtTime(this._minOutput, beforeEvent.time); + } + value = this._fromUnits(value); + var setValue = Math.max(value, this._minOutput); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Exponential, + 'value': setValue, + 'time': endTime + }); + //if the ramped to value is 0, make it go to the min output, and then set to 0. + if (value < this._minOutput) { + this._param.exponentialRampToValueAtTime(this._minOutput, endTime - this.sampleTime); + this.setValueAtTime(0, endTime); + } else { + this._param.exponentialRampToValueAtTime(value, endTime); + } + return this; + }; + /** + * Start exponentially approaching the target value at the given time with + * a rate having the given time constant. + * @param {number} value + * @param {Time} startTime + * @param {number} timeConstant + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { + value = this._fromUnits(value); + value = Math.max(this._minOutput, value); + timeConstant = Math.max(this._minOutput, timeConstant); + startTime = this.toSeconds(startTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Target, + 'value': value, + 'time': startTime, + 'constant': timeConstant + }); + this._param.setTargetAtTime(value, startTime, timeConstant); + return this; + }; + /** + * Set an array of arbitrary values starting at the given time for the given duration. + * @param {Float32Array} values + * @param {Time} startTime + * @param {Time} duration + * @param {NormalRange} [scaling=1] If the values in the curve should be scaled by some value + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.setValueCurveAtTime = function (values, startTime, duration, scaling) { + scaling = this.defaultArg(scaling, 1); + //copy the array + var floats = new Array(values.length); + for (var i = 0; i < floats.length; i++) { + floats[i] = this._fromUnits(values[i]) * scaling; + } + startTime = this.toSeconds(startTime); + duration = this.toSeconds(duration); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Curve, + 'value': floats, + 'time': startTime, + 'duration': duration + }); + //set the first value + this._param.setValueAtTime(floats[0], startTime); + //schedule a lienar ramp for each of the segments + for (var j = 1; j < floats.length; j++) { + var segmentTime = startTime + j / (floats.length - 1) * duration; + this._param.linearRampToValueAtTime(floats[j], segmentTime); + } + return this; + }; + /** + * Cancels all scheduled parameter changes with times greater than or + * equal to startTime. + * + * @param {Time} startTime + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { + after = this.toSeconds(after); + this._events.cancel(after); + this._param.cancelScheduledValues(after); + return this; + }; + /** + * Sets the computed value at the given time. This provides + * a point from which a linear or exponential curve + * can be scheduled after. Will cancel events after + * the given time and shorten the currently scheduled + * linear or exponential ramp so that it ends at `time` . + * This is to avoid discontinuities and clicks in envelopes. + * @param {Time} time When to set the ramp point + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.setRampPoint = function (time) { + time = this.toSeconds(time); + //get the value at the given time + var val = this._toUnits(this.getValueAtTime(time)); + //if there is an event at the given time + //and that even is not a "set" + var before = this._searchBefore(time); + if (before && before.time === time) { + //remove everything after + this.cancelScheduledValues(time + this.sampleTime); + } else if (before && before.type === Tone.TimelineSignal.Type.Curve && before.time + before.duration > time) { + //if the curve is still playing + //cancel the curve + this.cancelScheduledValues(time); + this.linearRampToValueAtTime(val, time); + } else { + //reschedule the next event to end at the given time + var after = this._searchAfter(time); + if (after) { + //cancel the next event(s) + this.cancelScheduledValues(time); + if (after.type === Tone.TimelineSignal.Type.Linear) { + this.linearRampToValueAtTime(val, time); + } else if (after.type === Tone.TimelineSignal.Type.Exponential) { + this.exponentialRampToValueAtTime(val, time); + } + } + this.setValueAtTime(val, time); + } + return this; + }; + /** + * Do a linear ramp to the given value between the start and finish times. + * @param {Number} value The value to ramp to. + * @param {Time} start The beginning anchor point to do the linear ramp + * @param {Time} finish The ending anchor point by which the value of + * the signal will equal the given value. + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { + this.setRampPoint(start); + this.linearRampToValueAtTime(value, finish); + return this; + }; + /** + * Do a exponential ramp to the given value between the start and finish times. + * @param {Number} value The value to ramp to. + * @param {Time} start The beginning anchor point to do the exponential ramp + * @param {Time} finish The ending anchor point by which the value of + * the signal will equal the given value. + * @returns {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { + this.setRampPoint(start); + this.exponentialRampToValueAtTime(value, finish); + return this; + }; + /////////////////////////////////////////////////////////////////////////// + // GETTING SCHEDULED VALUES + /////////////////////////////////////////////////////////////////////////// + /** + * Returns the value before or equal to the given time + * @param {Number} time The time to query + * @return {Object} The event at or before the given time. + * @private + */ + Tone.TimelineSignal.prototype._searchBefore = function (time) { + return this._events.get(time); + }; + /** + * The event after the given time + * @param {Number} time The time to query. + * @return {Object} The next event after the given time + * @private + */ + Tone.TimelineSignal.prototype._searchAfter = function (time) { + return this._events.getAfter(time); + }; + /** + * Get the scheduled value at the given time. This will + * return the unconverted (raw) value. + * @param {Number} time The time in seconds. + * @return {Number} The scheduled value at the given time. + */ + Tone.TimelineSignal.prototype.getValueAtTime = function (time) { + time = this.toSeconds(time); + var after = this._searchAfter(time); + var before = this._searchBefore(time); + var value = this._initial; + //if it was set by + if (before === null) { + value = this._initial; + } else if (before.type === Tone.TimelineSignal.Type.Target) { + var previous = this._events.getBefore(before.time); + var previouVal; + if (previous === null) { + previouVal = this._initial; + } else { + previouVal = previous.value; + } + value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); + } else if (before.type === Tone.TimelineSignal.Type.Curve) { + value = this._curveInterpolate(before.time, before.value, before.duration, time); + } else if (after === null) { + value = before.value; + } else if (after.type === Tone.TimelineSignal.Type.Linear) { + value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); + } else if (after.type === Tone.TimelineSignal.Type.Exponential) { + value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); + } else { + value = before.value; + } + return value; + }; + /** + * When signals connect to other signals or AudioParams, + * they take over the output value of that signal or AudioParam. + * For all other nodes, the behavior is the same as a default connect. + * + * @override + * @param {AudioParam|AudioNode|Tone.Signal|Tone} node + * @param {number} [outputNumber=0] The output number to connect from. + * @param {number} [inputNumber=0] The input number to connect to. + * @returns {Tone.TimelineSignal} this + * @method + */ + Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; + /////////////////////////////////////////////////////////////////////////// + // AUTOMATION CURVE CALCULATIONS + // MIT License, copyright (c) 2014 Jordan Santell + /////////////////////////////////////////////////////////////////////////// + /** + * Calculates the the value along the curve produced by setTargetAtTime + * @private + */ + Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { + return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); + }; + /** + * Calculates the the value along the curve produced by linearRampToValueAtTime + * @private + */ + Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { + return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); + }; + /** + * Calculates the the value along the curve produced by exponentialRampToValueAtTime + * @private + */ + Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { + v0 = Math.max(this._minOutput, v0); + return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); + }; + /** + * Calculates the the value along the curve produced by setValueCurveAtTime + * @private + */ + Tone.TimelineSignal.prototype._curveInterpolate = function (start, curve, duration, time) { + var len = curve.length; + // If time is after duration, return the last curve value + if (time >= start + duration) { + return curve[len - 1]; + } else if (time <= start) { + return curve[0]; + } else { + var progress = (time - start) / duration; + var lowerIndex = Math.floor((len - 1) * progress); + var upperIndex = Math.ceil((len - 1) * progress); + var lowerVal = curve[lowerIndex]; + var upperVal = curve[upperIndex]; + if (upperIndex === lowerIndex) { + return lowerVal; + } else { + return this._linearInterpolate(lowerIndex, lowerVal, upperIndex, upperVal, progress * (len - 1)); + } + } + }; + /** + * Clean up. + * @return {Tone.TimelineSignal} this + */ + Tone.TimelineSignal.prototype.dispose = function () { + Tone.Signal.prototype.dispose.call(this); + Tone.Param.prototype.dispose.call(this); + this._events.dispose(); + this._events = null; + }; + return Tone.TimelineSignal; + }); + Module(function (Tone) { + + /** + * @class Pow applies an exponent to the incoming signal. The incoming signal + * must be AudioRange. + * + * @extends {Tone.SignalBase} + * @constructor + * @param {Positive} exp The exponent to apply to the incoming signal, must be at least 2. + * @example + * var pow = new Tone.Pow(2); + * var sig = new Tone.Signal(0.5).connect(pow); + * //output of pow is 0.25. + */ + Tone.Pow = function (exp) { + /** + * the exponent + * @private + * @type {number} + */ + this._exp = this.defaultArg(exp, 1); + /** + * @type {WaveShaperNode} + * @private + */ + this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192); + }; + Tone.extend(Tone.Pow, Tone.SignalBase); + /** + * The value of the exponent. + * @memberOf Tone.Pow# + * @type {number} + * @name value + */ + Object.defineProperty(Tone.Pow.prototype, 'value', { + get: function () { + return this._exp; + }, + set: function (exp) { + this._exp = exp; + this._expScaler.setMap(this._expFunc(this._exp)); + } + }); + /** + * the function which maps the waveshaper + * @param {number} exp + * @return {function} + * @private + */ + Tone.Pow.prototype._expFunc = function (exp) { + return function (val) { + return Math.pow(Math.abs(val), exp); + }; + }; + /** + * Clean up. + * @returns {Tone.Pow} this + */ + Tone.Pow.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._expScaler.dispose(); + this._expScaler = null; + return this; + }; + return Tone.Pow; + }); + Module(function (Tone) { + + /** + * @class Tone.Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope) + * envelope generator. Tone.Envelope outputs a signal which + * can be connected to an AudioParam or Tone.Signal. + * + * + * @constructor + * @extends {Tone} + * @param {Time} [attack] The amount of time it takes for the envelope to go from + * 0 to it's maximum value. + * @param {Time} [decay] The period of time after the attack that it takes for the envelope + * to fall to the sustain value. + * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until + * the release is triggered. + * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. + * @example + * //an amplitude envelope + * var gainNode = Tone.context.createGain(); + * var env = new Tone.Envelope({ + * "attack" : 0.1, + * "decay" : 0.2, + * "sustain" : 1, + * "release" : 0.8, + * }); + * env.connect(gainNode.gain); + */ + Tone.Envelope = function () { + //get all of the defaults + var options = this.optionsObject(arguments, [ + 'attack', + 'decay', + 'sustain', + 'release' + ], Tone.Envelope.defaults); + /** + * When triggerAttack is called, the attack time is the amount of + * time it takes for the envelope to reach it's maximum value. + * @type {Time} + */ + this.attack = options.attack; + /** + * After the attack portion of the envelope, the value will fall + * over the duration of the decay time to it's sustain value. + * @type {Time} + */ + this.decay = options.decay; + /** + * The sustain value is the value + * which the envelope rests at after triggerAttack is + * called, but before triggerRelease is invoked. + * @type {NormalRange} + */ + this.sustain = options.sustain; + /** + * After triggerRelease is called, the envelope's + * value will fall to it's miminum value over the + * duration of the release time. + * @type {Time} + */ + this.release = options.release; + /** + * the next time the envelope is at standby + * @type {number} + * @private + */ + this._attackCurve = 'linear'; + /** + * the next time the envelope is at standby + * @type {number} + * @private + */ + this._releaseCurve = 'exponential'; + /** + * the signal + * @type {Tone.TimelineSignal} + * @private + */ + this._sig = this.output = new Tone.TimelineSignal(); + this._sig.setValueAtTime(0, 0); + //set the attackCurve initially + this.attackCurve = options.attackCurve; + this.releaseCurve = options.releaseCurve; + }; + Tone.extend(Tone.Envelope); + /** + * the default parameters + * @static + * @const + */ + Tone.Envelope.defaults = { + 'attack': 0.01, + 'decay': 0.1, + 'sustain': 0.5, + 'release': 1, + 'attackCurve': 'linear', + 'releaseCurve': 'exponential' + }; + /** + * Read the current value of the envelope. Useful for + * syncronizing visual output to the envelope. + * @memberOf Tone.Envelope# + * @type {Number} + * @name value + * @readOnly + */ + Object.defineProperty(Tone.Envelope.prototype, 'value', { + get: function () { + return this.getValueAtTime(this.now()); + } + }); + /** + * The shape of the attack. + * Can be any of these strings: + *
    + *
  • linear
  • + *
  • exponential
  • + *
  • sine
  • + *
  • cosine
  • + *
  • bounce
  • + *
  • ripple
  • + *
  • step
  • + *
+ * Can also be an array which describes the curve. Values + * in the array are evenly subdivided and linearly + * interpolated over the duration of the attack. + * @memberOf Tone.Envelope# + * @type {String|Array} + * @name attackCurve + * @example + * env.attackCurve = "linear"; + * @example + * //can also be an array + * env.attackCurve = [0, 0.2, 0.3, 0.4, 1] + */ + Object.defineProperty(Tone.Envelope.prototype, 'attackCurve', { + get: function () { + if (this.isString(this._attackCurve)) { + return this._attackCurve; + } else if (this.isArray(this._attackCurve)) { + //look up the name in the curves array + for (var type in Tone.Envelope.Type) { + if (Tone.Envelope.Type[type].In === this._attackCurve) { + return type; + } + } + //otherwise just return the array + return this._attackCurve; + } + }, + set: function (curve) { + //check if it's a valid type + if (Tone.Envelope.Type.hasOwnProperty(curve)) { + var curveDef = Tone.Envelope.Type[curve]; + if (this.isObject(curveDef)) { + this._attackCurve = curveDef.In; + } else { + this._attackCurve = curveDef; + } + } else if (this.isArray(curve)) { + this._attackCurve = curve; + } else { + throw new Error('Tone.Envelope: invalid curve: ' + curve); + } + } + }); + /** + * The shape of the release. See the attack curve types. + * @memberOf Tone.Envelope# + * @type {String|Array} + * @name releaseCurve + * @example + * env.releaseCurve = "linear"; + */ + Object.defineProperty(Tone.Envelope.prototype, 'releaseCurve', { + get: function () { + if (this.isString(this._releaseCurve)) { + return this._releaseCurve; + } else if (this.isArray(this._releaseCurve)) { + //look up the name in the curves array + for (var type in Tone.Envelope.Type) { + if (Tone.Envelope.Type[type].Out === this._releaseCurve) { + return type; + } + } + //otherwise just return the array + return this._releaseCurve; + } + }, + set: function (curve) { + //check if it's a valid type + if (Tone.Envelope.Type.hasOwnProperty(curve)) { + var curveDef = Tone.Envelope.Type[curve]; + if (this.isObject(curveDef)) { + this._releaseCurve = curveDef.Out; + } else { + this._releaseCurve = curveDef; + } + } else if (this.isArray(curve)) { + this._releaseCurve = curve; + } else { + throw new Error('Tone.Envelope: invalid curve: ' + curve); + } + } + }); + /** + * Trigger the attack/decay portion of the ADSR envelope. + * @param {Time} [time=now] When the attack should start. + * @param {NormalRange} [velocity=1] The velocity of the envelope scales the vales. + * number between 0-1 + * @returns {Tone.Envelope} this + * @example + * //trigger the attack 0.5 seconds from now with a velocity of 0.2 + * env.triggerAttack("+0.5", 0.2); + */ + Tone.Envelope.prototype.triggerAttack = function (time, velocity) { + time = this.toSeconds(time); + var originalAttack = this.toSeconds(this.attack); + var attack = originalAttack; + var decay = this.toSeconds(this.decay); + velocity = this.defaultArg(velocity, 1); + //check if it's not a complete attack + var currentValue = this.getValueAtTime(time); + if (currentValue > 0) { + //subtract the current value from the attack time + var attackRate = 1 / attack; + var remainingDistance = 1 - currentValue; + //the attack is now the remaining time + attack = remainingDistance / attackRate; + } + //attack + if (this._attackCurve === 'linear') { + this._sig.linearRampToValue(velocity, attack, time); + } else if (this._attackCurve === 'exponential') { + this._sig.exponentialRampToValue(velocity, attack, time); + } else if (attack > 0) { + this._sig.setRampPoint(time); + var curve = this._attackCurve; + //take only a portion of the curve + if (attack < originalAttack) { + var percentComplete = 1 - attack / originalAttack; + var sliceIndex = Math.floor(percentComplete * this._attackCurve.length); + curve = this._attackCurve.slice(sliceIndex); + //the first index is the current value + curve[0] = currentValue; + } + this._sig.setValueCurveAtTime(curve, time, attack, velocity); + } + //decay + this._sig.exponentialRampToValue(velocity * this.sustain, decay, attack + time); + return this; + }; + /** + * Triggers the release of the envelope. + * @param {Time} [time=now] When the release portion of the envelope should start. + * @returns {Tone.Envelope} this + * @example + * //trigger release immediately + * env.triggerRelease(); + */ + Tone.Envelope.prototype.triggerRelease = function (time) { + time = this.toSeconds(time); + var currentValue = this.getValueAtTime(time); + if (currentValue > 0) { + var release = this.toSeconds(this.release); + if (this._releaseCurve === 'linear') { + this._sig.linearRampToValue(0, release, time); + } else if (this._releaseCurve === 'exponential') { + this._sig.exponentialRampToValue(0, release, time); + } else { + var curve = this._releaseCurve; + if (this.isArray(curve)) { + this._sig.setRampPoint(time); + this._sig.setValueCurveAtTime(curve, time, release, currentValue); + } + } + } + return this; + }; + /** + * Get the scheduled value at the given time. This will + * return the unconverted (raw) value. + * @param {Number} time The time in seconds. + * @return {Number} The scheduled value at the given time. + */ + Tone.Envelope.prototype.getValueAtTime = function (time) { + return this._sig.getValueAtTime(time); + }; + /** + * triggerAttackRelease is shorthand for triggerAttack, then waiting + * some duration, then triggerRelease. + * @param {Time} duration The duration of the sustain. + * @param {Time} [time=now] When the attack should be triggered. + * @param {number} [velocity=1] The velocity of the envelope. + * @returns {Tone.Envelope} this + * @example + * //trigger the attack and then the release after 0.6 seconds. + * env.triggerAttackRelease(0.6); + */ + Tone.Envelope.prototype.triggerAttackRelease = function (duration, time, velocity) { + time = this.toSeconds(time); + this.triggerAttack(time, velocity); + this.triggerRelease(time + this.toSeconds(duration)); + return this; + }; + /** + * Cancels all scheduled envelope changes after the given time. + * @param {Time} after + * @returns {Tone.Envelope} this + */ + Tone.Envelope.prototype.cancel = function (after) { + this._sig.cancelScheduledValues(after); + return this; + }; + /** + * Borrows the connect method from Tone.Signal. + * @function + * @private + */ + Tone.Envelope.prototype.connect = Tone.Signal.prototype.connect; + /** + * Generate some complex envelope curves. + */ + (function _createCurves() { + var curveLen = 128; + var i, k; + //cosine curve + var cosineCurve = []; + for (i = 0; i < curveLen; i++) { + cosineCurve[i] = Math.sin(i / (curveLen - 1) * (Math.PI / 2)); + } + //ripple curve + var rippleCurve = []; + var rippleCurveFreq = 6.4; + for (i = 0; i < curveLen - 1; i++) { + k = i / (curveLen - 1); + var sineWave = Math.sin(k * (Math.PI * 2) * rippleCurveFreq - Math.PI / 2) + 1; + rippleCurve[i] = sineWave / 10 + k * 0.83; + } + rippleCurve[curveLen - 1] = 1; + //stairs curve + var stairsCurve = []; + var steps = 5; + for (i = 0; i < curveLen; i++) { + stairsCurve[i] = Math.ceil(i / (curveLen - 1) * steps) / steps; + } + //in-out easing curve + var sineCurve = []; + for (i = 0; i < curveLen; i++) { + k = i / (curveLen - 1); + sineCurve[i] = 0.5 * (1 - Math.cos(Math.PI * k)); + } + //a bounce curve + var bounceCurve = []; + for (i = 0; i < curveLen; i++) { + k = i / (curveLen - 1); + var freq = Math.pow(k, 3) * 4 + 0.2; + var val = Math.cos(freq * Math.PI * 2 * k); + bounceCurve[i] = Math.abs(val * (1 - k)); + } + /** + * Invert a value curve to make it work for the release + * @private + */ + function invertCurve(curve) { + var out = new Array(curve.length); + for (var j = 0; j < curve.length; j++) { + out[j] = 1 - curve[j]; + } + return out; + } + /** + * reverse the curve + * @private + */ + function reverseCurve(curve) { + return curve.slice(0).reverse(); + } + /** + * attack and release curve arrays + * @type {Object} + * @private + */ + Tone.Envelope.Type = { + 'linear': 'linear', + 'exponential': 'exponential', + 'bounce': { + In: invertCurve(bounceCurve), + Out: bounceCurve + }, + 'cosine': { + In: cosineCurve, + Out: reverseCurve(cosineCurve) + }, + 'step': { + In: stairsCurve, + Out: invertCurve(stairsCurve) + }, + 'ripple': { + In: rippleCurve, + Out: invertCurve(rippleCurve) + }, + 'sine': { + In: sineCurve, + Out: invertCurve(sineCurve) + } + }; + }()); + /** + * Disconnect and dispose. + * @returns {Tone.Envelope} this + */ + Tone.Envelope.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._sig.dispose(); + this._sig = null; + this._attackCurve = null; + this._releaseCurve = null; + return this; + }; + return Tone.Envelope; + }); + Module(function (Tone) { + + /** + * @class Tone.AmplitudeEnvelope is a Tone.Envelope connected to a gain node. + * Unlike Tone.Envelope, which outputs the envelope's value, Tone.AmplitudeEnvelope accepts + * an audio signal as the input and will apply the envelope to the amplitude + * of the signal. Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope). + * + * @constructor + * @extends {Tone.Envelope} + * @param {Time|Object} [attack] The amount of time it takes for the envelope to go from + * 0 to it's maximum value. + * @param {Time} [decay] The period of time after the attack that it takes for the envelope + * to fall to the sustain value. + * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until + * the release is triggered. + * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. + * @example + * var ampEnv = new Tone.AmplitudeEnvelope({ + * "attack": 0.1, + * "decay": 0.2, + * "sustain": 1.0, + * "release": 0.8 + * }).toMaster(); + * //create an oscillator and connect it + * var osc = new Tone.Oscillator().connect(ampEnv).start(); + * //trigger the envelopes attack and release "8t" apart + * ampEnv.triggerAttackRelease("8t"); + */ + Tone.AmplitudeEnvelope = function () { + Tone.Envelope.apply(this, arguments); + /** + * the input node + * @type {GainNode} + * @private + */ + this.input = this.output = new Tone.Gain(); + this._sig.connect(this.output.gain); + }; + Tone.extend(Tone.AmplitudeEnvelope, Tone.Envelope); + /** + * Clean up + * @return {Tone.AmplitudeEnvelope} this + */ + Tone.AmplitudeEnvelope.prototype.dispose = function () { + this.input.dispose(); + this.input = null; + Tone.Envelope.prototype.dispose.call(this); + return this; + }; + return Tone.AmplitudeEnvelope; + }); + Module(function (Tone) { + + /** + * AnalyserNode.getFloatTimeDomainData polyfill + * @private + */ + if (window.AnalyserNode && !AnalyserNode.prototype.getFloatTimeDomainData) { + //referenced https://github.com/mohayonao/get-float-time-domain-data + AnalyserNode.prototype.getFloatTimeDomainData = function (array) { + var uint8 = new Uint8Array(array.length); + this.getByteTimeDomainData(uint8); + for (var i = 0; i < uint8.length; i++) { + array[i] = (uint8[i] - 128) / 128; + } + }; + } + /** + * @class Wrapper around the native Web Audio's + * [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode). + * Extracts FFT or Waveform data from the incoming signal. + * @extends {Tone} + * @param {String=} type The return type of the analysis, either "fft", or "waveform". + * @param {Number=} size The size of the FFT. Value must be a power of + * two in the range 32 to 32768. + */ + Tone.Analyser = function () { + var options = this.optionsObject(arguments, [ + 'type', + 'size' + ], Tone.Analyser.defaults); + /** + * The analyser node. + * @private + * @type {AnalyserNode} + */ + this._analyser = this.input = this.output = this.context.createAnalyser(); + /** + * The analysis type + * @type {String} + * @private + */ + this._type = options.type; + /** + * The return type of the analysis + * @type {String} + * @private + */ + this._returnType = options.returnType; + /** + * The buffer that the FFT data is written to + * @type {TypedArray} + * @private + */ + this._buffer = null; + //set the values initially + this.size = options.size; + this.type = options.type; + this.returnType = options.returnType; + this.minDecibels = options.minDecibels; + this.maxDecibels = options.maxDecibels; + }; + Tone.extend(Tone.Analyser); + /** + * The default values. + * @type {Object} + * @const + */ + Tone.Analyser.defaults = { + 'size': 1024, + 'returnType': 'byte', + 'type': 'fft', + 'smoothing': 0.8, + 'maxDecibels': -30, + 'minDecibels': -100 + }; + /** + * Possible return types of Tone.Analyser.analyse() + * @enum {String} + */ + Tone.Analyser.Type = { + Waveform: 'waveform', + FFT: 'fft' + }; + /** + * Possible return types of Tone.Analyser.analyse(). + * byte values are between [0,255]. float values are between + * [-1, 1] when the type is set to "waveform" and between + * [minDecibels,maxDecibels] when the type is "fft". + * @enum {String} + */ + Tone.Analyser.ReturnType = { + Byte: 'byte', + Float: 'float' + }; + /** + * Run the analysis given the current settings and return the + * result as a TypedArray. + * @returns {TypedArray} + */ + Tone.Analyser.prototype.analyse = function () { + if (this._type === Tone.Analyser.Type.FFT) { + if (this._returnType === Tone.Analyser.ReturnType.Byte) { + this._analyser.getByteFrequencyData(this._buffer); + } else { + this._analyser.getFloatFrequencyData(this._buffer); + } + } else if (this._type === Tone.Analyser.Type.Waveform) { + if (this._returnType === Tone.Analyser.ReturnType.Byte) { + this._analyser.getByteTimeDomainData(this._buffer); + } else { + this._analyser.getFloatTimeDomainData(this._buffer); + } + } + return this._buffer; + }; + /** + * The size of analysis. This must be a power of two in the range 32 to 32768. + * @memberOf Tone.Analyser# + * @type {Number} + * @name size + */ + Object.defineProperty(Tone.Analyser.prototype, 'size', { + get: function () { + return this._analyser.frequencyBinCount; + }, + set: function (size) { + this._analyser.fftSize = size * 2; + this.type = this._type; + } + }); + /** + * The return type of Tone.Analyser.analyse(), either "byte" or "float". + * When the type is set to "byte" the range of values returned in the array + * are between 0-255. "float" values are between + * [-1, 1] when the type is set to "waveform" and between + * [minDecibels,maxDecibels] when the type is "fft". + * @memberOf Tone.Analyser# + * @type {String} + * @name type + */ + Object.defineProperty(Tone.Analyser.prototype, 'returnType', { + get: function () { + return this._returnType; + }, + set: function (type) { + if (type === Tone.Analyser.ReturnType.Byte) { + this._buffer = new Uint8Array(this._analyser.frequencyBinCount); + } else if (type === Tone.Analyser.ReturnType.Float) { + this._buffer = new Float32Array(this._analyser.frequencyBinCount); + } else { + throw new TypeError('Tone.Analayser: invalid return type: ' + type); + } + this._returnType = type; + } + }); + /** + * The analysis function returned by Tone.Analyser.analyse(), either "fft" or "waveform". + * @memberOf Tone.Analyser# + * @type {String} + * @name type + */ + Object.defineProperty(Tone.Analyser.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT) { + throw new TypeError('Tone.Analyser: invalid type: ' + type); + } + this._type = type; + } + }); + /** + * 0 represents no time averaging with the last analysis frame. + * @memberOf Tone.Analyser# + * @type {NormalRange} + * @name smoothing + */ + Object.defineProperty(Tone.Analyser.prototype, 'smoothing', { + get: function () { + return this._analyser.smoothingTimeConstant; + }, + set: function (val) { + this._analyser.smoothingTimeConstant = val; + } + }); + /** + * The smallest decibel value which is analysed by the FFT. + * @memberOf Tone.Analyser# + * @type {Decibels} + * @name minDecibels + */ + Object.defineProperty(Tone.Analyser.prototype, 'minDecibels', { + get: function () { + return this._analyser.minDecibels; + }, + set: function (val) { + this._analyser.minDecibels = val; + } + }); + /** + * The largest decibel value which is analysed by the FFT. + * @memberOf Tone.Analyser# + * @type {Decibels} + * @name maxDecibels + */ + Object.defineProperty(Tone.Analyser.prototype, 'maxDecibels', { + get: function () { + return this._analyser.maxDecibels; + }, + set: function (val) { + this._analyser.maxDecibels = val; + } + }); + /** + * Clean up. + * @return {Tone.Analyser} this + */ + Tone.Analyser.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._analyser.disconnect(); + this._analyser = null; + this._buffer = null; + }; + return Tone.Analyser; + }); + Module(function (Tone) { + + /** + * @class Tone.Compressor is a thin wrapper around the Web Audio + * [DynamicsCompressorNode](http://webaudio.github.io/web-audio-api/#the-dynamicscompressornode-interface). + * Compression reduces the volume of loud sounds or amplifies quiet sounds + * by narrowing or "compressing" an audio signal's dynamic range. + * Read more on [Wikipedia](https://en.wikipedia.org/wiki/Dynamic_range_compression). + * + * @extends {Tone} + * @constructor + * @param {Decibels|Object} [threshold] The value above which the compression starts to be applied. + * @param {Positive} [ratio] The gain reduction ratio. + * @example + * var comp = new Tone.Compressor(-30, 3); + */ + Tone.Compressor = function () { + var options = this.optionsObject(arguments, [ + 'threshold', + 'ratio' + ], Tone.Compressor.defaults); + /** + * the compressor node + * @type {DynamicsCompressorNode} + * @private + */ + this._compressor = this.input = this.output = this.context.createDynamicsCompressor(); + /** + * the threshold vaue + * @type {Decibels} + * @signal + */ + this.threshold = new Tone.Param({ + 'param': this._compressor.threshold, + 'units': Tone.Type.Decibels, + 'convert': false + }); + /** + * The attack parameter + * @type {Time} + * @signal + */ + this.attack = new Tone.Param(this._compressor.attack, Tone.Type.Time); + /** + * The release parameter + * @type {Time} + * @signal + */ + this.release = new Tone.Param(this._compressor.release, Tone.Type.Time); + /** + * The knee parameter + * @type {Decibels} + * @signal + */ + this.knee = new Tone.Param({ + 'param': this._compressor.knee, + 'units': Tone.Type.Decibels, + 'convert': false + }); + /** + * The ratio value + * @type {Number} + * @signal + */ + this.ratio = new Tone.Param({ + 'param': this._compressor.ratio, + 'convert': false + }); + //set the defaults + this._readOnly([ + 'knee', + 'release', + 'attack', + 'ratio', + 'threshold' + ]); + this.set(options); + }; + Tone.extend(Tone.Compressor); + /** + * @static + * @const + * @type {Object} + */ + Tone.Compressor.defaults = { + 'ratio': 12, + 'threshold': -24, + 'release': 0.25, + 'attack': 0.003, + 'knee': 30 + }; + /** + * clean up + * @returns {Tone.Compressor} this + */ + Tone.Compressor.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'knee', + 'release', + 'attack', + 'ratio', + 'threshold' + ]); + this._compressor.disconnect(); + this._compressor = null; + this.attack.dispose(); + this.attack = null; + this.release.dispose(); + this.release = null; + this.threshold.dispose(); + this.threshold = null; + this.ratio.dispose(); + this.ratio = null; + this.knee.dispose(); + this.knee = null; + return this; + }; + return Tone.Compressor; + }); + Module(function (Tone) { + + /** + * @class Add a signal and a number or two signals. When no value is + * passed into the constructor, Tone.Add will sum input[0] + * and input[1]. If a value is passed into the constructor, + * the it will be added to the input. + * + * @constructor + * @extends {Tone.Signal} + * @param {number=} value If no value is provided, Tone.Add will sum the first + * and second inputs. + * @example + * var signal = new Tone.Signal(2); + * var add = new Tone.Add(2); + * signal.connect(add); + * //the output of add equals 4 + * @example + * //if constructed with no arguments + * //it will add the first and second inputs + * var add = new Tone.Add(); + * var sig0 = new Tone.Signal(3).connect(add, 0, 0); + * var sig1 = new Tone.Signal(4).connect(add, 0, 1); + * //the output of add equals 7. + */ + Tone.Add = function (value) { + this.createInsOuts(2, 0); + /** + * the summing node + * @type {GainNode} + * @private + */ + this._sum = this.input[0] = this.input[1] = this.output = new Tone.Gain(); + /** + * @private + * @type {Tone.Signal} + */ + this._param = this.input[1] = new Tone.Signal(value); + this._param.connect(this._sum); + }; + Tone.extend(Tone.Add, Tone.Signal); + /** + * Clean up. + * @returns {Tone.Add} this + */ + Tone.Add.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._sum.dispose(); + this._sum = null; + this._param.dispose(); + this._param = null; + return this; + }; + return Tone.Add; + }); + Module(function (Tone) { + + /** + * @class Multiply two incoming signals. Or, if a number is given in the constructor, + * multiplies the incoming signal by that value. + * + * @constructor + * @extends {Tone.Signal} + * @param {number=} value Constant value to multiple. If no value is provided, + * it will return the product of the first and second inputs + * @example + * var mult = new Tone.Multiply(); + * var sigA = new Tone.Signal(3); + * var sigB = new Tone.Signal(4); + * sigA.connect(mult, 0, 0); + * sigB.connect(mult, 0, 1); + * //output of mult is 12. + * @example + * var mult = new Tone.Multiply(10); + * var sig = new Tone.Signal(2).connect(mult); + * //the output of mult is 20. + */ + Tone.Multiply = function (value) { + this.createInsOuts(2, 0); + /** + * the input node is the same as the output node + * it is also the GainNode which handles the scaling of incoming signal + * + * @type {GainNode} + * @private + */ + this._mult = this.input[0] = this.output = new Tone.Gain(); + /** + * the scaling parameter + * @type {AudioParam} + * @private + */ + this._param = this.input[1] = this.output.gain; + this._param.value = this.defaultArg(value, 0); + }; + Tone.extend(Tone.Multiply, Tone.Signal); + /** + * clean up + * @returns {Tone.Multiply} this + */ + Tone.Multiply.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._mult.dispose(); + this._mult = null; + this._param = null; + return this; + }; + return Tone.Multiply; + }); + Module(function (Tone) { + + /** + * @class Negate the incoming signal. i.e. an input signal of 10 will output -10 + * + * @constructor + * @extends {Tone.SignalBase} + * @example + * var neg = new Tone.Negate(); + * var sig = new Tone.Signal(-2).connect(neg); + * //output of neg is positive 2. + */ + Tone.Negate = function () { + /** + * negation is done by multiplying by -1 + * @type {Tone.Multiply} + * @private + */ + this._multiply = this.input = this.output = new Tone.Multiply(-1); + }; + Tone.extend(Tone.Negate, Tone.SignalBase); + /** + * clean up + * @returns {Tone.Negate} this + */ + Tone.Negate.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._multiply.dispose(); + this._multiply = null; + return this; + }; + return Tone.Negate; + }); + Module(function (Tone) { + + /** + * @class Subtract the signal connected to input[1] from the signal connected + * to input[0]. If an argument is provided in the constructor, the + * signals .value will be subtracted from the incoming signal. + * + * @extends {Tone.Signal} + * @constructor + * @param {number=} value The value to subtract from the incoming signal. If the value + * is omitted, it will subtract the second signal from the first. + * @example + * var sub = new Tone.Subtract(1); + * var sig = new Tone.Signal(4).connect(sub); + * //the output of sub is 3. + * @example + * var sub = new Tone.Subtract(); + * var sigA = new Tone.Signal(10); + * var sigB = new Tone.Signal(2.5); + * sigA.connect(sub, 0, 0); + * sigB.connect(sub, 0, 1); + * //output of sub is 7.5 + */ + Tone.Subtract = function (value) { + this.createInsOuts(2, 0); + /** + * the summing node + * @type {GainNode} + * @private + */ + this._sum = this.input[0] = this.output = new Tone.Gain(); + /** + * negate the input of the second input before connecting it + * to the summing node. + * @type {Tone.Negate} + * @private + */ + this._neg = new Tone.Negate(); + /** + * the node where the value is set + * @private + * @type {Tone.Signal} + */ + this._param = this.input[1] = new Tone.Signal(value); + this._param.chain(this._neg, this._sum); + }; + Tone.extend(Tone.Subtract, Tone.Signal); + /** + * Clean up. + * @returns {Tone.SignalBase} this + */ + Tone.Subtract.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._neg.dispose(); + this._neg = null; + this._sum.disconnect(); + this._sum = null; + this._param.dispose(); + this._param = null; + return this; + }; + return Tone.Subtract; + }); + Module(function (Tone) { + + /** + * @class GreaterThanZero outputs 1 when the input is strictly greater than zero + * + * @constructor + * @extends {Tone.SignalBase} + * @example + * var gt0 = new Tone.GreaterThanZero(); + * var sig = new Tone.Signal(0.01).connect(gt0); + * //the output of gt0 is 1. + * sig.value = 0; + * //the output of gt0 is 0. + */ + Tone.GreaterThanZero = function () { + /** + * @type {Tone.WaveShaper} + * @private + */ + this._thresh = this.output = new Tone.WaveShaper(function (val) { + if (val <= 0) { + return 0; + } else { + return 1; + } + }, 127); + /** + * scale the first thresholded signal by a large value. + * this will help with values which are very close to 0 + * @type {Tone.Multiply} + * @private + */ + this._scale = this.input = new Tone.Multiply(10000); + //connections + this._scale.connect(this._thresh); + }; + Tone.extend(Tone.GreaterThanZero, Tone.SignalBase); + /** + * dispose method + * @returns {Tone.GreaterThanZero} this + */ + Tone.GreaterThanZero.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._scale.dispose(); + this._scale = null; + this._thresh.dispose(); + this._thresh = null; + return this; + }; + return Tone.GreaterThanZero; + }); + Module(function (Tone) { + + /** + * @class Output 1 if the signal is greater than the value, otherwise outputs 0. + * can compare two signals or a signal and a number. + * + * @constructor + * @extends {Tone.Signal} + * @param {number} [value=0] the value to compare to the incoming signal + * @example + * var gt = new Tone.GreaterThan(2); + * var sig = new Tone.Signal(4).connect(gt); + * //output of gt is equal 1. + */ + Tone.GreaterThan = function (value) { + this.createInsOuts(2, 0); + /** + * subtract the amount from the incoming signal + * @type {Tone.Subtract} + * @private + */ + this._param = this.input[0] = new Tone.Subtract(value); + this.input[1] = this._param.input[1]; + /** + * compare that amount to zero + * @type {Tone.GreaterThanZero} + * @private + */ + this._gtz = this.output = new Tone.GreaterThanZero(); + //connect + this._param.connect(this._gtz); + }; + Tone.extend(Tone.GreaterThan, Tone.Signal); + /** + * dispose method + * @returns {Tone.GreaterThan} this + */ + Tone.GreaterThan.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._param.dispose(); + this._param = null; + this._gtz.dispose(); + this._gtz = null; + return this; + }; + return Tone.GreaterThan; + }); + Module(function (Tone) { + + /** + * @class Return the absolute value of an incoming signal. + * + * @constructor + * @extends {Tone.SignalBase} + * @example + * var signal = new Tone.Signal(-1); + * var abs = new Tone.Abs(); + * signal.connect(abs); + * //the output of abs is 1. + */ + Tone.Abs = function () { + /** + * @type {Tone.LessThan} + * @private + */ + this._abs = this.input = this.output = new Tone.WaveShaper(function (val) { + if (val === 0) { + return 0; + } else { + return Math.abs(val); + } + }, 127); + }; + Tone.extend(Tone.Abs, Tone.SignalBase); + /** + * dispose method + * @returns {Tone.Abs} this + */ + Tone.Abs.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._abs.dispose(); + this._abs = null; + return this; + }; + return Tone.Abs; + }); + Module(function (Tone) { + + /** + * @class Signal-rate modulo operator. Only works in AudioRange [-1, 1] and for modulus + * values in the NormalRange. + * + * @constructor + * @extends {Tone.SignalBase} + * @param {NormalRange} modulus The modulus to apply. + * @example + * var mod = new Tone.Modulo(0.2) + * var sig = new Tone.Signal(0.5).connect(mod); + * //mod outputs 0.1 + */ + Tone.Modulo = function (modulus) { + this.createInsOuts(1, 0); + /** + * A waveshaper gets the integer multiple of + * the input signal and the modulus. + * @private + * @type {Tone.WaveShaper} + */ + this._shaper = new Tone.WaveShaper(Math.pow(2, 16)); + /** + * the integer multiple is multiplied by the modulus + * @type {Tone.Multiply} + * @private + */ + this._multiply = new Tone.Multiply(); + /** + * and subtracted from the input signal + * @type {Tone.Subtract} + * @private + */ + this._subtract = this.output = new Tone.Subtract(); + /** + * the modulus signal + * @type {Tone.Signal} + * @private + */ + this._modSignal = new Tone.Signal(modulus); + //connections + this.input.fan(this._shaper, this._subtract); + this._modSignal.connect(this._multiply, 0, 0); + this._shaper.connect(this._multiply, 0, 1); + this._multiply.connect(this._subtract, 0, 1); + this._setWaveShaper(modulus); + }; + Tone.extend(Tone.Modulo, Tone.SignalBase); + /** + * @param {number} mod the modulus to apply + * @private + */ + Tone.Modulo.prototype._setWaveShaper = function (mod) { + this._shaper.setMap(function (val) { + var multiple = Math.floor((val + 0.0001) / mod); + return multiple; + }); + }; + /** + * The modulus value. + * @memberOf Tone.Modulo# + * @type {NormalRange} + * @name value + */ + Object.defineProperty(Tone.Modulo.prototype, 'value', { + get: function () { + return this._modSignal.value; + }, + set: function (mod) { + this._modSignal.value = mod; + this._setWaveShaper(mod); + } + }); + /** + * clean up + * @returns {Tone.Modulo} this + */ + Tone.Modulo.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._shaper.dispose(); + this._shaper = null; + this._multiply.dispose(); + this._multiply = null; + this._subtract.dispose(); + this._subtract = null; + this._modSignal.dispose(); + this._modSignal = null; + return this; + }; + return Tone.Modulo; + }); + Module(function (Tone) { + + /** + * @class AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1]. + * See Tone.GainToAudio. + * + * @extends {Tone.SignalBase} + * @constructor + * @example + * var a2g = new Tone.AudioToGain(); + */ + Tone.AudioToGain = function () { + /** + * @type {WaveShaperNode} + * @private + */ + this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { + return (x + 1) / 2; + }); + }; + Tone.extend(Tone.AudioToGain, Tone.SignalBase); + /** + * clean up + * @returns {Tone.AudioToGain} this + */ + Tone.AudioToGain.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._norm.dispose(); + this._norm = null; + return this; + }; + return Tone.AudioToGain; + }); + Module(function (Tone) { + + /** + * @class Evaluate an expression at audio rate.

+ * Parsing code modified from https://code.google.com/p/tapdigit/ + * Copyright 2011 2012 Ariya Hidayat, New BSD License + * + * @extends {Tone.SignalBase} + * @constructor + * @param {string} expr the expression to generate + * @example + * //adds the signals from input[0] and input[1]. + * var expr = new Tone.Expr("$0 + $1"); + */ + Tone.Expr = function () { + var expr = this._replacements(Array.prototype.slice.call(arguments)); + var inputCount = this._parseInputs(expr); + /** + * hold onto all of the nodes for disposal + * @type {Array} + * @private + */ + this._nodes = []; + /** + * The inputs. The length is determined by the expression. + * @type {Array} + */ + this.input = new Array(inputCount); + //create a gain for each input + for (var i = 0; i < inputCount; i++) { + this.input[i] = this.context.createGain(); + } + //parse the syntax tree + var tree = this._parseTree(expr); + //evaluate the results + var result; + try { + result = this._eval(tree); + } catch (e) { + this._disposeNodes(); + throw new Error('Tone.Expr: Could evaluate expression: ' + expr); + } + /** + * The output node is the result of the expression + * @type {Tone} + */ + this.output = result; + }; + Tone.extend(Tone.Expr, Tone.SignalBase); + //some helpers to cut down the amount of code + function applyBinary(Constructor, args, self) { + var op = new Constructor(); + self._eval(args[0]).connect(op, 0, 0); + self._eval(args[1]).connect(op, 0, 1); + return op; + } + function applyUnary(Constructor, args, self) { + var op = new Constructor(); + self._eval(args[0]).connect(op, 0, 0); + return op; + } + function getNumber(arg) { + return arg ? parseFloat(arg) : undefined; + } + function literalNumber(arg) { + return arg && arg.args ? parseFloat(arg.args) : undefined; + } + /* + * the Expressions that Tone.Expr can parse. + * + * each expression belongs to a group and contains a regexp + * for selecting the operator as well as that operators method + * + * @type {Object} + * @private + */ + Tone.Expr._Expressions = { + //values + 'value': { + 'signal': { + regexp: /^\d+\.\d+|^\d+/, + method: function (arg) { + var sig = new Tone.Signal(getNumber(arg)); + return sig; + } + }, + 'input': { + regexp: /^\$\d/, + method: function (arg, self) { + return self.input[getNumber(arg.substr(1))]; + } + } + }, + //syntactic glue + 'glue': { + '(': { regexp: /^\(/ }, + ')': { regexp: /^\)/ }, + ',': { regexp: /^,/ } + }, + //functions + 'func': { + 'abs': { + regexp: /^abs/, + method: applyUnary.bind(this, Tone.Abs) + }, + 'mod': { + regexp: /^mod/, + method: function (args, self) { + var modulus = literalNumber(args[1]); + var op = new Tone.Modulo(modulus); + self._eval(args[0]).connect(op); + return op; + } + }, + 'pow': { + regexp: /^pow/, + method: function (args, self) { + var exp = literalNumber(args[1]); + var op = new Tone.Pow(exp); + self._eval(args[0]).connect(op); + return op; + } + }, + 'a2g': { + regexp: /^a2g/, + method: function (args, self) { + var op = new Tone.AudioToGain(); + self._eval(args[0]).connect(op); + return op; + } + } + }, + //binary expressions + 'binary': { + '+': { + regexp: /^\+/, + precedence: 1, + method: applyBinary.bind(this, Tone.Add) + }, + '-': { + regexp: /^\-/, + precedence: 1, + method: function (args, self) { + //both unary and binary op + if (args.length === 1) { + return applyUnary(Tone.Negate, args, self); + } else { + return applyBinary(Tone.Subtract, args, self); + } + } + }, + '*': { + regexp: /^\*/, + precedence: 0, + method: applyBinary.bind(this, Tone.Multiply) + } + }, + //unary expressions + 'unary': { + '-': { + regexp: /^\-/, + method: applyUnary.bind(this, Tone.Negate) + }, + '!': { + regexp: /^\!/, + method: applyUnary.bind(this, Tone.NOT) + } + } + }; + /** + * @param {string} expr the expression string + * @return {number} the input count + * @private + */ + Tone.Expr.prototype._parseInputs = function (expr) { + var inputArray = expr.match(/\$\d/g); + var inputMax = 0; + if (inputArray !== null) { + for (var i = 0; i < inputArray.length; i++) { + var inputNum = parseInt(inputArray[i].substr(1)) + 1; + inputMax = Math.max(inputMax, inputNum); + } + } + return inputMax; + }; + /** + * @param {Array} args an array of arguments + * @return {string} the results of the replacements being replaced + * @private + */ + Tone.Expr.prototype._replacements = function (args) { + var expr = args.shift(); + for (var i = 0; i < args.length; i++) { + expr = expr.replace(/\%/i, args[i]); + } + return expr; + }; + /** + * tokenize the expression based on the Expressions object + * @param {string} expr + * @return {Object} returns two methods on the tokenized list, next and peek + * @private + */ + Tone.Expr.prototype._tokenize = function (expr) { + var position = -1; + var tokens = []; + while (expr.length > 0) { + expr = expr.trim(); + var token = getNextToken(expr); + tokens.push(token); + expr = expr.substr(token.value.length); + } + function getNextToken(expr) { + for (var type in Tone.Expr._Expressions) { + var group = Tone.Expr._Expressions[type]; + for (var opName in group) { + var op = group[opName]; + var reg = op.regexp; + var match = expr.match(reg); + if (match !== null) { + return { + type: type, + value: match[0], + method: op.method + }; + } + } + } + throw new SyntaxError('Tone.Expr: Unexpected token ' + expr); + } + return { + next: function () { + return tokens[++position]; + }, + peek: function () { + return tokens[position + 1]; + } + }; + }; + /** + * recursively parse the string expression into a syntax tree + * + * @param {string} expr + * @return {Object} + * @private + */ + Tone.Expr.prototype._parseTree = function (expr) { + var lexer = this._tokenize(expr); + var isUndef = this.isUndef.bind(this); + function matchSyntax(token, syn) { + return !isUndef(token) && token.type === 'glue' && token.value === syn; + } + function matchGroup(token, groupName, prec) { + var ret = false; + var group = Tone.Expr._Expressions[groupName]; + if (!isUndef(token)) { + for (var opName in group) { + var op = group[opName]; + if (op.regexp.test(token.value)) { + if (!isUndef(prec)) { + if (op.precedence === prec) { + return true; + } + } else { + return true; + } + } + } + } + return ret; + } + function parseExpression(precedence) { + if (isUndef(precedence)) { + precedence = 5; + } + var expr; + if (precedence < 0) { + expr = parseUnary(); + } else { + expr = parseExpression(precedence - 1); + } + var token = lexer.peek(); + while (matchGroup(token, 'binary', precedence)) { + token = lexer.next(); + expr = { + operator: token.value, + method: token.method, + args: [ + expr, + parseExpression(precedence - 1) + ] + }; + token = lexer.peek(); + } + return expr; + } + function parseUnary() { + var token, expr; + token = lexer.peek(); + if (matchGroup(token, 'unary')) { + token = lexer.next(); + expr = parseUnary(); + return { + operator: token.value, + method: token.method, + args: [expr] + }; + } + return parsePrimary(); + } + function parsePrimary() { + var token, expr; + token = lexer.peek(); + if (isUndef(token)) { + throw new SyntaxError('Tone.Expr: Unexpected termination of expression'); + } + if (token.type === 'func') { + token = lexer.next(); + return parseFunctionCall(token); + } + if (token.type === 'value') { + token = lexer.next(); + return { + method: token.method, + args: token.value + }; + } + if (matchSyntax(token, '(')) { + lexer.next(); + expr = parseExpression(); + token = lexer.next(); + if (!matchSyntax(token, ')')) { + throw new SyntaxError('Expected )'); + } + return expr; + } + throw new SyntaxError('Tone.Expr: Parse error, cannot process token ' + token.value); + } + function parseFunctionCall(func) { + var token, args = []; + token = lexer.next(); + if (!matchSyntax(token, '(')) { + throw new SyntaxError('Tone.Expr: Expected ( in a function call "' + func.value + '"'); + } + token = lexer.peek(); + if (!matchSyntax(token, ')')) { + args = parseArgumentList(); + } + token = lexer.next(); + if (!matchSyntax(token, ')')) { + throw new SyntaxError('Tone.Expr: Expected ) in a function call "' + func.value + '"'); + } + return { + method: func.method, + args: args, + name: name + }; + } + function parseArgumentList() { + var token, expr, args = []; + while (true) { + expr = parseExpression(); + if (isUndef(expr)) { + // TODO maybe throw exception? + break; + } + args.push(expr); + token = lexer.peek(); + if (!matchSyntax(token, ',')) { + break; + } + lexer.next(); + } + return args; + } + return parseExpression(); + }; + /** + * recursively evaluate the expression tree + * @param {Object} tree + * @return {AudioNode} the resulting audio node from the expression + * @private + */ + Tone.Expr.prototype._eval = function (tree) { + if (!this.isUndef(tree)) { + var node = tree.method(tree.args, this); + this._nodes.push(node); + return node; + } + }; + /** + * dispose all the nodes + * @private + */ + Tone.Expr.prototype._disposeNodes = function () { + for (var i = 0; i < this._nodes.length; i++) { + var node = this._nodes[i]; + if (this.isFunction(node.dispose)) { + node.dispose(); + } else if (this.isFunction(node.disconnect)) { + node.disconnect(); + } + node = null; + this._nodes[i] = null; + } + this._nodes = null; + }; + /** + * clean up + */ + Tone.Expr.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._disposeNodes(); + }; + return Tone.Expr; + }); + Module(function (Tone) { + + /** + * @class Convert an incoming signal between 0, 1 to an equal power gain scale. + * + * @extends {Tone.SignalBase} + * @constructor + * @example + * var eqPowGain = new Tone.EqualPowerGain(); + */ + Tone.EqualPowerGain = function () { + /** + * @type {Tone.WaveShaper} + * @private + */ + this._eqPower = this.input = this.output = new Tone.WaveShaper(function (val) { + if (Math.abs(val) < 0.001) { + //should output 0 when input is 0 + return 0; + } else { + return this.equalPowerScale(val); + } + }.bind(this), 4096); + }; + Tone.extend(Tone.EqualPowerGain, Tone.SignalBase); + /** + * clean up + * @returns {Tone.EqualPowerGain} this + */ + Tone.EqualPowerGain.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._eqPower.dispose(); + this._eqPower = null; + return this; + }; + return Tone.EqualPowerGain; + }); + Module(function (Tone) { + + /** + * @class Tone.Crossfade provides equal power fading between two inputs. + * More on crossfading technique [here](https://en.wikipedia.org/wiki/Fade_(audio_engineering)#Crossfading). + * + * @constructor + * @extends {Tone} + * @param {NormalRange} [initialFade=0.5] + * @example + * var crossFade = new Tone.CrossFade(0.5); + * //connect effect A to crossfade from + * //effect output 0 to crossfade input 0 + * effectA.connect(crossFade, 0, 0); + * //connect effect B to crossfade from + * //effect output 0 to crossfade input 1 + * effectB.connect(crossFade, 0, 1); + * crossFade.fade.value = 0; + * // ^ only effectA is output + * crossFade.fade.value = 1; + * // ^ only effectB is output + * crossFade.fade.value = 0.5; + * // ^ the two signals are mixed equally. + */ + Tone.CrossFade = function (initialFade) { + this.createInsOuts(2, 1); + /** + * Alias for input[0]. + * @type {Tone.Gain} + */ + this.a = this.input[0] = new Tone.Gain(); + /** + * Alias for input[1]. + * @type {Tone.Gain} + */ + this.b = this.input[1] = new Tone.Gain(); + /** + * The mix between the two inputs. A fade value of 0 + * will output 100% input[0] and + * a value of 1 will output 100% input[1]. + * @type {NormalRange} + * @signal + */ + this.fade = new Tone.Signal(this.defaultArg(initialFade, 0.5), Tone.Type.NormalRange); + /** + * equal power gain cross fade + * @private + * @type {Tone.EqualPowerGain} + */ + this._equalPowerA = new Tone.EqualPowerGain(); + /** + * equal power gain cross fade + * @private + * @type {Tone.EqualPowerGain} + */ + this._equalPowerB = new Tone.EqualPowerGain(); + /** + * invert the incoming signal + * @private + * @type {Tone} + */ + this._invert = new Tone.Expr('1 - $0'); + //connections + this.a.connect(this.output); + this.b.connect(this.output); + this.fade.chain(this._equalPowerB, this.b.gain); + this.fade.chain(this._invert, this._equalPowerA, this.a.gain); + this._readOnly('fade'); + }; + Tone.extend(Tone.CrossFade); + /** + * clean up + * @returns {Tone.CrossFade} this + */ + Tone.CrossFade.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable('fade'); + this._equalPowerA.dispose(); + this._equalPowerA = null; + this._equalPowerB.dispose(); + this._equalPowerB = null; + this.fade.dispose(); + this.fade = null; + this._invert.dispose(); + this._invert = null; + this.a.dispose(); + this.a = null; + this.b.dispose(); + this.b = null; + return this; + }; + return Tone.CrossFade; + }); + Module(function (Tone) { + + /** + * @class Tone.Filter is a filter which allows for all of the same native methods + * as the [BiquadFilterNode](http://webaudio.github.io/web-audio-api/#the-biquadfilternode-interface). + * Tone.Filter has the added ability to set the filter rolloff at -12 + * (default), -24 and -48. + * + * @constructor + * @extends {Tone} + * @param {Frequency|Object} [frequency] The cutoff frequency of the filter. + * @param {string=} type The type of filter. + * @param {number=} rolloff The drop in decibels per octave after the cutoff frequency. + * 3 choices: -12, -24, and -48 + * @example + * var filter = new Tone.Filter(200, "highpass"); + */ + Tone.Filter = function () { + this.createInsOuts(1, 1); + var options = this.optionsObject(arguments, [ + 'frequency', + 'type', + 'rolloff' + ], Tone.Filter.defaults); + /** + * the filter(s) + * @type {Array} + * @private + */ + this._filters = []; + /** + * The cutoff frequency of the filter. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The detune parameter + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(0, Tone.Type.Cents); + /** + * The gain of the filter, only used in certain filter types + * @type {Number} + * @signal + */ + this.gain = new Tone.Signal({ + 'value': options.gain, + 'convert': false + }); + /** + * The Q or Quality of the filter + * @type {Positive} + * @signal + */ + this.Q = new Tone.Signal(options.Q); + /** + * the type of the filter + * @type {string} + * @private + */ + this._type = options.type; + /** + * the rolloff value of the filter + * @type {number} + * @private + */ + this._rolloff = options.rolloff; + //set the rolloff; + this.rolloff = options.rolloff; + this._readOnly([ + 'detune', + 'frequency', + 'gain', + 'Q' + ]); + }; + Tone.extend(Tone.Filter); + /** + * the default parameters + * + * @static + * @type {Object} + */ + Tone.Filter.defaults = { + 'type': 'lowpass', + 'frequency': 350, + 'rolloff': -12, + 'Q': 1, + 'gain': 0 + }; + /** + * The type of the filter. Types: "lowpass", "highpass", + * "bandpass", "lowshelf", "highshelf", "notch", "allpass", or "peaking". + * @memberOf Tone.Filter# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.Filter.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + var types = [ + 'lowpass', + 'highpass', + 'bandpass', + 'lowshelf', + 'highshelf', + 'notch', + 'allpass', + 'peaking' + ]; + if (types.indexOf(type) === -1) { + throw new TypeError('Tone.Filter: invalid type ' + type); + } + this._type = type; + for (var i = 0; i < this._filters.length; i++) { + this._filters[i].type = type; + } + } + }); + /** + * The rolloff of the filter which is the drop in db + * per octave. Implemented internally by cascading filters. + * Only accepts the values -12, -24, -48 and -96. + * @memberOf Tone.Filter# + * @type {number} + * @name rolloff + */ + Object.defineProperty(Tone.Filter.prototype, 'rolloff', { + get: function () { + return this._rolloff; + }, + set: function (rolloff) { + rolloff = parseInt(rolloff, 10); + var possibilities = [ + -12, + -24, + -48, + -96 + ]; + var cascadingCount = possibilities.indexOf(rolloff); + //check the rolloff is valid + if (cascadingCount === -1) { + throw new RangeError('Tone.Filter: rolloff can only be -12, -24, -48 or -96'); + } + cascadingCount += 1; + this._rolloff = rolloff; + //first disconnect the filters and throw them away + this.input.disconnect(); + for (var i = 0; i < this._filters.length; i++) { + this._filters[i].disconnect(); + this._filters[i] = null; + } + this._filters = new Array(cascadingCount); + for (var count = 0; count < cascadingCount; count++) { + var filter = this.context.createBiquadFilter(); + filter.type = this._type; + this.frequency.connect(filter.frequency); + this.detune.connect(filter.detune); + this.Q.connect(filter.Q); + this.gain.connect(filter.gain); + this._filters[count] = filter; + } + //connect them up + var connectionChain = [this.input].concat(this._filters).concat([this.output]); + this.connectSeries.apply(this, connectionChain); + } + }); + /** + * Clean up. + * @return {Tone.Filter} this + */ + Tone.Filter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + for (var i = 0; i < this._filters.length; i++) { + this._filters[i].disconnect(); + this._filters[i] = null; + } + this._filters = null; + this._writable([ + 'detune', + 'frequency', + 'gain', + 'Q' + ]); + this.frequency.dispose(); + this.Q.dispose(); + this.frequency = null; + this.Q = null; + this.detune.dispose(); + this.detune = null; + this.gain.dispose(); + this.gain = null; + return this; + }; + return Tone.Filter; + }); + Module(function (Tone) { + + /** + * @class Split the incoming signal into three bands (low, mid, high) + * with two crossover frequency controls. + * + * @extends {Tone} + * @constructor + * @param {Frequency|Object} [lowFrequency] the low/mid crossover frequency + * @param {Frequency} [highFrequency] the mid/high crossover frequency + */ + Tone.MultibandSplit = function () { + var options = this.optionsObject(arguments, [ + 'lowFrequency', + 'highFrequency' + ], Tone.MultibandSplit.defaults); + /** + * the input + * @type {Tone.Gain} + * @private + */ + this.input = new Tone.Gain(); + /** + * the outputs + * @type {Array} + * @private + */ + this.output = new Array(3); + /** + * The low band. Alias for output[0] + * @type {Tone.Filter} + */ + this.low = this.output[0] = new Tone.Filter(0, 'lowpass'); + /** + * the lower filter of the mid band + * @type {Tone.Filter} + * @private + */ + this._lowMidFilter = new Tone.Filter(0, 'highpass'); + /** + * The mid band output. Alias for output[1] + * @type {Tone.Filter} + */ + this.mid = this.output[1] = new Tone.Filter(0, 'lowpass'); + /** + * The high band output. Alias for output[2] + * @type {Tone.Filter} + */ + this.high = this.output[2] = new Tone.Filter(0, 'highpass'); + /** + * The low/mid crossover frequency. + * @type {Frequency} + * @signal + */ + this.lowFrequency = new Tone.Signal(options.lowFrequency, Tone.Type.Frequency); + /** + * The mid/high crossover frequency. + * @type {Frequency} + * @signal + */ + this.highFrequency = new Tone.Signal(options.highFrequency, Tone.Type.Frequency); + /** + * The quality of all the filters + * @type {Number} + * @signal + */ + this.Q = new Tone.Signal(options.Q); + this.input.fan(this.low, this.high); + this.input.chain(this._lowMidFilter, this.mid); + //the frequency control signal + this.lowFrequency.connect(this.low.frequency); + this.lowFrequency.connect(this._lowMidFilter.frequency); + this.highFrequency.connect(this.mid.frequency); + this.highFrequency.connect(this.high.frequency); + //the Q value + this.Q.connect(this.low.Q); + this.Q.connect(this._lowMidFilter.Q); + this.Q.connect(this.mid.Q); + this.Q.connect(this.high.Q); + this._readOnly([ + 'high', + 'mid', + 'low', + 'highFrequency', + 'lowFrequency' + ]); + }; + Tone.extend(Tone.MultibandSplit); + /** + * @private + * @static + * @type {Object} + */ + Tone.MultibandSplit.defaults = { + 'lowFrequency': 400, + 'highFrequency': 2500, + 'Q': 1 + }; + /** + * Clean up. + * @returns {Tone.MultibandSplit} this + */ + Tone.MultibandSplit.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'high', + 'mid', + 'low', + 'highFrequency', + 'lowFrequency' + ]); + this.low.dispose(); + this.low = null; + this._lowMidFilter.dispose(); + this._lowMidFilter = null; + this.mid.dispose(); + this.mid = null; + this.high.dispose(); + this.high = null; + this.lowFrequency.dispose(); + this.lowFrequency = null; + this.highFrequency.dispose(); + this.highFrequency = null; + this.Q.dispose(); + this.Q = null; + return this; + }; + return Tone.MultibandSplit; + }); + Module(function (Tone) { + + /** + * @class Tone.EQ3 is a three band EQ with control over low, mid, and high gain as + * well as the low and high crossover frequencies. + * + * @constructor + * @extends {Tone} + * + * @param {Decibels|Object} [lowLevel] The gain applied to the lows. + * @param {Decibels} [midLevel] The gain applied to the mid. + * @param {Decibels} [highLevel] The gain applied to the high. + * @example + * var eq = new Tone.EQ3(-10, 3, -20); + */ + Tone.EQ3 = function () { + var options = this.optionsObject(arguments, [ + 'low', + 'mid', + 'high' + ], Tone.EQ3.defaults); + /** + * the output node + * @type {GainNode} + * @private + */ + this.output = new Tone.Gain(); + /** + * the multiband split + * @type {Tone.MultibandSplit} + * @private + */ + this._multibandSplit = this.input = new Tone.MultibandSplit({ + 'lowFrequency': options.lowFrequency, + 'highFrequency': options.highFrequency + }); + /** + * The gain for the lower signals + * @type {Tone.Gain} + * @private + */ + this._lowGain = new Tone.Gain(options.low, Tone.Type.Decibels); + /** + * The gain for the mid signals + * @type {Tone.Gain} + * @private + */ + this._midGain = new Tone.Gain(options.mid, Tone.Type.Decibels); + /** + * The gain in decibels of the high part + * @type {Tone.Gain} + * @private + */ + this._highGain = new Tone.Gain(options.high, Tone.Type.Decibels); + /** + * The gain in decibels of the low part + * @type {Decibels} + * @signal + */ + this.low = this._lowGain.gain; + /** + * The gain in decibels of the mid part + * @type {Decibels} + * @signal + */ + this.mid = this._midGain.gain; + /** + * The gain in decibels of the high part + * @type {Decibels} + * @signal + */ + this.high = this._highGain.gain; + /** + * The Q value for all of the filters. + * @type {Positive} + * @signal + */ + this.Q = this._multibandSplit.Q; + /** + * The low/mid crossover frequency. + * @type {Frequency} + * @signal + */ + this.lowFrequency = this._multibandSplit.lowFrequency; + /** + * The mid/high crossover frequency. + * @type {Frequency} + * @signal + */ + this.highFrequency = this._multibandSplit.highFrequency; + //the frequency bands + this._multibandSplit.low.chain(this._lowGain, this.output); + this._multibandSplit.mid.chain(this._midGain, this.output); + this._multibandSplit.high.chain(this._highGain, this.output); + this._readOnly([ + 'low', + 'mid', + 'high', + 'lowFrequency', + 'highFrequency' + ]); + }; + Tone.extend(Tone.EQ3); + /** + * the default values + */ + Tone.EQ3.defaults = { + 'low': 0, + 'mid': 0, + 'high': 0, + 'lowFrequency': 400, + 'highFrequency': 2500 + }; + /** + * clean up + * @returns {Tone.EQ3} this + */ + Tone.EQ3.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'low', + 'mid', + 'high', + 'lowFrequency', + 'highFrequency' + ]); + this._multibandSplit.dispose(); + this._multibandSplit = null; + this.lowFrequency = null; + this.highFrequency = null; + this._lowGain.dispose(); + this._lowGain = null; + this._midGain.dispose(); + this._midGain = null; + this._highGain.dispose(); + this._highGain = null; + this.low = null; + this.mid = null; + this.high = null; + this.Q = null; + return this; + }; + return Tone.EQ3; + }); + Module(function (Tone) { + + /** + * @class Performs a linear scaling on an input signal. + * Scales a NormalRange input to between + * outputMin and outputMax. + * + * @constructor + * @extends {Tone.SignalBase} + * @param {number} [outputMin=0] The output value when the input is 0. + * @param {number} [outputMax=1] The output value when the input is 1. + * @example + * var scale = new Tone.Scale(50, 100); + * var signal = new Tone.Signal(0.5).connect(scale); + * //the output of scale equals 75 + */ + Tone.Scale = function (outputMin, outputMax) { + /** + * @private + * @type {number} + */ + this._outputMin = this.defaultArg(outputMin, 0); + /** + * @private + * @type {number} + */ + this._outputMax = this.defaultArg(outputMax, 1); + /** + * @private + * @type {Tone.Multiply} + * @private + */ + this._scale = this.input = new Tone.Multiply(1); + /** + * @private + * @type {Tone.Add} + * @private + */ + this._add = this.output = new Tone.Add(0); + this._scale.connect(this._add); + this._setRange(); + }; + Tone.extend(Tone.Scale, Tone.SignalBase); + /** + * The minimum output value. This number is output when + * the value input value is 0. + * @memberOf Tone.Scale# + * @type {number} + * @name min + */ + Object.defineProperty(Tone.Scale.prototype, 'min', { + get: function () { + return this._outputMin; + }, + set: function (min) { + this._outputMin = min; + this._setRange(); + } + }); + /** + * The maximum output value. This number is output when + * the value input value is 1. + * @memberOf Tone.Scale# + * @type {number} + * @name max + */ + Object.defineProperty(Tone.Scale.prototype, 'max', { + get: function () { + return this._outputMax; + }, + set: function (max) { + this._outputMax = max; + this._setRange(); + } + }); + /** + * set the values + * @private + */ + Tone.Scale.prototype._setRange = function () { + this._add.value = this._outputMin; + this._scale.value = this._outputMax - this._outputMin; + }; + /** + * Clean up. + * @returns {Tone.Scale} this + */ + Tone.Scale.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._add.dispose(); + this._add = null; + this._scale.dispose(); + this._scale = null; + return this; + }; + return Tone.Scale; + }); + Module(function (Tone) { + /** + * @class Performs an exponential scaling on an input signal. + * Scales a NormalRange value [0,1] exponentially + * to the output range of outputMin to outputMax. + * + * @constructor + * @extends {Tone.SignalBase} + * @param {number} [outputMin=0] The output value when the input is 0. + * @param {number} [outputMax=1] The output value when the input is 1. + * @param {number} [exponent=2] The exponent which scales the incoming signal. + * @example + * var scaleExp = new Tone.ScaleExp(0, 100, 2); + * var signal = new Tone.Signal(0.5).connect(scaleExp); + */ + Tone.ScaleExp = function (outputMin, outputMax, exponent) { + /** + * scale the input to the output range + * @type {Tone.Scale} + * @private + */ + this._scale = this.output = new Tone.Scale(outputMin, outputMax); + /** + * @private + * @type {Tone.Pow} + * @private + */ + this._exp = this.input = new Tone.Pow(this.defaultArg(exponent, 2)); + this._exp.connect(this._scale); + }; + Tone.extend(Tone.ScaleExp, Tone.SignalBase); + /** + * Instead of interpolating linearly between the min and + * max values, setting the exponent will interpolate between + * the two values with an exponential curve. + * @memberOf Tone.ScaleExp# + * @type {number} + * @name exponent + */ + Object.defineProperty(Tone.ScaleExp.prototype, 'exponent', { + get: function () { + return this._exp.value; + }, + set: function (exp) { + this._exp.value = exp; + } + }); + /** + * The minimum output value. This number is output when + * the value input value is 0. + * @memberOf Tone.ScaleExp# + * @type {number} + * @name min + */ + Object.defineProperty(Tone.ScaleExp.prototype, 'min', { + get: function () { + return this._scale.min; + }, + set: function (min) { + this._scale.min = min; + } + }); + /** + * The maximum output value. This number is output when + * the value input value is 1. + * @memberOf Tone.ScaleExp# + * @type {number} + * @name max + */ + Object.defineProperty(Tone.ScaleExp.prototype, 'max', { + get: function () { + return this._scale.max; + }, + set: function (max) { + this._scale.max = max; + } + }); + /** + * Clean up. + * @returns {Tone.ScaleExp} this + */ + Tone.ScaleExp.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._scale.dispose(); + this._scale = null; + this._exp.dispose(); + this._exp = null; + return this; + }; + return Tone.ScaleExp; + }); + Module(function (Tone) { + + /** + * createDelay shim + * @private + */ + if (window.DelayNode && !AudioContext.prototype.createDelay) { + AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; + } + /** + * @class Wrapper around Web Audio's native [DelayNode](http://webaudio.github.io/web-audio-api/#the-delaynode-interface). + * @extends {Tone} + * @param {Time=} delayTime The delay applied to the incoming signal. + * @param {Time=} maxDelay The maximum delay time. + */ + Tone.Delay = function () { + var options = this.optionsObject(arguments, [ + 'delayTime', + 'maxDelay' + ], Tone.Delay.defaults); + /** + * The native delay node + * @type {DelayNode} + * @private + */ + this._delayNode = this.input = this.output = this.context.createDelay(this.toSeconds(options.maxDelay)); + /** + * The amount of time the incoming signal is + * delayed. + * @type {Tone.Param} + * @signal + */ + this.delayTime = new Tone.Param({ + 'param': this._delayNode.delayTime, + 'units': Tone.Type.Time, + 'value': options.delayTime + }); + this._readOnly('delayTime'); + }; + Tone.extend(Tone.Delay); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.Delay.defaults = { + 'maxDelay': 1, + 'delayTime': 0 + }; + /** + * Clean up. + * @return {Tone.Delay} this + */ + Tone.Delay.prototype.dispose = function () { + Tone.Param.prototype.dispose.call(this); + this._delayNode.disconnect(); + this._delayNode = null; + this._writable('delayTime'); + this.delayTime = null; + return this; + }; + return Tone.Delay; + }); + Module(function (Tone) { + + /** + * @class Comb filters are basic building blocks for physical modeling. Read more + * about comb filters on [CCRMA's website](https://ccrma.stanford.edu/~jos/pasp/Feedback_Comb_Filters.html). + * + * @extends {Tone} + * @constructor + * @param {Time|Object} [delayTime] The delay time of the filter. + * @param {NormalRange=} resonance The amount of feedback the filter has. + */ + Tone.FeedbackCombFilter = function () { + var options = this.optionsObject(arguments, [ + 'delayTime', + 'resonance' + ], Tone.FeedbackCombFilter.defaults); + /** + * the delay node + * @type {DelayNode} + * @private + */ + this._delay = this.input = this.output = new Tone.Delay(options.delayTime); + /** + * The amount of delay of the comb filter. + * @type {Time} + * @signal + */ + this.delayTime = this._delay.delayTime; + /** + * the feedback node + * @type {GainNode} + * @private + */ + this._feedback = new Tone.Gain(options.resonance, Tone.Type.NormalRange); + /** + * The amount of feedback of the delayed signal. + * @type {NormalRange} + * @signal + */ + this.resonance = this._feedback.gain; + this._delay.chain(this._feedback, this._delay); + this._readOnly([ + 'resonance', + 'delayTime' + ]); + }; + Tone.extend(Tone.FeedbackCombFilter); + /** + * the default parameters + * @static + * @const + * @type {Object} + */ + Tone.FeedbackCombFilter.defaults = { + 'delayTime': 0.1, + 'resonance': 0.5 + }; + /** + * clean up + * @returns {Tone.FeedbackCombFilter} this + */ + Tone.FeedbackCombFilter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'resonance', + 'delayTime' + ]); + this._delay.dispose(); + this._delay = null; + this.delayTime = null; + this._feedback.dispose(); + this._feedback = null; + this.resonance = null; + return this; + }; + return Tone.FeedbackCombFilter; + }); + Module(function (Tone) { + + /** + * @class Tone.Follower is a crude envelope follower which will follow + * the amplitude of an incoming signal. + * Take care with small (< 0.02) attack or decay values + * as follower has some ripple which is exaggerated + * at these values. Read more about envelope followers (also known + * as envelope detectors) on [Wikipedia](https://en.wikipedia.org/wiki/Envelope_detector). + * + * @constructor + * @extends {Tone} + * @param {Time|Object} [attack] The rate at which the follower rises. + * @param {Time=} release The rate at which the folower falls. + * @example + * var follower = new Tone.Follower(0.2, 0.4); + */ + Tone.Follower = function () { + this.createInsOuts(1, 1); + var options = this.optionsObject(arguments, [ + 'attack', + 'release' + ], Tone.Follower.defaults); + /** + * @type {Tone.Abs} + * @private + */ + this._abs = new Tone.Abs(); + /** + * the lowpass filter which smooths the input + * @type {BiquadFilterNode} + * @private + */ + this._filter = this.context.createBiquadFilter(); + this._filter.type = 'lowpass'; + this._filter.frequency.value = 0; + this._filter.Q.value = -100; + /** + * @type {WaveShaperNode} + * @private + */ + this._frequencyValues = new Tone.WaveShaper(); + /** + * @type {Tone.Subtract} + * @private + */ + this._sub = new Tone.Subtract(); + /** + * @type {Tone.Delay} + * @private + */ + this._delay = new Tone.Delay(this.blockTime); + /** + * this keeps it far from 0, even for very small differences + * @type {Tone.Multiply} + * @private + */ + this._mult = new Tone.Multiply(10000); + /** + * @private + * @type {number} + */ + this._attack = options.attack; + /** + * @private + * @type {number} + */ + this._release = options.release; + //the smoothed signal to get the values + this.input.chain(this._abs, this._filter, this.output); + //the difference path + this._abs.connect(this._sub, 0, 1); + this._filter.chain(this._delay, this._sub); + //threshold the difference and use the thresh to set the frequency + this._sub.chain(this._mult, this._frequencyValues, this._filter.frequency); + //set the attack and release values in the table + this._setAttackRelease(this._attack, this._release); + }; + Tone.extend(Tone.Follower); + /** + * @static + * @type {Object} + */ + Tone.Follower.defaults = { + 'attack': 0.05, + 'release': 0.5 + }; + /** + * sets the attack and release times in the wave shaper + * @param {Time} attack + * @param {Time} release + * @private + */ + Tone.Follower.prototype._setAttackRelease = function (attack, release) { + var minTime = this.blockTime; + attack = Tone.Time(attack).toFrequency(); + release = Tone.Time(release).toFrequency(); + attack = Math.max(attack, minTime); + release = Math.max(release, minTime); + this._frequencyValues.setMap(function (val) { + if (val <= 0) { + return attack; + } else { + return release; + } + }); + }; + /** + * The attack time. + * @memberOf Tone.Follower# + * @type {Time} + * @name attack + */ + Object.defineProperty(Tone.Follower.prototype, 'attack', { + get: function () { + return this._attack; + }, + set: function (attack) { + this._attack = attack; + this._setAttackRelease(this._attack, this._release); + } + }); + /** + * The release time. + * @memberOf Tone.Follower# + * @type {Time} + * @name release + */ + Object.defineProperty(Tone.Follower.prototype, 'release', { + get: function () { + return this._release; + }, + set: function (release) { + this._release = release; + this._setAttackRelease(this._attack, this._release); + } + }); + /** + * Borrows the connect method from Signal so that the output can be used + * as a Tone.Signal control signal. + * @function + */ + Tone.Follower.prototype.connect = Tone.Signal.prototype.connect; + /** + * dispose + * @returns {Tone.Follower} this + */ + Tone.Follower.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._filter.disconnect(); + this._filter = null; + this._frequencyValues.disconnect(); + this._frequencyValues = null; + this._delay.dispose(); + this._delay = null; + this._sub.disconnect(); + this._sub = null; + this._abs.dispose(); + this._abs = null; + this._mult.dispose(); + this._mult = null; + this._curve = null; + return this; + }; + return Tone.Follower; + }); + Module(function (Tone) { + + /** + * @class Tone.ScaledEnvelop is an envelope which can be scaled + * to any range. It's useful for applying an envelope + * to a frequency or any other non-NormalRange signal + * parameter. + * + * @extends {Tone.Envelope} + * @constructor + * @param {Time|Object} [attack] the attack time in seconds + * @param {Time} [decay] the decay time in seconds + * @param {number} [sustain] a percentage (0-1) of the full amplitude + * @param {Time} [release] the release time in seconds + * @example + * var scaledEnv = new Tone.ScaledEnvelope({ + * "attack" : 0.2, + * "min" : 200, + * "max" : 2000 + * }); + * scaledEnv.connect(oscillator.frequency); + */ + Tone.ScaledEnvelope = function () { + //get all of the defaults + var options = this.optionsObject(arguments, [ + 'attack', + 'decay', + 'sustain', + 'release' + ], Tone.Envelope.defaults); + Tone.Envelope.call(this, options); + options = this.defaultArg(options, Tone.ScaledEnvelope.defaults); + /** + * scale the incoming signal by an exponent + * @type {Tone.Pow} + * @private + */ + this._exp = this.output = new Tone.Pow(options.exponent); + /** + * scale the signal to the desired range + * @type {Tone.Multiply} + * @private + */ + this._scale = this.output = new Tone.Scale(options.min, options.max); + this._sig.chain(this._exp, this._scale); + }; + Tone.extend(Tone.ScaledEnvelope, Tone.Envelope); + /** + * the default parameters + * @static + */ + Tone.ScaledEnvelope.defaults = { + 'min': 0, + 'max': 1, + 'exponent': 1 + }; + /** + * The envelope's min output value. This is the value which it + * starts at. + * @memberOf Tone.ScaledEnvelope# + * @type {number} + * @name min + */ + Object.defineProperty(Tone.ScaledEnvelope.prototype, 'min', { + get: function () { + return this._scale.min; + }, + set: function (min) { + this._scale.min = min; + } + }); + /** + * The envelope's max output value. In other words, the value + * at the peak of the attack portion of the envelope. + * @memberOf Tone.ScaledEnvelope# + * @type {number} + * @name max + */ + Object.defineProperty(Tone.ScaledEnvelope.prototype, 'max', { + get: function () { + return this._scale.max; + }, + set: function (max) { + this._scale.max = max; + } + }); + /** + * The envelope's exponent value. + * @memberOf Tone.ScaledEnvelope# + * @type {number} + * @name exponent + */ + Object.defineProperty(Tone.ScaledEnvelope.prototype, 'exponent', { + get: function () { + return this._exp.value; + }, + set: function (exp) { + this._exp.value = exp; + } + }); + /** + * clean up + * @returns {Tone.ScaledEnvelope} this + */ + Tone.ScaledEnvelope.prototype.dispose = function () { + Tone.Envelope.prototype.dispose.call(this); + this._scale.dispose(); + this._scale = null; + this._exp.dispose(); + this._exp = null; + return this; + }; + return Tone.ScaledEnvelope; + }); + Module(function (Tone) { + + /** + * @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max` + * it's got a `baseFrequency` and `octaves` parameter. + * + * @extends {Tone.Envelope} + * @constructor + * @param {Time|Object} [attack] the attack time in seconds + * @param {Time} [decay] the decay time in seconds + * @param {number} [sustain] a percentage (0-1) of the full amplitude + * @param {Time} [release] the release time in seconds + * @example + * var env = new Tone.FrequencyEnvelope({ + * "attack" : 0.2, + * "baseFrequency" : "C2", + * "octaves" : 4 + * }); + * scaledEnv.connect(oscillator.frequency); + */ + Tone.FrequencyEnvelope = function () { + var options = this.optionsObject(arguments, [ + 'attack', + 'decay', + 'sustain', + 'release' + ], Tone.Envelope.defaults); + Tone.ScaledEnvelope.call(this, options); + options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults); + /** + * Stores the octave value + * @type {Positive} + * @private + */ + this._octaves = options.octaves; + //setup + this.baseFrequency = options.baseFrequency; + this.octaves = options.octaves; + }; + Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope); + /** + * the default parameters + * @static + */ + Tone.FrequencyEnvelope.defaults = { + 'baseFrequency': 200, + 'octaves': 4, + 'exponent': 2 + }; + /** + * The envelope's mininum output value. This is the value which it + * starts at. + * @memberOf Tone.FrequencyEnvelope# + * @type {Frequency} + * @name baseFrequency + */ + Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'baseFrequency', { + get: function () { + return this._scale.min; + }, + set: function (min) { + this._scale.min = this.toFrequency(min); + //also update the octaves + this.octaves = this._octaves; + } + }); + /** + * The number of octaves above the baseFrequency that the + * envelope will scale to. + * @memberOf Tone.FrequencyEnvelope# + * @type {Positive} + * @name octaves + */ + Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'octaves', { + get: function () { + return this._octaves; + }, + set: function (octaves) { + this._octaves = octaves; + this._scale.max = this.baseFrequency * Math.pow(2, octaves); + } + }); + /** + * The envelope's exponent value. + * @memberOf Tone.FrequencyEnvelope# + * @type {number} + * @name exponent + */ + Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'exponent', { + get: function () { + return this._exp.value; + }, + set: function (exp) { + this._exp.value = exp; + } + }); + /** + * clean up + * @returns {Tone.FrequencyEnvelope} this + */ + Tone.FrequencyEnvelope.prototype.dispose = function () { + Tone.ScaledEnvelope.prototype.dispose.call(this); + return this; + }; + return Tone.FrequencyEnvelope; + }); + Module(function (Tone) { + + /** + * @class Tone.Gate only passes a signal through when the incoming + * signal exceeds a specified threshold. To do this, Gate uses + * a Tone.Follower to follow the amplitude of the incoming signal. + * A common implementation of this class is a [Noise Gate](https://en.wikipedia.org/wiki/Noise_gate). + * + * @constructor + * @extends {Tone} + * @param {Decibels|Object} [threshold] The threshold above which the gate will open. + * @param {Time=} attack The follower's attack time + * @param {Time=} release The follower's release time + * @example + * var gate = new Tone.Gate(-30, 0.2, 0.3).toMaster(); + * var mic = new Tone.UserMedia().connect(gate); + * //the gate will only pass through the incoming + * //signal when it's louder than -30db + */ + Tone.Gate = function () { + this.createInsOuts(1, 1); + var options = this.optionsObject(arguments, [ + 'threshold', + 'attack', + 'release' + ], Tone.Gate.defaults); + /** + * @type {Tone.Follower} + * @private + */ + this._follower = new Tone.Follower(options.attack, options.release); + /** + * @type {Tone.GreaterThan} + * @private + */ + this._gt = new Tone.GreaterThan(this.dbToGain(options.threshold)); + //the connections + this.input.connect(this.output); + //the control signal + this.input.chain(this._gt, this._follower, this.output.gain); + }; + Tone.extend(Tone.Gate); + /** + * @const + * @static + * @type {Object} + */ + Tone.Gate.defaults = { + 'attack': 0.1, + 'release': 0.1, + 'threshold': -40 + }; + /** + * The threshold of the gate in decibels + * @memberOf Tone.Gate# + * @type {Decibels} + * @name threshold + */ + Object.defineProperty(Tone.Gate.prototype, 'threshold', { + get: function () { + return this.gainToDb(this._gt.value); + }, + set: function (thresh) { + this._gt.value = this.dbToGain(thresh); + } + }); + /** + * The attack speed of the gate + * @memberOf Tone.Gate# + * @type {Time} + * @name attack + */ + Object.defineProperty(Tone.Gate.prototype, 'attack', { + get: function () { + return this._follower.attack; + }, + set: function (attackTime) { + this._follower.attack = attackTime; + } + }); + /** + * The release speed of the gate + * @memberOf Tone.Gate# + * @type {Time} + * @name release + */ + Object.defineProperty(Tone.Gate.prototype, 'release', { + get: function () { + return this._follower.release; + }, + set: function (releaseTime) { + this._follower.release = releaseTime; + } + }); + /** + * Clean up. + * @returns {Tone.Gate} this + */ + Tone.Gate.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._follower.dispose(); + this._gt.dispose(); + this._follower = null; + this._gt = null; + return this; + }; + return Tone.Gate; + }); + Module(function (Tone) { + + /** + * @class A Timeline State. Provides the methods: setStateAtTime("state", time) + * and getValueAtTime(time). + * + * @extends {Tone.Timeline} + * @param {String} initial The initial state of the TimelineState. + * Defaults to undefined + */ + Tone.TimelineState = function (initial) { + Tone.Timeline.call(this); + /** + * The initial state + * @private + * @type {String} + */ + this._initial = initial; + }; + Tone.extend(Tone.TimelineState, Tone.Timeline); + /** + * Returns the scheduled state scheduled before or at + * the given time. + * @param {Number} time The time to query. + * @return {String} The name of the state input in setStateAtTime. + */ + Tone.TimelineState.prototype.getValueAtTime = function (time) { + var event = this.get(time); + if (event !== null) { + return event.state; + } else { + return this._initial; + } + }; + /** + * Returns the scheduled state scheduled before or at + * the given time. + * @param {String} state The name of the state to set. + * @param {Number} time The time to query. + */ + Tone.TimelineState.prototype.setStateAtTime = function (state, time) { + this.add({ + 'state': state, + 'time': time + }); + }; + return Tone.TimelineState; + }); + Module(function (Tone) { + + /** + * @class A sample accurate clock which provides a callback at the given rate. + * While the callback is not sample-accurate (it is still susceptible to + * loose JS timing), the time passed in as the argument to the callback + * is precise. For most applications, it is better to use Tone.Transport + * instead of the Clock by itself since you can synchronize multiple callbacks. + * + * @constructor + * @extends {Tone.Emitter} + * @param {function} callback The callback to be invoked with the time of the audio event + * @param {Frequency} frequency The rate of the callback + * @example + * //the callback will be invoked approximately once a second + * //and will print the time exactly once a second apart. + * var clock = new Tone.Clock(function(time){ + * console.log(time); + * }, 1); + */ + Tone.Clock = function () { + Tone.Emitter.call(this); + var options = this.optionsObject(arguments, [ + 'callback', + 'frequency' + ], Tone.Clock.defaults); + /** + * The callback function to invoke at the scheduled tick. + * @type {Function} + */ + this.callback = options.callback; + /** + * The next time the callback is scheduled. + * @type {Number} + * @private + */ + this._nextTick = 0; + /** + * The last state of the clock. + * @type {State} + * @private + */ + this._lastState = Tone.State.Stopped; + /** + * The rate the callback function should be invoked. + * @type {BPM} + * @signal + */ + this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); + this._readOnly('frequency'); + /** + * The number of times the callback was invoked. Starts counting at 0 + * and increments after the callback was invoked. + * @type {Ticks} + * @readOnly + */ + this.ticks = 0; + /** + * The state timeline + * @type {Tone.TimelineState} + * @private + */ + this._state = new Tone.TimelineState(Tone.State.Stopped); + /** + * The loop function bound to its context. + * This is necessary to remove the event in the end. + * @type {Function} + * @private + */ + this._boundLoop = this._loop.bind(this); + //bind a callback to the worker thread + this.context.on('tick', this._boundLoop); + }; + Tone.extend(Tone.Clock, Tone.Emitter); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.Clock.defaults = { + 'callback': Tone.noOp, + 'frequency': 1, + 'lookAhead': 'auto' + }; + /** + * Returns the playback state of the source, either "started", "stopped" or "paused". + * @type {Tone.State} + * @readOnly + * @memberOf Tone.Clock# + * @name state + */ + Object.defineProperty(Tone.Clock.prototype, 'state', { + get: function () { + return this._state.getValueAtTime(this.now()); + } + }); + /** + * Start the clock at the given time. Optionally pass in an offset + * of where to start the tick counter from. + * @param {Time} time The time the clock should start + * @param {Ticks=} offset Where the tick counter starts counting from. + * @return {Tone.Clock} this + */ + Tone.Clock.prototype.start = function (time, offset) { + time = this.toSeconds(time); + if (this._state.getValueAtTime(time) !== Tone.State.Started) { + this._state.add({ + 'state': Tone.State.Started, + 'time': time, + 'offset': offset + }); + } + return this; + }; + /** + * Stop the clock. Stopping the clock resets the tick counter to 0. + * @param {Time} [time=now] The time when the clock should stop. + * @returns {Tone.Clock} this + * @example + * clock.stop(); + */ + Tone.Clock.prototype.stop = function (time) { + time = this.toSeconds(time); + this._state.cancel(time); + this._state.setStateAtTime(Tone.State.Stopped, time); + return this; + }; + /** + * Pause the clock. Pausing does not reset the tick counter. + * @param {Time} [time=now] The time when the clock should stop. + * @returns {Tone.Clock} this + */ + Tone.Clock.prototype.pause = function (time) { + time = this.toSeconds(time); + if (this._state.getValueAtTime(time) === Tone.State.Started) { + this._state.setStateAtTime(Tone.State.Paused, time); + } + return this; + }; + /** + * The scheduling loop. + * @param {Number} time The current page time starting from 0 + * when the page was loaded. + * @private + */ + Tone.Clock.prototype._loop = function () { + //get the frequency value to compute the value of the next loop + var now = this.now(); + //if it's started + var lookAhead = this.context.lookAhead; + var updateInterval = this.context.updateInterval; + var lagCompensation = this.context.lag * 2; + var loopInterval = now + lookAhead + updateInterval + lagCompensation; + while (loopInterval > this._nextTick && this._state) { + var currentState = this._state.getValueAtTime(this._nextTick); + if (currentState !== this._lastState) { + this._lastState = currentState; + var event = this._state.get(this._nextTick); + // emit an event + if (currentState === Tone.State.Started) { + //correct the time + this._nextTick = event.time; + if (!this.isUndef(event.offset)) { + this.ticks = event.offset; + } + this.emit('start', event.time, this.ticks); + } else if (currentState === Tone.State.Stopped) { + this.ticks = 0; + this.emit('stop', event.time); + } else if (currentState === Tone.State.Paused) { + this.emit('pause', event.time); + } + } + var tickTime = this._nextTick; + if (this.frequency) { + this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); + if (currentState === Tone.State.Started) { + this.callback(tickTime); + this.ticks++; + } + } + } + }; + /** + * Returns the scheduled state at the given time. + * @param {Time} time The time to query. + * @return {String} The name of the state input in setStateAtTime. + * @example + * clock.start("+0.1"); + * clock.getStateAtTime("+0.1"); //returns "started" + */ + Tone.Clock.prototype.getStateAtTime = function (time) { + time = this.toSeconds(time); + return this._state.getValueAtTime(time); + }; + /** + * Clean up + * @returns {Tone.Clock} this + */ + Tone.Clock.prototype.dispose = function () { + Tone.Emitter.prototype.dispose.call(this); + this.context.off('tick', this._boundLoop); + this._writable('frequency'); + this.frequency.dispose(); + this.frequency = null; + this._boundLoop = null; + this._nextTick = Infinity; + this.callback = null; + this._state.dispose(); + this._state = null; + }; + return Tone.Clock; + }); + Module(function (Tone) { + + /** + * @class Similar to Tone.Timeline, but all events represent + * intervals with both "time" and "duration" times. The + * events are placed in a tree structure optimized + * for querying an intersection point with the timeline + * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree) + * to represent the data. + * @extends {Tone} + */ + Tone.IntervalTimeline = function () { + /** + * The root node of the inteval tree + * @type {IntervalNode} + * @private + */ + this._root = null; + /** + * Keep track of the length of the timeline. + * @type {Number} + * @private + */ + this._length = 0; + }; + Tone.extend(Tone.IntervalTimeline); + /** + * The event to add to the timeline. All events must + * have a time and duration value + * @param {Object} event The event to add to the timeline + * @return {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.add = function (event) { + if (this.isUndef(event.time) || this.isUndef(event.duration)) { + throw new Error('Tone.IntervalTimeline: events must have time and duration parameters'); + } + var node = new IntervalNode(event.time, event.time + event.duration, event); + if (this._root === null) { + this._root = node; + } else { + this._root.insert(node); + } + this._length++; + // Restructure tree to be balanced + while (node !== null) { + node.updateHeight(); + node.updateMax(); + this._rebalance(node); + node = node.parent; + } + return this; + }; + /** + * Remove an event from the timeline. + * @param {Object} event The event to remove from the timeline + * @return {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.remove = function (event) { + if (this._root !== null) { + var results = []; + this._root.search(event.time, results); + for (var i = 0; i < results.length; i++) { + var node = results[i]; + if (node.event === event) { + this._removeNode(node); + this._length--; + break; + } + } + } + return this; + }; + /** + * The number of items in the timeline. + * @type {Number} + * @memberOf Tone.IntervalTimeline# + * @name length + * @readOnly + */ + Object.defineProperty(Tone.IntervalTimeline.prototype, 'length', { + get: function () { + return this._length; + } + }); + /** + * Remove events whose time time is after the given time + * @param {Number} time The time to query. + * @returns {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.cancel = function (after) { + this.forEachAfter(after, function (event) { + this.remove(event); + }.bind(this)); + return this; + }; + /** + * Set the root node as the given node + * @param {IntervalNode} node + * @private + */ + Tone.IntervalTimeline.prototype._setRoot = function (node) { + this._root = node; + if (this._root !== null) { + this._root.parent = null; + } + }; + /** + * Replace the references to the node in the node's parent + * with the replacement node. + * @param {IntervalNode} node + * @param {IntervalNode} replacement + * @private + */ + Tone.IntervalTimeline.prototype._replaceNodeInParent = function (node, replacement) { + if (node.parent !== null) { + if (node.isLeftChild()) { + node.parent.left = replacement; + } else { + node.parent.right = replacement; + } + this._rebalance(node.parent); + } else { + this._setRoot(replacement); + } + }; + /** + * Remove the node from the tree and replace it with + * a successor which follows the schema. + * @param {IntervalNode} node + * @private + */ + Tone.IntervalTimeline.prototype._removeNode = function (node) { + if (node.left === null && node.right === null) { + this._replaceNodeInParent(node, null); + } else if (node.right === null) { + this._replaceNodeInParent(node, node.left); + } else if (node.left === null) { + this._replaceNodeInParent(node, node.right); + } else { + var balance = node.getBalance(); + var replacement, temp; + if (balance > 0) { + if (node.left.right === null) { + replacement = node.left; + replacement.right = node.right; + temp = replacement; + } else { + replacement = node.left.right; + while (replacement.right !== null) { + replacement = replacement.right; + } + replacement.parent.right = replacement.left; + temp = replacement.parent; + replacement.left = node.left; + replacement.right = node.right; + } + } else { + if (node.right.left === null) { + replacement = node.right; + replacement.left = node.left; + temp = replacement; + } else { + replacement = node.right.left; + while (replacement.left !== null) { + replacement = replacement.left; + } + replacement.parent = replacement.parent; + replacement.parent.left = replacement.right; + temp = replacement.parent; + replacement.left = node.left; + replacement.right = node.right; + } + } + if (node.parent !== null) { + if (node.isLeftChild()) { + node.parent.left = replacement; + } else { + node.parent.right = replacement; + } + } else { + this._setRoot(replacement); + } + // this._replaceNodeInParent(node, replacement); + this._rebalance(temp); + } + node.dispose(); + }; + /** + * Rotate the tree to the left + * @param {IntervalNode} node + * @private + */ + Tone.IntervalTimeline.prototype._rotateLeft = function (node) { + var parent = node.parent; + var isLeftChild = node.isLeftChild(); + // Make node.right the new root of this sub tree (instead of node) + var pivotNode = node.right; + node.right = pivotNode.left; + pivotNode.left = node; + if (parent !== null) { + if (isLeftChild) { + parent.left = pivotNode; + } else { + parent.right = pivotNode; + } + } else { + this._setRoot(pivotNode); + } + }; + /** + * Rotate the tree to the right + * @param {IntervalNode} node + * @private + */ + Tone.IntervalTimeline.prototype._rotateRight = function (node) { + var parent = node.parent; + var isLeftChild = node.isLeftChild(); + // Make node.left the new root of this sub tree (instead of node) + var pivotNode = node.left; + node.left = pivotNode.right; + pivotNode.right = node; + if (parent !== null) { + if (isLeftChild) { + parent.left = pivotNode; + } else { + parent.right = pivotNode; + } + } else { + this._setRoot(pivotNode); + } + }; + /** + * Balance the BST + * @param {IntervalNode} node + * @private + */ + Tone.IntervalTimeline.prototype._rebalance = function (node) { + var balance = node.getBalance(); + if (balance > 1) { + if (node.left.getBalance() < 0) { + this._rotateLeft(node.left); + } else { + this._rotateRight(node); + } + } else if (balance < -1) { + if (node.right.getBalance() > 0) { + this._rotateRight(node.right); + } else { + this._rotateLeft(node); + } + } + }; + /** + * Get an event whose time and duration span the give time. Will + * return the match whose "time" value is closest to the given time. + * @param {Object} event The event to add to the timeline + * @return {Object} The event which spans the desired time + */ + Tone.IntervalTimeline.prototype.get = function (time) { + if (this._root !== null) { + var results = []; + this._root.search(time, results); + if (results.length > 0) { + var max = results[0]; + for (var i = 1; i < results.length; i++) { + if (results[i].low > max.low) { + max = results[i]; + } + } + return max.event; + } + } + return null; + }; + /** + * Iterate over everything in the timeline. + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.forEach = function (callback) { + if (this._root !== null) { + var allNodes = []; + if (this._root !== null) { + this._root.traverse(function (node) { + allNodes.push(node); + }); + } + for (var i = 0; i < allNodes.length; i++) { + var ev = allNodes[i].event; + if (ev) { + callback(ev); + } + } + } + return this; + }; + /** + * Iterate over everything in the array in which the given time + * overlaps with the time and duration time of the event. + * @param {Number} time The time to check if items are overlapping + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.forEachAtTime = function (time, callback) { + if (this._root !== null) { + var results = []; + this._root.search(time, results); + for (var i = results.length - 1; i >= 0; i--) { + var ev = results[i].event; + if (ev) { + callback(ev); + } + } + } + return this; + }; + /** + * Iterate over everything in the array in which the time is greater + * than the given time. + * @param {Number} time The time to check if items are before + * @param {Function} callback The callback to invoke with every item + * @returns {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.forEachAfter = function (time, callback) { + if (this._root !== null) { + var results = []; + this._root.searchAfter(time, results); + for (var i = results.length - 1; i >= 0; i--) { + var ev = results[i].event; + if (ev) { + callback(ev); + } + } + } + return this; + }; + /** + * Clean up + * @return {Tone.IntervalTimeline} this + */ + Tone.IntervalTimeline.prototype.dispose = function () { + var allNodes = []; + if (this._root !== null) { + this._root.traverse(function (node) { + allNodes.push(node); + }); + } + for (var i = 0; i < allNodes.length; i++) { + allNodes[i].dispose(); + } + allNodes = null; + this._root = null; + return this; + }; + /////////////////////////////////////////////////////////////////////////// + // INTERVAL NODE HELPER + /////////////////////////////////////////////////////////////////////////// + /** + * Represents a node in the binary search tree, with the addition + * of a "high" value which keeps track of the highest value of + * its children. + * References: + * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/ + * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf + * @param {Number} low + * @param {Number} high + * @private + */ + var IntervalNode = function (low, high, event) { + //the event container + this.event = event; + //the low value + this.low = low; + //the high value + this.high = high; + //the high value for this and all child nodes + this.max = this.high; + //the nodes to the left + this._left = null; + //the nodes to the right + this._right = null; + //the parent node + this.parent = null; + //the number of child nodes + this.height = 0; + }; + /** + * Insert a node into the correct spot in the tree + * @param {IntervalNode} node + */ + IntervalNode.prototype.insert = function (node) { + if (node.low <= this.low) { + if (this.left === null) { + this.left = node; + } else { + this.left.insert(node); + } + } else { + if (this.right === null) { + this.right = node; + } else { + this.right.insert(node); + } + } + }; + /** + * Search the tree for nodes which overlap + * with the given point + * @param {Number} point The point to query + * @param {Array} results The array to put the results + */ + IntervalNode.prototype.search = function (point, results) { + // If p is to the right of the rightmost point of any interval + // in this node and all children, there won't be any matches. + if (point > this.max) { + return; + } + // Search left children + if (this.left !== null) { + this.left.search(point, results); + } + // Check this node + if (this.low <= point && this.high > point) { + results.push(this); + } + // If p is to the left of the time of this interval, + // then it can't be in any child to the right. + if (this.low > point) { + return; + } + // Search right children + if (this.right !== null) { + this.right.search(point, results); + } + }; + /** + * Search the tree for nodes which are less + * than the given point + * @param {Number} point The point to query + * @param {Array} results The array to put the results + */ + IntervalNode.prototype.searchAfter = function (point, results) { + // Check this node + if (this.low >= point) { + results.push(this); + if (this.left !== null) { + this.left.searchAfter(point, results); + } + } + // search the right side + if (this.right !== null) { + this.right.searchAfter(point, results); + } + }; + /** + * Invoke the callback on this element and both it's branches + * @param {Function} callback + */ + IntervalNode.prototype.traverse = function (callback) { + callback(this); + if (this.left !== null) { + this.left.traverse(callback); + } + if (this.right !== null) { + this.right.traverse(callback); + } + }; + /** + * Update the height of the node + */ + IntervalNode.prototype.updateHeight = function () { + if (this.left !== null && this.right !== null) { + this.height = Math.max(this.left.height, this.right.height) + 1; + } else if (this.right !== null) { + this.height = this.right.height + 1; + } else if (this.left !== null) { + this.height = this.left.height + 1; + } else { + this.height = 0; + } + }; + /** + * Update the height of the node + */ + IntervalNode.prototype.updateMax = function () { + this.max = this.high; + if (this.left !== null) { + this.max = Math.max(this.max, this.left.max); + } + if (this.right !== null) { + this.max = Math.max(this.max, this.right.max); + } + }; + /** + * The balance is how the leafs are distributed on the node + * @return {Number} Negative numbers are balanced to the right + */ + IntervalNode.prototype.getBalance = function () { + var balance = 0; + if (this.left !== null && this.right !== null) { + balance = this.left.height - this.right.height; + } else if (this.left !== null) { + balance = this.left.height + 1; + } else if (this.right !== null) { + balance = -(this.right.height + 1); + } + return balance; + }; + /** + * @returns {Boolean} true if this node is the left child + * of its parent + */ + IntervalNode.prototype.isLeftChild = function () { + return this.parent !== null && this.parent.left === this; + }; + /** + * get/set the left node + * @type {IntervalNode} + */ + Object.defineProperty(IntervalNode.prototype, 'left', { + get: function () { + return this._left; + }, + set: function (node) { + this._left = node; + if (node !== null) { + node.parent = this; + } + this.updateHeight(); + this.updateMax(); + } + }); + /** + * get/set the right node + * @type {IntervalNode} + */ + Object.defineProperty(IntervalNode.prototype, 'right', { + get: function () { + return this._right; + }, + set: function (node) { + this._right = node; + if (node !== null) { + node.parent = this; + } + this.updateHeight(); + this.updateMax(); + } + }); + /** + * null out references. + */ + IntervalNode.prototype.dispose = function () { + this.parent = null; + this._left = null; + this._right = null; + this.event = null; + }; + /////////////////////////////////////////////////////////////////////////// + // END INTERVAL NODE HELPER + /////////////////////////////////////////////////////////////////////////// + return Tone.IntervalTimeline; + }); + Module(function (Tone) { + + /** + * @class Transport for timing musical events. + * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame) + * Tone.Transport timing events pass in the exact time of the scheduled event + * in the argument of the callback function. Pass that time value to the object + * you're scheduling.

+ * A single transport is created for you when the library is initialized. + *

+ * The transport emits the events: "start", "stop", "pause", and "loop" which are + * called with the time of that event as the argument. + * + * @extends {Tone.Emitter} + * @singleton + * @example + * //repeated event every 8th note + * Tone.Transport.scheduleRepeat(function(time){ + * //do something with the time + * }, "8n"); + * @example + * //schedule an event on the 16th measure + * Tone.Transport.schedule(function(time){ + * //do something with the time + * }, "16:0:0"); + */ + Tone.Transport = function () { + Tone.Emitter.call(this); + /////////////////////////////////////////////////////////////////////// + // LOOPING + ////////////////////////////////////////////////////////////////////// + /** + * If the transport loops or not. + * @type {boolean} + */ + this.loop = false; + /** + * The loop start position in ticks + * @type {Ticks} + * @private + */ + this._loopStart = 0; + /** + * The loop end position in ticks + * @type {Ticks} + * @private + */ + this._loopEnd = 0; + /////////////////////////////////////////////////////////////////////// + // CLOCK/TEMPO + ////////////////////////////////////////////////////////////////////// + /** + * Pulses per quarter is the number of ticks per quarter note. + * @private + * @type {Number} + */ + this._ppq = TransportConstructor.defaults.PPQ; + /** + * watches the main oscillator for timing ticks + * initially starts at 120bpm + * @private + * @type {Tone.Clock} + */ + this._clock = new Tone.Clock({ + 'callback': this._processTick.bind(this), + 'frequency': 0 + }); + this._bindClockEvents(); + /** + * The Beats Per Minute of the Transport. + * @type {BPM} + * @signal + * @example + * Tone.Transport.bpm.value = 80; + * //ramp the bpm to 120 over 10 seconds + * Tone.Transport.bpm.rampTo(120, 10); + */ + this.bpm = this._clock.frequency; + this.bpm._toUnits = this._toUnits.bind(this); + this.bpm._fromUnits = this._fromUnits.bind(this); + this.bpm.units = Tone.Type.BPM; + this.bpm.value = TransportConstructor.defaults.bpm; + this._readOnly('bpm'); + /** + * The time signature, or more accurately the numerator + * of the time signature over a denominator of 4. + * @type {Number} + * @private + */ + this._timeSignature = TransportConstructor.defaults.timeSignature; + /////////////////////////////////////////////////////////////////////// + // TIMELINE EVENTS + ////////////////////////////////////////////////////////////////////// + /** + * All the events in an object to keep track by ID + * @type {Object} + * @private + */ + this._scheduledEvents = {}; + /** + * The event ID counter + * @type {Number} + * @private + */ + this._eventID = 0; + /** + * The scheduled events. + * @type {Tone.Timeline} + * @private + */ + this._timeline = new Tone.Timeline(); + /** + * Repeated events + * @type {Array} + * @private + */ + this._repeatedEvents = new Tone.IntervalTimeline(); + /** + * Events that occur once + * @type {Array} + * @private + */ + this._onceEvents = new Tone.Timeline(); + /** + * All of the synced Signals + * @private + * @type {Array} + */ + this._syncedSignals = []; + /////////////////////////////////////////////////////////////////////// + // SWING + ////////////////////////////////////////////////////////////////////// + /** + * The subdivision of the swing + * @type {Ticks} + * @private + */ + this._swingTicks = TransportConstructor.defaults.PPQ / 2; + //8n + /** + * The swing amount + * @type {NormalRange} + * @private + */ + this._swingAmount = 0; + }; + Tone.extend(Tone.Transport, Tone.Emitter); + /** + * the defaults + * @type {Object} + * @const + * @static + */ + Tone.Transport.defaults = { + 'bpm': 120, + 'swing': 0, + 'swingSubdivision': '8n', + 'timeSignature': 4, + 'loopStart': 0, + 'loopEnd': '4m', + 'PPQ': 192 + }; + /////////////////////////////////////////////////////////////////////////////// + // TICKS + /////////////////////////////////////////////////////////////////////////////// + /** + * called on every tick + * @param {number} tickTime clock relative tick time + * @private + */ + Tone.Transport.prototype._processTick = function (tickTime) { + var ticks = this._clock.ticks; + //handle swing + if (this._swingAmount > 0 && ticks % this._ppq !== 0 && //not on a downbeat + ticks % (this._swingTicks * 2) !== 0) { + //add some swing + var progress = ticks % (this._swingTicks * 2) / (this._swingTicks * 2); + var amount = Math.sin(progress * Math.PI) * this._swingAmount; + tickTime += Tone.Time(this._swingTicks * 2 / 3, 'i') * amount; + } + //do the loop test + if (this.loop) { + if (ticks === this._loopEnd) { + this.emit('loopEnd', tickTime); + this._clock.ticks = this._loopStart; + ticks = this._loopStart; + this.emit('loopStart', tickTime, this.seconds); + this.emit('loop', tickTime); + } + } + //process the single occurrence events + this._onceEvents.forEachBefore(ticks, function (event) { + event.callback(tickTime); + //remove the event + delete this._scheduledEvents[event.id.toString()]; + }.bind(this)); + //and clear the single occurrence timeline + this._onceEvents.cancelBefore(ticks); + //fire the next tick events if their time has come + this._timeline.forEachAtTime(ticks, function (event) { + event.callback(tickTime); + }); + //process the repeated events + this._repeatedEvents.forEachAtTime(ticks, function (event) { + if ((ticks - event.time) % event.interval === 0) { + event.callback(tickTime); + } + }); + }; + /////////////////////////////////////////////////////////////////////////////// + // SCHEDULABLE EVENTS + /////////////////////////////////////////////////////////////////////////////// + /** + * Schedule an event along the timeline. + * @param {Function} callback The callback to be invoked at the time. + * @param {TransportTime} time The time to invoke the callback at. + * @return {Number} The id of the event which can be used for canceling the event. + * @example + * //trigger the callback when the Transport reaches the desired time + * Tone.Transport.schedule(function(time){ + * envelope.triggerAttack(time); + * }, "128i"); + */ + Tone.Transport.prototype.schedule = function (callback, time) { + var event = { + 'time': this.toTicks(time), + 'callback': callback + }; + var id = this._eventID++; + this._scheduledEvents[id.toString()] = { + 'event': event, + 'timeline': this._timeline + }; + this._timeline.add(event); + return id; + }; + /** + * Schedule a repeated event along the timeline. The event will fire + * at the `interval` starting at the `startTime` and for the specified + * `duration`. + * @param {Function} callback The callback to invoke. + * @param {Time} interval The duration between successive + * callbacks. + * @param {TimelinePosition=} startTime When along the timeline the events should + * start being invoked. + * @param {Time} [duration=Infinity] How long the event should repeat. + * @return {Number} The ID of the scheduled event. Use this to cancel + * the event. + * @example + * //a callback invoked every eighth note after the first measure + * Tone.Transport.scheduleRepeat(callback, "8n", "1m"); + */ + Tone.Transport.prototype.scheduleRepeat = function (callback, interval, startTime, duration) { + if (interval <= 0) { + throw new Error('Tone.Transport: repeat events must have an interval larger than 0'); + } + var event = { + 'time': this.toTicks(startTime), + 'duration': this.toTicks(this.defaultArg(duration, Infinity)), + 'interval': this.toTicks(interval), + 'callback': callback + }; + var id = this._eventID++; + this._scheduledEvents[id.toString()] = { + 'event': event, + 'timeline': this._repeatedEvents + }; + this._repeatedEvents.add(event); + return id; + }; + /** + * Schedule an event that will be removed after it is invoked. + * Note that if the given time is less than the current transport time, + * the event will be invoked immediately. + * @param {Function} callback The callback to invoke once. + * @param {TransportTime} time The time the callback should be invoked. + * @returns {Number} The ID of the scheduled event. + */ + Tone.Transport.prototype.scheduleOnce = function (callback, time) { + var id = this._eventID++; + var event = { + 'time': this.toTicks(time), + 'callback': callback, + 'id': id + }; + this._scheduledEvents[id.toString()] = { + 'event': event, + 'timeline': this._onceEvents + }; + this._onceEvents.add(event); + return id; + }; + /** + * Clear the passed in event id from the timeline + * @param {Number} eventId The id of the event. + * @returns {Tone.Transport} this + */ + Tone.Transport.prototype.clear = function (eventId) { + if (this._scheduledEvents.hasOwnProperty(eventId)) { + var item = this._scheduledEvents[eventId.toString()]; + item.timeline.remove(item.event); + delete this._scheduledEvents[eventId.toString()]; + } + return this; + }; + /** + * Remove scheduled events from the timeline after + * the given time. Repeated events will be removed + * if their startTime is after the given time + * @param {TransportTime} [after=0] Clear all events after + * this time. + * @returns {Tone.Transport} this + */ + Tone.Transport.prototype.cancel = function (after) { + after = this.defaultArg(after, 0); + after = this.toTicks(after); + this._timeline.cancel(after); + this._onceEvents.cancel(after); + this._repeatedEvents.cancel(after); + return this; + }; + /////////////////////////////////////////////////////////////////////////////// + // START/STOP/PAUSE + /////////////////////////////////////////////////////////////////////////////// + /** + * Bind start/stop/pause events from the clock and emit them. + */ + Tone.Transport.prototype._bindClockEvents = function () { + this._clock.on('start', function (time, offset) { + offset = Tone.Time(this._clock.ticks, 'i').toSeconds(); + this.emit('start', time, offset); + }.bind(this)); + this._clock.on('stop', function (time) { + this.emit('stop', time); + }.bind(this)); + this._clock.on('pause', function (time) { + this.emit('pause', time); + }.bind(this)); + }; + /** + * Returns the playback state of the source, either "started", "stopped", or "paused" + * @type {Tone.State} + * @readOnly + * @memberOf Tone.Transport# + * @name state + */ + Object.defineProperty(Tone.Transport.prototype, 'state', { + get: function () { + return this._clock.getStateAtTime(this.now()); + } + }); + /** + * Start the transport and all sources synced to the transport. + * @param {Time} [time=now] The time when the transport should start. + * @param {TransportTime=} offset The timeline offset to start the transport. + * @returns {Tone.Transport} this + * @example + * //start the transport in one second starting at beginning of the 5th measure. + * Tone.Transport.start("+1", "4:0:0"); + */ + Tone.Transport.prototype.start = function (time, offset) { + //start the clock + if (!this.isUndef(offset)) { + offset = this.toTicks(offset); + } + this._clock.start(time, offset); + return this; + }; + /** + * Stop the transport and all sources synced to the transport. + * @param {Time} [time=now] The time when the transport should stop. + * @returns {Tone.Transport} this + * @example + * Tone.Transport.stop(); + */ + Tone.Transport.prototype.stop = function (time) { + this._clock.stop(time); + return this; + }; + /** + * Pause the transport and all sources synced to the transport. + * @param {Time} [time=now] + * @returns {Tone.Transport} this + */ + Tone.Transport.prototype.pause = function (time) { + this._clock.pause(time); + return this; + }; + /////////////////////////////////////////////////////////////////////////////// + // SETTERS/GETTERS + /////////////////////////////////////////////////////////////////////////////// + /** + * The time signature as just the numerator over 4. + * For example 4/4 would be just 4 and 6/8 would be 3. + * @memberOf Tone.Transport# + * @type {Number|Array} + * @name timeSignature + * @example + * //common time + * Tone.Transport.timeSignature = 4; + * // 7/8 + * Tone.Transport.timeSignature = [7, 8]; + * //this will be reduced to a single number + * Tone.Transport.timeSignature; //returns 3.5 + */ + Object.defineProperty(Tone.Transport.prototype, 'timeSignature', { + get: function () { + return this._timeSignature; + }, + set: function (timeSig) { + if (this.isArray(timeSig)) { + timeSig = timeSig[0] / timeSig[1] * 4; + } + this._timeSignature = timeSig; + } + }); + /** + * When the Tone.Transport.loop = true, this is the starting position of the loop. + * @memberOf Tone.Transport# + * @type {TransportTime} + * @name loopStart + */ + Object.defineProperty(Tone.Transport.prototype, 'loopStart', { + get: function () { + return Tone.TransportTime(this._loopStart, 'i').toSeconds(); + }, + set: function (startPosition) { + this._loopStart = this.toTicks(startPosition); + } + }); + /** + * When the Tone.Transport.loop = true, this is the ending position of the loop. + * @memberOf Tone.Transport# + * @type {TransportTime} + * @name loopEnd + */ + Object.defineProperty(Tone.Transport.prototype, 'loopEnd', { + get: function () { + return Tone.TransportTime(this._loopEnd, 'i').toSeconds(); + }, + set: function (endPosition) { + this._loopEnd = this.toTicks(endPosition); + } + }); + /** + * Set the loop start and stop at the same time. + * @param {TransportTime} startPosition + * @param {TransportTime} endPosition + * @returns {Tone.Transport} this + * @example + * //loop over the first measure + * Tone.Transport.setLoopPoints(0, "1m"); + * Tone.Transport.loop = true; + */ + Tone.Transport.prototype.setLoopPoints = function (startPosition, endPosition) { + this.loopStart = startPosition; + this.loopEnd = endPosition; + return this; + }; + /** + * The swing value. Between 0-1 where 1 equal to + * the note + half the subdivision. + * @memberOf Tone.Transport# + * @type {NormalRange} + * @name swing + */ + Object.defineProperty(Tone.Transport.prototype, 'swing', { + get: function () { + return this._swingAmount; + }, + set: function (amount) { + //scale the values to a normal range + this._swingAmount = amount; + } + }); + /** + * Set the subdivision which the swing will be applied to. + * The default value is an 8th note. Value must be less + * than a quarter note. + * + * @memberOf Tone.Transport# + * @type {Time} + * @name swingSubdivision + */ + Object.defineProperty(Tone.Transport.prototype, 'swingSubdivision', { + get: function () { + return Tone.Time(this._swingTicks, 'i').toNotation(); + }, + set: function (subdivision) { + this._swingTicks = this.toTicks(subdivision); + } + }); + /** + * The Transport's position in Bars:Beats:Sixteenths. + * Setting the value will jump to that position right away. + * @memberOf Tone.Transport# + * @type {BarsBeatsSixteenths} + * @name position + */ + Object.defineProperty(Tone.Transport.prototype, 'position', { + get: function () { + return Tone.TransportTime(this.ticks, 'i').toBarsBeatsSixteenths(); + }, + set: function (progress) { + var ticks = this.toTicks(progress); + this.ticks = ticks; + } + }); + /** + * The Transport's position in seconds + * Setting the value will jump to that position right away. + * @memberOf Tone.Transport# + * @type {Seconds} + * @name seconds + */ + Object.defineProperty(Tone.Transport.prototype, 'seconds', { + get: function () { + return Tone.TransportTime(this.ticks, 'i').toSeconds(); + }, + set: function (progress) { + var ticks = this.toTicks(progress); + this.ticks = ticks; + } + }); + /** + * The Transport's loop position as a normalized value. Always + * returns 0 if the transport if loop is not true. + * @memberOf Tone.Transport# + * @name progress + * @type {NormalRange} + */ + Object.defineProperty(Tone.Transport.prototype, 'progress', { + get: function () { + if (this.loop) { + return (this.ticks - this._loopStart) / (this._loopEnd - this._loopStart); + } else { + return 0; + } + } + }); + /** + * The transports current tick position. + * + * @memberOf Tone.Transport# + * @type {Ticks} + * @name ticks + */ + Object.defineProperty(Tone.Transport.prototype, 'ticks', { + get: function () { + return this._clock.ticks; + }, + set: function (t) { + if (this._clock.ticks !== t) { + var now = this.now(); + //stop everything synced to the transport + if (this.state === Tone.State.Started) { + this.emit('stop', now); + this._clock.ticks = t; + //restart it with the new time + this.emit('start', now, this.seconds); + } else { + this._clock.ticks = t; + } + } + } + }); + /** + * Pulses Per Quarter note. This is the smallest resolution + * the Transport timing supports. This should be set once + * on initialization and not set again. Changing this value + * after other objects have been created can cause problems. + * + * @memberOf Tone.Transport# + * @type {Number} + * @name PPQ + */ + Object.defineProperty(Tone.Transport.prototype, 'PPQ', { + get: function () { + return this._ppq; + }, + set: function (ppq) { + var bpm = this.bpm.value; + this._ppq = ppq; + this.bpm.value = bpm; + } + }); + /** + * The hint to the type of playback. Affects tradeoffs between audio + * output latency and responsiveness. + * + * In addition to setting the value in seconds, the latencyHint also + * accepts the strings "interactive" (prioritizes low latency), + * "playback" (prioritizes sustained playback), "balanced" (balances + * latency and performance), and "fastest" (lowest latency, might glitch more often). + * @memberOf Tone.Transport# + * @type {Seconds|String} + * @name latencyHint + */ + Object.defineProperty(Tone.Transport.prototype, 'latencyHint', { + get: function () { + return Tone.Clock.latencyHint; + }, + set: function (hint) { + Tone.Clock.latencyHint = hint; + } + }); + /** + * Convert from BPM to frequency (factoring in PPQ) + * @param {BPM} bpm The BPM value to convert to frequency + * @return {Frequency} The BPM as a frequency with PPQ factored in. + * @private + */ + Tone.Transport.prototype._fromUnits = function (bpm) { + return 1 / (60 / bpm / this.PPQ); + }; + /** + * Convert from frequency (with PPQ) into BPM + * @param {Frequency} freq The clocks frequency to convert to BPM + * @return {BPM} The frequency value as BPM. + * @private + */ + Tone.Transport.prototype._toUnits = function (freq) { + return freq / this.PPQ * 60; + }; + /////////////////////////////////////////////////////////////////////////////// + // SYNCING + /////////////////////////////////////////////////////////////////////////////// + /** + * Returns the time aligned to the next subdivision + * of the Transport. If the Transport is not started, + * it will return 0. + * Note: this will not work precisely during tempo ramps. + * @param {Time} subdivision The subdivision to quantize to + * @return {Number} The context time of the next subdivision. + * @example + * Tone.Transport.start(); //the transport must be started + * Tone.Transport.nextSubdivision("4n"); + */ + Tone.Transport.prototype.nextSubdivision = function (subdivision) { + subdivision = this.toSeconds(subdivision); + //if the transport's not started, return 0 + var now; + if (this.state === Tone.State.Started) { + now = this._clock._nextTick; + } else { + return 0; + } + var transportPos = Tone.Time(this.ticks, 'i'); + var remainingTime = subdivision - transportPos % subdivision; + if (remainingTime === 0) { + remainingTime = subdivision; + } + return now + remainingTime; + }; + /** + * Attaches the signal to the tempo control signal so that + * any changes in the tempo will change the signal in the same + * ratio. + * + * @param {Tone.Signal} signal + * @param {number=} ratio Optionally pass in the ratio between + * the two signals. Otherwise it will be computed + * based on their current values. + * @returns {Tone.Transport} this + */ + Tone.Transport.prototype.syncSignal = function (signal, ratio) { + if (!ratio) { + //get the sync ratio + if (signal._param.value !== 0) { + ratio = signal._param.value / this.bpm._param.value; + } else { + ratio = 0; + } + } + var ratioSignal = new Tone.Gain(ratio); + this.bpm.chain(ratioSignal, signal._param); + this._syncedSignals.push({ + 'ratio': ratioSignal, + 'signal': signal, + 'initial': signal._param.value + }); + signal._param.value = 0; + return this; + }; + /** + * Unsyncs a previously synced signal from the transport's control. + * See Tone.Transport.syncSignal. + * @param {Tone.Signal} signal + * @returns {Tone.Transport} this + */ + Tone.Transport.prototype.unsyncSignal = function (signal) { + for (var i = this._syncedSignals.length - 1; i >= 0; i--) { + var syncedSignal = this._syncedSignals[i]; + if (syncedSignal.signal === signal) { + syncedSignal.ratio.dispose(); + syncedSignal.signal._param.value = syncedSignal.initial; + this._syncedSignals.splice(i, 1); + } + } + return this; + }; + /** + * Clean up. + * @returns {Tone.Transport} this + * @private + */ + Tone.Transport.prototype.dispose = function () { + Tone.Emitter.prototype.dispose.call(this); + this._clock.dispose(); + this._clock = null; + this._writable('bpm'); + this.bpm = null; + this._timeline.dispose(); + this._timeline = null; + this._onceEvents.dispose(); + this._onceEvents = null; + this._repeatedEvents.dispose(); + this._repeatedEvents = null; + return this; + }; + /////////////////////////////////////////////////////////////////////////////// + // INITIALIZATION + /////////////////////////////////////////////////////////////////////////////// + var TransportConstructor = Tone.Transport; + Tone.Transport = new TransportConstructor(); + Tone.Context.on('init', function (context) { + if (context.Transport instanceof TransportConstructor) { + Tone.Transport = context.Transport; + } else { + Tone.Transport = new TransportConstructor(); + //store the Transport on the context so it can be retrieved later + context.Transport = Tone.Transport; + } + }); + return Tone.Transport; + }); + Module(function (Tone) { + + /** + * @class Tone.Volume is a simple volume node, useful for creating a volume fader. + * + * @extends {Tone} + * @constructor + * @param {Decibels} [volume=0] the initial volume + * @example + * var vol = new Tone.Volume(-12); + * instrument.chain(vol, Tone.Master); + */ + Tone.Volume = function () { + var options = this.optionsObject(arguments, ['volume'], Tone.Volume.defaults); + /** + * the output node + * @type {GainNode} + * @private + */ + this.output = this.input = new Tone.Gain(options.volume, Tone.Type.Decibels); + /** + * The unmuted volume + * @type {Decibels} + * @private + */ + this._unmutedVolume = options.volume; + /** + * The volume control in decibels. + * @type {Decibels} + * @signal + */ + this.volume = this.output.gain; + this._readOnly('volume'); + //set the mute initially + this.mute = options.mute; + }; + Tone.extend(Tone.Volume); + /** + * Defaults + * @type {Object} + * @const + * @static + */ + Tone.Volume.defaults = { + 'volume': 0, + 'mute': false + }; + /** + * Mute the output. + * @memberOf Tone.Volume# + * @type {boolean} + * @name mute + * @example + * //mute the output + * volume.mute = true; + */ + Object.defineProperty(Tone.Volume.prototype, 'mute', { + get: function () { + return this.volume.value === -Infinity; + }, + set: function (mute) { + if (!this.mute && mute) { + this._unmutedVolume = this.volume.value; + //maybe it should ramp here? + this.volume.value = -Infinity; + } else if (this.mute && !mute) { + this.volume.value = this._unmutedVolume; + } + } + }); + /** + * clean up + * @returns {Tone.Volume} this + */ + Tone.Volume.prototype.dispose = function () { + this.input.dispose(); + Tone.prototype.dispose.call(this); + this._writable('volume'); + this.volume.dispose(); + this.volume = null; + return this; + }; + return Tone.Volume; + }); + Module(function (Tone) { + + /** + * @class A single master output which is connected to the + * AudioDestinationNode (aka your speakers). + * It provides useful conveniences such as the ability + * to set the volume and mute the entire application. + * It also gives you the ability to apply master effects to your application. + *

+ * Like Tone.Transport, A single Tone.Master is created + * on initialization and you do not need to explicitly construct one. + * + * @constructor + * @extends {Tone} + * @singleton + * @example + * //the audio will go from the oscillator to the speakers + * oscillator.connect(Tone.Master); + * //a convenience for connecting to the master output is also provided: + * oscillator.toMaster(); + * //the above two examples are equivalent. + */ + Tone.Master = function () { + this.createInsOuts(1, 1); + /** + * The private volume node + * @type {Tone.Volume} + * @private + */ + this._volume = this.output = new Tone.Volume(); + /** + * The volume of the master output. + * @type {Decibels} + * @signal + */ + this.volume = this._volume.volume; + this._readOnly('volume'); + //connections + this.input.chain(this.output, this.context.destination); + }; + Tone.extend(Tone.Master); + /** + * @type {Object} + * @const + */ + Tone.Master.defaults = { + 'volume': 0, + 'mute': false + }; + /** + * Mute the output. + * @memberOf Tone.Master# + * @type {boolean} + * @name mute + * @example + * //mute the output + * Tone.Master.mute = true; + */ + Object.defineProperty(Tone.Master.prototype, 'mute', { + get: function () { + return this._volume.mute; + }, + set: function (mute) { + this._volume.mute = mute; + } + }); + /** + * Add a master effects chain. NOTE: this will disconnect any nodes which were previously + * chained in the master effects chain. + * @param {AudioNode|Tone...} args All arguments will be connected in a row + * and the Master will be routed through it. + * @return {Tone.Master} this + * @example + * //some overall compression to keep the levels in check + * var masterCompressor = new Tone.Compressor({ + * "threshold" : -6, + * "ratio" : 3, + * "attack" : 0.5, + * "release" : 0.1 + * }); + * //give a little boost to the lows + * var lowBump = new Tone.Filter(200, "lowshelf"); + * //route everything through the filter + * //and compressor before going to the speakers + * Tone.Master.chain(lowBump, masterCompressor); + */ + Tone.Master.prototype.chain = function () { + this.input.disconnect(); + this.input.chain.apply(this.input, arguments); + arguments[arguments.length - 1].connect(this.output); + }; + /** + * Clean up + * @return {Tone.Master} this + */ + Tone.Master.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable('volume'); + this._volume.dispose(); + this._volume = null; + this.volume = null; + }; + /////////////////////////////////////////////////////////////////////////// + // AUGMENT TONE's PROTOTYPE + /////////////////////////////////////////////////////////////////////////// + /** + * Connect 'this' to the master output. Shorthand for this.connect(Tone.Master) + * @returns {Tone} this + * @example + * //connect an oscillator to the master output + * var osc = new Tone.Oscillator().toMaster(); + */ + Tone.prototype.toMaster = function () { + this.connect(Tone.Master); + return this; + }; + /** + * Also augment AudioNode's prototype to include toMaster + * as a convenience + * @returns {AudioNode} this + */ + AudioNode.prototype.toMaster = function () { + this.connect(Tone.Master); + return this; + }; + /** + * initialize the module and listen for new audio contexts + */ + var MasterConstructor = Tone.Master; + Tone.Master = new MasterConstructor(); + Tone.Context.on('init', function (context) { + // if it already exists, just restore it + if (context.Master instanceof MasterConstructor) { + Tone.Master = context.Master; + } else { + Tone.Master = new MasterConstructor(); + } + context.Master = Tone.Master; + }); + return Tone.Master; + }); + Module(function (Tone) { + + /** + * @class Base class for sources. Sources have start/stop methods + * and the ability to be synced to the + * start/stop of Tone.Transport. + * + * @constructor + * @extends {Tone} + * @example + * //Multiple state change events can be chained together, + * //but must be set in the correct order and with ascending times + * + * // OK + * state.start().stop("+0.2"); + * // AND + * state.start().stop("+0.2").start("+0.4").stop("+0.7") + * + * // BAD + * state.stop("+0.2").start(); + * // OR + * state.start("+0.3").stop("+0.2"); + * + */ + Tone.Source = function (options) { + // this.createInsOuts(0, 1); + options = this.defaultArg(options, Tone.Source.defaults); + /** + * The output volume node + * @type {Tone.Volume} + * @private + */ + this._volume = this.output = new Tone.Volume(options.volume); + /** + * The volume of the output in decibels. + * @type {Decibels} + * @signal + * @example + * source.volume.value = -6; + */ + this.volume = this._volume.volume; + this._readOnly('volume'); + /** + * Keep track of the scheduled state. + * @type {Tone.TimelineState} + * @private + */ + this._state = new Tone.TimelineState(Tone.State.Stopped); + this._state.memory = 10; + /** + * The synced `start` callback function from the transport + * @type {Function} + * @private + */ + this._synced = false; + /** + * Keep track of all of the scheduled event ids + * @type {Array} + * @private + */ + this._scheduled = []; + //make the output explicitly stereo + this._volume.output.output.channelCount = 2; + this._volume.output.output.channelCountMode = 'explicit'; + //mute initially + this.mute = options.mute; + }; + Tone.extend(Tone.Source); + /** + * The default parameters + * @static + * @const + * @type {Object} + */ + Tone.Source.defaults = { + 'volume': 0, + 'mute': false + }; + /** + * Returns the playback state of the source, either "started" or "stopped". + * @type {Tone.State} + * @readOnly + * @memberOf Tone.Source# + * @name state + */ + Object.defineProperty(Tone.Source.prototype, 'state', { + get: function () { + if (this._synced) { + if (Tone.Transport.state === Tone.State.Started) { + return this._state.getValueAtTime(Tone.Transport.seconds); + } else { + return Tone.State.Stopped; + } + } else { + return this._state.getValueAtTime(this.now()); + } + } + }); + /** + * Mute the output. + * @memberOf Tone.Source# + * @type {boolean} + * @name mute + * @example + * //mute the output + * source.mute = true; + */ + Object.defineProperty(Tone.Source.prototype, 'mute', { + get: function () { + return this._volume.mute; + }, + set: function (mute) { + this._volume.mute = mute; + } + }); + //overwrite these functions + Tone.Source.prototype._start = Tone.noOp; + Tone.Source.prototype._stop = Tone.noOp; + /** + * Start the source at the specified time. If no time is given, + * start the source now. + * @param {Time} [time=now] When the source should be started. + * @returns {Tone.Source} this + * @example + * source.start("+0.5"); //starts the source 0.5 seconds from now + */ + Tone.Source.prototype.start = function (time, offset, duration) { + if (this.isUndef(time) && this._synced) { + time = Tone.Transport.seconds; + } else { + time = this.toSeconds(time); + } + //if it's started, stop it and restart it + if (!this.retrigger && this._state.getValueAtTime(time) === Tone.State.Started) { + this.stop(time); + } + this._state.setStateAtTime(Tone.State.Started, time); + if (this._synced) { + // add the offset time to the event + var event = this._state.get(time); + event.offset = this.defaultArg(offset, 0); + event.duration = duration; + var sched = Tone.Transport.schedule(function (t) { + this._start(t, offset, duration); + }.bind(this), time); + this._scheduled.push(sched); + } else { + this._start.apply(this, arguments); + } + return this; + }; + /** + * Stop the source at the specified time. If no time is given, + * stop the source now. + * @param {Time} [time=now] When the source should be stopped. + * @returns {Tone.Source} this + * @example + * source.stop(); // stops the source immediately + */ + Tone.Source.prototype.stop = function (time) { + if (this.isUndef(time) && this._synced) { + time = Tone.Transport.seconds; + } else { + time = this.toSeconds(time); + } + this._state.cancel(time); + this._state.setStateAtTime(Tone.State.Stopped, time); + if (!this._synced) { + this._stop.apply(this, arguments); + } else { + var sched = Tone.Transport.schedule(this._stop.bind(this), time); + this._scheduled.push(sched); + } + return this; + }; + /** + * Sync the source to the Transport so that all subsequent + * calls to `start` and `stop` are synced to the TransportTime + * instead of the AudioContext time. + * + * @returns {Tone.Source} this + * @example + * //sync the source so that it plays between 0 and 0.3 on the Transport's timeline + * source.sync().start(0).stop(0.3); + * //start the transport. + * Tone.Transport.start(); + * + * @example + * //start the transport with an offset and the sync'ed sources + * //will start in the correct position + * source.sync().start(0.1); + * //the source will be invoked with an offset of 0.4 + * Tone.Transport.start("+0.5", 0.5); + */ + Tone.Source.prototype.sync = function () { + this._synced = true; + Tone.Transport.on('start loopStart', function (time, offset) { + if (offset > 0) { + // get the playback state at that time + var stateEvent = this._state.get(offset); + // listen for start events which may occur in the middle of the sync'ed time + if (stateEvent && stateEvent.state === Tone.State.Started && stateEvent.time !== offset) { + // get the offset + var startOffset = offset - this.toSeconds(stateEvent.time); + var duration; + if (stateEvent.duration) { + duration = this.toSeconds(stateEvent.duration) - startOffset; + } + this._start(time, this.toSeconds(stateEvent.offset) + startOffset, duration); + } + } + }.bind(this)); + Tone.Transport.on('stop pause loopEnd', function (time) { + if (this._state.getValueAtTime(Tone.Transport.seconds) === Tone.State.Started) { + this._stop(time); + } + }.bind(this)); + return this; + }; + /** + * Unsync the source to the Transport. See Tone.Source.sync + * @returns {Tone.Source} this + */ + Tone.Source.prototype.unsync = function () { + this._synced = false; + Tone.Transport.off('start stop pause loopEnd loopStart'); + // clear all of the scheduled ids + for (var i = 0; i < this._scheduled.length; i++) { + var id = this._scheduled[i]; + Tone.Transport.clear(id); + } + this._scheduled = []; + this._state.cancel(0); + return this; + }; + /** + * Clean up. + * @return {Tone.Source} this + */ + Tone.Source.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this.unsync(); + this._scheduled = null; + this._writable('volume'); + this._volume.dispose(); + this._volume = null; + this.volume = null; + this._state.dispose(); + this._state = null; + }; + return Tone.Source; + }); + Module(function (Tone) { + + /** + * OscillatorNode shim + * @private + */ + if (window.OscillatorNode && !OscillatorNode.prototype.start) { + OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; + OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; + if (!OscillatorNode.prototype.setPeriodicWave) { + OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; + } + if (!AudioContext.prototype.createPeriodicWave) { + AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; + } + } + /** + * @class Tone.Oscillator supports a number of features including + * phase rotation, multiple oscillator types (see Tone.Oscillator.type), + * and Transport syncing (see Tone.Oscillator.syncFrequency). + * + * @constructor + * @extends {Tone.Source} + * @param {Frequency} [frequency] Starting frequency + * @param {string} [type] The oscillator type. Read more about type below. + * @example + * //make and start a 440hz sine tone + * var osc = new Tone.Oscillator(440, "sine").toMaster().start(); + */ + Tone.Oscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'type' + ], Tone.Oscillator.defaults); + Tone.Source.call(this, options); + /** + * the main oscillator + * @type {OscillatorNode} + * @private + */ + this._oscillator = null; + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The detune control signal. + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + /** + * the periodic wave + * @type {PeriodicWave} + * @private + */ + this._wave = null; + /** + * The partials of the oscillator + * @type {Array} + * @private + */ + this._partials = this.defaultArg(options.partials, [1]); + /** + * the phase of the oscillator + * between 0 - 360 + * @type {number} + * @private + */ + this._phase = options.phase; + /** + * the type of the oscillator + * @type {string} + * @private + */ + this._type = null; + //setup + this.type = options.type; + this.phase = this._phase; + this._readOnly([ + 'frequency', + 'detune' + ]); + }; + Tone.extend(Tone.Oscillator, Tone.Source); + /** + * the default parameters + * @type {Object} + */ + Tone.Oscillator.defaults = { + 'type': 'sine', + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'partials': [] + }; + /** + * The Oscillator types + * @enum {String} + */ + Tone.Oscillator.Type = { + Sine: 'sine', + Triangle: 'triangle', + Sawtooth: 'sawtooth', + Square: 'square', + Custom: 'custom' + }; + /** + * start the oscillator + * @param {Time} [time=now] + * @private + */ + Tone.Oscillator.prototype._start = function (time) { + //new oscillator with previous values + this._oscillator = this.context.createOscillator(); + this._oscillator.setPeriodicWave(this._wave); + //connect the control signal to the oscillator frequency & detune + this._oscillator.connect(this.output); + this.frequency.connect(this._oscillator.frequency); + this.detune.connect(this._oscillator.detune); + //start the oscillator + this._oscillator.start(this.toSeconds(time)); + }; + /** + * stop the oscillator + * @private + * @param {Time} [time=now] (optional) timing parameter + * @returns {Tone.Oscillator} this + */ + Tone.Oscillator.prototype._stop = function (time) { + if (this._oscillator) { + this._oscillator.stop(this.toSeconds(time)); + this._oscillator = null; + } + return this; + }; + /** + * Sync the signal to the Transport's bpm. Any changes to the transports bpm, + * will also affect the oscillators frequency. + * @returns {Tone.Oscillator} this + * @example + * Tone.Transport.bpm.value = 120; + * osc.frequency.value = 440; + * //the ration between the bpm and the frequency will be maintained + * osc.syncFrequency(); + * Tone.Transport.bpm.value = 240; + * // the frequency of the oscillator is doubled to 880 + */ + Tone.Oscillator.prototype.syncFrequency = function () { + Tone.Transport.syncSignal(this.frequency); + return this; + }; + /** + * Unsync the oscillator's frequency from the Transport. + * See Tone.Oscillator.syncFrequency + * @returns {Tone.Oscillator} this + */ + Tone.Oscillator.prototype.unsyncFrequency = function () { + Tone.Transport.unsyncSignal(this.frequency); + return this; + }; + /** + * The type of the oscillator: either sine, square, triangle, or sawtooth. Also capable of + * setting the first x number of partials of the oscillator. For example: "sine4" would + * set be the first 4 partials of the sine wave and "triangle8" would set the first + * 8 partials of the triangle wave. + *

+ * Uses PeriodicWave internally even for native types so that it can set the phase. + * PeriodicWave equations are from the + * [Webkit Web Audio implementation](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium). + * + * @memberOf Tone.Oscillator# + * @type {string} + * @name type + * @example + * //set it to a square wave + * osc.type = "square"; + * @example + * //set the first 6 partials of a sawtooth wave + * osc.type = "sawtooth6"; + */ + Object.defineProperty(Tone.Oscillator.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + var coefs = this._getRealImaginary(type, this._phase); + var periodicWave = this.context.createPeriodicWave(coefs[0], coefs[1]); + this._wave = periodicWave; + if (this._oscillator !== null) { + this._oscillator.setPeriodicWave(this._wave); + } + this._type = type; + } + }); + /** + * Returns the real and imaginary components based + * on the oscillator type. + * @returns {Array} [real, imaginary] + * @private + */ + Tone.Oscillator.prototype._getRealImaginary = function (type, phase) { + var fftSize = 4096; + var periodicWaveSize = fftSize / 2; + var real = new Float32Array(periodicWaveSize); + var imag = new Float32Array(periodicWaveSize); + var partialCount = 1; + if (type === Tone.Oscillator.Type.Custom) { + partialCount = this._partials.length + 1; + periodicWaveSize = partialCount; + } else { + var partial = /^(sine|triangle|square|sawtooth)(\d+)$/.exec(type); + if (partial) { + partialCount = parseInt(partial[2]) + 1; + type = partial[1]; + partialCount = Math.max(partialCount, 2); + periodicWaveSize = partialCount; + } + } + for (var n = 1; n < periodicWaveSize; ++n) { + var piFactor = 2 / (n * Math.PI); + var b; + switch (type) { + case Tone.Oscillator.Type.Sine: + b = n <= partialCount ? 1 : 0; + break; + case Tone.Oscillator.Type.Square: + b = n & 1 ? 2 * piFactor : 0; + break; + case Tone.Oscillator.Type.Sawtooth: + b = piFactor * (n & 1 ? 1 : -1); + break; + case Tone.Oscillator.Type.Triangle: + if (n & 1) { + b = 2 * (piFactor * piFactor) * (n - 1 >> 1 & 1 ? -1 : 1); + } else { + b = 0; + } + break; + case Tone.Oscillator.Type.Custom: + b = this._partials[n - 1]; + break; + default: + throw new TypeError('Tone.Oscillator: invalid type: ' + type); + } + if (b !== 0) { + real[n] = -b * Math.sin(phase * n); + imag[n] = b * Math.cos(phase * n); + } else { + real[n] = 0; + imag[n] = 0; + } + } + return [ + real, + imag + ]; + }; + /** + * Compute the inverse FFT for a given phase. + * @param {Float32Array} real + * @param {Float32Array} imag + * @param {NormalRange} phase + * @return {AudioRange} + * @private + */ + Tone.Oscillator.prototype._inverseFFT = function (real, imag, phase) { + var sum = 0; + var len = real.length; + for (var i = 0; i < len; i++) { + sum += real[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase); + } + return sum; + }; + /** + * Returns the initial value of the oscillator. + * @return {AudioRange} + * @private + */ + Tone.Oscillator.prototype._getInitialValue = function () { + var coefs = this._getRealImaginary(this._type, 0); + var real = coefs[0]; + var imag = coefs[1]; + var maxValue = 0; + var twoPi = Math.PI * 2; + //check for peaks in 8 places + for (var i = 0; i < 8; i++) { + maxValue = Math.max(this._inverseFFT(real, imag, i / 8 * twoPi), maxValue); + } + return -this._inverseFFT(real, imag, this._phase) / maxValue; + }; + /** + * The partials of the waveform. A partial represents + * the amplitude at a harmonic. The first harmonic is the + * fundamental frequency, the second is the octave and so on + * following the harmonic series. + * Setting this value will automatically set the type to "custom". + * The value is an empty array when the type is not "custom". + * @memberOf Tone.Oscillator# + * @type {Array} + * @name partials + * @example + * osc.partials = [1, 0.2, 0.01]; + */ + Object.defineProperty(Tone.Oscillator.prototype, 'partials', { + get: function () { + if (this._type !== Tone.Oscillator.Type.Custom) { + return []; + } else { + return this._partials; + } + }, + set: function (partials) { + this._partials = partials; + this.type = Tone.Oscillator.Type.Custom; + } + }); + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.Oscillator# + * @type {Degrees} + * @name phase + * @example + * osc.phase = 180; //flips the phase of the oscillator + */ + Object.defineProperty(Tone.Oscillator.prototype, 'phase', { + get: function () { + return this._phase * (180 / Math.PI); + }, + set: function (phase) { + this._phase = phase * Math.PI / 180; + //reset the type + this.type = this._type; + } + }); + /** + * Dispose and disconnect. + * @return {Tone.Oscillator} this + */ + Tone.Oscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + if (this._oscillator !== null) { + this._oscillator.disconnect(); + this._oscillator = null; + } + this._wave = null; + this._writable([ + 'frequency', + 'detune' + ]); + this.frequency.dispose(); + this.frequency = null; + this.detune.dispose(); + this.detune = null; + this._partials = null; + return this; + }; + return Tone.Oscillator; + }); + Module(function (Tone) { + /** + * @class Tone.Zero outputs 0's at audio-rate. The reason this has to be + * it's own class is that many browsers optimize out Tone.Signal + * with a value of 0 and will not process nodes further down the graph. + * @extends {Tone} + */ + Tone.Zero = function () { + /** + * The gain node + * @type {Tone.Gain} + * @private + */ + this._gain = this.input = this.output = new Tone.Gain(); + this.context.getConstant(0).connect(this._gain); + }; + Tone.extend(Tone.Zero); + /** + * clean up + * @return {Tone.Zero} this + */ + Tone.Zero.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._gain.dispose(); + this._gain = null; + return this; + }; + return Tone.Zero; + }); + Module(function (Tone) { + + /** + * @class LFO stands for low frequency oscillator. Tone.LFO produces an output signal + * which can be attached to an AudioParam or Tone.Signal + * in order to modulate that parameter with an oscillator. The LFO can + * also be synced to the transport to start/stop and change when the tempo changes. + * + * @constructor + * @extends {Tone.Oscillator} + * @param {Frequency|Object} [frequency] The frequency of the oscillation. Typically, LFOs will be + * in the frequency range of 0.1 to 10 hertz. + * @param {number=} min The minimum output value of the LFO. + * @param {number=} max The maximum value of the LFO. + * @example + * var lfo = new Tone.LFO("4n", 400, 4000); + * lfo.connect(filter.frequency); + */ + Tone.LFO = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'min', + 'max' + ], Tone.LFO.defaults); + /** + * The oscillator. + * @type {Tone.Oscillator} + * @private + */ + this._oscillator = new Tone.Oscillator({ + 'frequency': options.frequency, + 'type': options.type + }); + /** + * the lfo's frequency + * @type {Frequency} + * @signal + */ + this.frequency = this._oscillator.frequency; + /** + * The amplitude of the LFO, which controls the output range between + * the min and max output. For example if the min is -10 and the max + * is 10, setting the amplitude to 0.5 would make the LFO modulate + * between -5 and 5. + * @type {Number} + * @signal + */ + this.amplitude = this._oscillator.volume; + this.amplitude.units = Tone.Type.NormalRange; + this.amplitude.value = options.amplitude; + /** + * The signal which is output when the LFO is stopped + * @type {Tone.Signal} + * @private + */ + this._stoppedSignal = new Tone.Signal(0, Tone.Type.AudioRange); + /** + * Just outputs zeros. + * @type {Tone.Zero} + * @private + */ + this._zeros = new Tone.Zero(); + /** + * The value that the LFO outputs when it's stopped + * @type {AudioRange} + * @private + */ + this._stoppedValue = 0; + /** + * @type {Tone.AudioToGain} + * @private + */ + this._a2g = new Tone.AudioToGain(); + /** + * @type {Tone.Scale} + * @private + */ + this._scaler = this.output = new Tone.Scale(options.min, options.max); + /** + * the units of the LFO (used for converting) + * @type {Tone.Type} + * @private + */ + this._units = Tone.Type.Default; + this.units = options.units; + //connect it up + this._oscillator.chain(this._a2g, this._scaler); + this._zeros.connect(this._a2g); + this._stoppedSignal.connect(this._a2g); + this._readOnly([ + 'amplitude', + 'frequency' + ]); + this.phase = options.phase; + }; + Tone.extend(Tone.LFO, Tone.Oscillator); + /** + * the default parameters + * + * @static + * @const + * @type {Object} + */ + Tone.LFO.defaults = { + 'type': 'sine', + 'min': 0, + 'max': 1, + 'phase': 0, + 'frequency': '4n', + 'amplitude': 1, + 'units': Tone.Type.Default + }; + /** + * Start the LFO. + * @param {Time} [time=now] the time the LFO will start + * @returns {Tone.LFO} this + */ + Tone.LFO.prototype.start = function (time) { + time = this.toSeconds(time); + this._stoppedSignal.setValueAtTime(0, time); + this._oscillator.start(time); + return this; + }; + /** + * Stop the LFO. + * @param {Time} [time=now] the time the LFO will stop + * @returns {Tone.LFO} this + */ + Tone.LFO.prototype.stop = function (time) { + time = this.toSeconds(time); + this._stoppedSignal.setValueAtTime(this._stoppedValue, time); + this._oscillator.stop(time); + return this; + }; + /** + * Sync the start/stop/pause to the transport + * and the frequency to the bpm of the transport + * @returns {Tone.LFO} this + * @example + * lfo.frequency.value = "8n"; + * lfo.sync().start(0) + * //the rate of the LFO will always be an eighth note, + * //even as the tempo changes + */ + Tone.LFO.prototype.sync = function () { + this._oscillator.sync(); + this._oscillator.syncFrequency(); + return this; + }; + /** + * unsync the LFO from transport control + * @returns {Tone.LFO} this + */ + Tone.LFO.prototype.unsync = function () { + this._oscillator.unsync(); + this._oscillator.unsyncFrequency(); + return this; + }; + /** + * The miniumum output of the LFO. + * @memberOf Tone.LFO# + * @type {number} + * @name min + */ + Object.defineProperty(Tone.LFO.prototype, 'min', { + get: function () { + return this._toUnits(this._scaler.min); + }, + set: function (min) { + min = this._fromUnits(min); + this._scaler.min = min; + } + }); + /** + * The maximum output of the LFO. + * @memberOf Tone.LFO# + * @type {number} + * @name max + */ + Object.defineProperty(Tone.LFO.prototype, 'max', { + get: function () { + return this._toUnits(this._scaler.max); + }, + set: function (max) { + max = this._fromUnits(max); + this._scaler.max = max; + } + }); + /** + * The type of the oscillator: sine, square, sawtooth, triangle. + * @memberOf Tone.LFO# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.LFO.prototype, 'type', { + get: function () { + return this._oscillator.type; + }, + set: function (type) { + this._oscillator.type = type; + this._stoppedValue = this._oscillator._getInitialValue(); + this._stoppedSignal.value = this._stoppedValue; + } + }); + /** + * The phase of the LFO. + * @memberOf Tone.LFO# + * @type {number} + * @name phase + */ + Object.defineProperty(Tone.LFO.prototype, 'phase', { + get: function () { + return this._oscillator.phase; + }, + set: function (phase) { + this._oscillator.phase = phase; + this._stoppedValue = this._oscillator._getInitialValue(); + this._stoppedSignal.value = this._stoppedValue; + } + }); + /** + * The output units of the LFO. + * @memberOf Tone.LFO# + * @type {Tone.Type} + * @name units + */ + Object.defineProperty(Tone.LFO.prototype, 'units', { + get: function () { + return this._units; + }, + set: function (val) { + var currentMin = this.min; + var currentMax = this.max; + //convert the min and the max + this._units = val; + this.min = currentMin; + this.max = currentMax; + } + }); + /** + * Mute the output. + * @memberOf Tone.LFO# + * @type {Boolean} + * @name mute + */ + Object.defineProperty(Tone.LFO.prototype, 'mute', { + get: function () { + return this._oscillator.mute; + }, + set: function (mute) { + this._oscillator.mute = mute; + } + }); + /** + * Returns the playback state of the source, either "started" or "stopped". + * @type {Tone.State} + * @readOnly + * @memberOf Tone.LFO# + * @name state + */ + Object.defineProperty(Tone.LFO.prototype, 'state', { + get: function () { + return this._oscillator.state; + } + }); + /** + * Connect the output of the LFO to an AudioParam, AudioNode, or Tone Node. + * Tone.LFO will automatically convert to the destination units of the + * will get the units from the connected node. + * @param {Tone | AudioParam | AudioNode} node + * @param {number} [outputNum=0] optionally which output to connect from + * @param {number} [inputNum=0] optionally which input to connect to + * @returns {Tone.LFO} this + * @private + */ + Tone.LFO.prototype.connect = function (node) { + if (node.constructor === Tone.Signal || node.constructor === Tone.Param || node.constructor === Tone.TimelineSignal) { + this.convert = node.convert; + this.units = node.units; + } + Tone.Signal.prototype.connect.apply(this, arguments); + return this; + }; + /** + * private method borrowed from Param converts + * units from their destination value + * @function + * @private + */ + Tone.LFO.prototype._fromUnits = Tone.Param.prototype._fromUnits; + /** + * private method borrowed from Param converts + * units to their destination value + * @function + * @private + */ + Tone.LFO.prototype._toUnits = Tone.Param.prototype._toUnits; + /** + * disconnect and dispose + * @returns {Tone.LFO} this + */ + Tone.LFO.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'amplitude', + 'frequency' + ]); + this._oscillator.dispose(); + this._oscillator = null; + this._stoppedSignal.dispose(); + this._stoppedSignal = null; + this._zeros.dispose(); + this._zeros = null; + this._scaler.dispose(); + this._scaler = null; + this._a2g.dispose(); + this._a2g = null; + this.frequency = null; + this.amplitude = null; + return this; + }; + return Tone.LFO; + }); + Module(function (Tone) { + + /** + * @class Tone.Limiter will limit the loudness of an incoming signal. + * It is composed of a Tone.Compressor with a fast attack + * and release. Limiters are commonly used to safeguard against + * signal clipping. Unlike a compressor, limiters do not provide + * smooth gain reduction and almost completely prevent + * additional gain above the threshold. + * + * @extends {Tone} + * @constructor + * @param {number} threshold The theshold above which the limiting is applied. + * @example + * var limiter = new Tone.Limiter(-6); + */ + Tone.Limiter = function () { + var options = this.optionsObject(arguments, ['threshold'], Tone.Limiter.defaults); + /** + * the compressor + * @private + * @type {Tone.Compressor} + */ + this._compressor = this.input = this.output = new Tone.Compressor({ + 'attack': 0.001, + 'decay': 0.001, + 'threshold': options.threshold + }); + /** + * The threshold of of the limiter + * @type {Decibel} + * @signal + */ + this.threshold = this._compressor.threshold; + this._readOnly('threshold'); + }; + Tone.extend(Tone.Limiter); + /** + * The default value + * @type {Object} + * @const + * @static + */ + Tone.Limiter.defaults = { 'threshold': -12 }; + /** + * Clean up. + * @returns {Tone.Limiter} this + */ + Tone.Limiter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._compressor.dispose(); + this._compressor = null; + this._writable('threshold'); + this.threshold = null; + return this; + }; + return Tone.Limiter; + }); + Module(function (Tone) { + + /** + * @class Tone.Lowpass is a lowpass feedback comb filter. It is similar to + * Tone.FeedbackCombFilter, but includes a lowpass filter. + * + * @extends {Tone} + * @constructor + * @param {Time|Object} [delayTime] The delay time of the comb filter + * @param {NormalRange=} resonance The resonance (feedback) of the comb filter + * @param {Frequency=} dampening The cutoff of the lowpass filter dampens the + * signal as it is fedback. + */ + Tone.LowpassCombFilter = function () { + this.createInsOuts(1, 1); + var options = this.optionsObject(arguments, [ + 'delayTime', + 'resonance', + 'dampening' + ], Tone.LowpassCombFilter.defaults); + /** + * the delay node + * @type {DelayNode} + * @private + */ + this._delay = this.input = new Tone.Delay(options.delayTime); + /** + * The delayTime of the comb filter. + * @type {Time} + * @signal + */ + this.delayTime = this._delay.delayTime; + /** + * the lowpass filter + * @type {BiquadFilterNode} + * @private + */ + this._lowpass = this.output = this.context.createBiquadFilter(); + this._lowpass.Q.value = -3.0102999566398125; + this._lowpass.type = 'lowpass'; + /** + * The dampening control of the feedback + * @type {Frequency} + * @signal + */ + this.dampening = new Tone.Param({ + 'param': this._lowpass.frequency, + 'units': Tone.Type.Frequency, + 'value': options.dampening + }); + /** + * the feedback gain + * @type {Tone.Gain} + * @private + */ + this._feedback = new Tone.Gain(options.resonance, Tone.Type.NormalRange); + /** + * The amount of feedback of the delayed signal. + * @type {NormalRange} + * @signal + */ + this.resonance = this._feedback.gain; + //connections + this._delay.chain(this._lowpass, this._feedback, this._delay); + this._readOnly([ + 'dampening', + 'resonance', + 'delayTime' + ]); + }; + Tone.extend(Tone.LowpassCombFilter); + /** + * the default parameters + * @static + * @const + * @type {Object} + */ + Tone.LowpassCombFilter.defaults = { + 'delayTime': 0.1, + 'resonance': 0.5, + 'dampening': 3000 + }; + /** + * Clean up. + * @returns {Tone.LowpassCombFilter} this + */ + Tone.LowpassCombFilter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'dampening', + 'resonance', + 'delayTime' + ]); + this.dampening.dispose(); + this.dampening = null; + this.resonance.dispose(); + this.resonance = null; + this._delay.dispose(); + this._delay = null; + this.delayTime = null; + this._lowpass.disconnect(); + this._lowpass = null; + this._feedback.disconnect(); + this._feedback = null; + return this; + }; + return Tone.LowpassCombFilter; + }); + Module(function (Tone) { + + /** + * @class Tone.Merge brings two signals into the left and right + * channels of a single stereo channel. + * + * @constructor + * @extends {Tone} + * @example + * var merge = new Tone.Merge().toMaster(); + * //routing a sine tone in the left channel + * //and noise in the right channel + * var osc = new Tone.Oscillator().connect(merge.left); + * var noise = new Tone.Noise().connect(merge.right); + * //starting our oscillators + * noise.start(); + * osc.start(); + */ + Tone.Merge = function () { + this.createInsOuts(2, 0); + /** + * The left input channel. + * Alias for input[0] + * @type {GainNode} + */ + this.left = this.input[0] = new Tone.Gain(); + /** + * The right input channel. + * Alias for input[1]. + * @type {GainNode} + */ + this.right = this.input[1] = new Tone.Gain(); + /** + * the merger node for the two channels + * @type {ChannelMergerNode} + * @private + */ + this._merger = this.output = this.context.createChannelMerger(2); + //connections + this.left.connect(this._merger, 0, 0); + this.right.connect(this._merger, 0, 1); + this.left.channelCount = 1; + this.right.channelCount = 1; + this.left.channelCountMode = 'explicit'; + this.right.channelCountMode = 'explicit'; + }; + Tone.extend(Tone.Merge); + /** + * Clean up. + * @returns {Tone.Merge} this + */ + Tone.Merge.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this.left.dispose(); + this.left = null; + this.right.dispose(); + this.right = null; + this._merger.disconnect(); + this._merger = null; + return this; + }; + return Tone.Merge; + }); + Module(function (Tone) { + + /** + * @class Tone.Meter gets the [RMS](https://en.wikipedia.org/wiki/Root_mean_square) + * of an input signal with some averaging applied. It can also get the raw + * value of the input signal. + * + * @constructor + * @extends {Tone} + * @param {String} type Either "level" or "signal". + * @param {Number} smoothing The amount of smoothing applied between frames. + * @example + * var meter = new Tone.Meter(); + * var mic = new Tone.UserMedia().start(); + * //connect mic to the meter + * mic.connect(meter); + * //the current level of the mic input + * var level = meter.value; + */ + Tone.Meter = function () { + var options = this.optionsObject(arguments, [ + 'type', + 'smoothing' + ], Tone.Meter.defaults); + /** + * The type of the meter, either "level" or "signal". + * A "level" meter will return the volume level (rms) of the + * input signal and a "signal" meter will return + * the signal value of the input. + * @type {String} + */ + this.type = options.type; + /** + * The analyser node which computes the levels. + * @private + * @type {Tone.Analyser} + */ + this.input = this.output = this._analyser = new Tone.Analyser('waveform', 512); + this._analyser.returnType = 'float'; + /** + * The amount of carryover between the current and last frame. + * Only applied meter for "level" type. + * @type {Number} + */ + this.smoothing = options.smoothing; + /** + * The last computed value + * @type {Number} + * @private + */ + this._lastValue = 0; + }; + Tone.extend(Tone.Meter); + /** + * @private + * @enum {String} + */ + Tone.Meter.Type = { + Level: 'level', + Signal: 'signal' + }; + /** + * The defaults + * @type {Object} + * @static + * @const + */ + Tone.Meter.defaults = { + 'smoothing': 0.8, + 'type': Tone.Meter.Type.Level + }; + /** + * The current value of the meter. A value of 1 is + * "unity". + * @memberOf Tone.Meter# + * @type {Number} + * @name value + * @readOnly + */ + Object.defineProperty(Tone.Meter.prototype, 'value', { + get: function () { + var signal = this._analyser.analyse(); + if (this.type === Tone.Meter.Type.Level) { + //rms + var sum = 0; + for (var i = 0; i < signal.length; i++) { + sum += Math.pow(signal[i], 2); + } + var rms = Math.sqrt(sum / signal.length); + //smooth it + rms = Math.max(rms, this._lastValue * this.smoothing); + this._lastValue = rms; + //scale it + var unity = 0.35; + var val = rms / unity; + //scale the output curve + return Math.sqrt(val); + } else { + return signal[0]; + } + } + }); + /** + * Clean up. + * @returns {Tone.Meter} this + */ + Tone.Meter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._analyser.dispose(); + this._analyser = null; + return this; + }; + return Tone.Meter; + }); + Module(function (Tone) { + + /** + * @class Tone.Split splits an incoming signal into left and right channels. + * + * @constructor + * @extends {Tone} + * @example + * var split = new Tone.Split(); + * stereoSignal.connect(split); + */ + Tone.Split = function () { + this.createInsOuts(0, 2); + /** + * @type {ChannelSplitterNode} + * @private + */ + this._splitter = this.input = this.context.createChannelSplitter(2); + /** + * Left channel output. + * Alias for output[0] + * @type {Tone.Gain} + */ + this.left = this.output[0] = new Tone.Gain(); + /** + * Right channel output. + * Alias for output[1] + * @type {Tone.Gain} + */ + this.right = this.output[1] = new Tone.Gain(); + //connections + this._splitter.connect(this.left, 0, 0); + this._splitter.connect(this.right, 1, 0); + }; + Tone.extend(Tone.Split); + /** + * Clean up. + * @returns {Tone.Split} this + */ + Tone.Split.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._splitter.disconnect(); + this.left.dispose(); + this.left = null; + this.right.dispose(); + this.right = null; + this._splitter = null; + return this; + }; + return Tone.Split; + }); + Module(function (Tone) { + + /** + * @class Mid/Side processing separates the the 'mid' signal + * (which comes out of both the left and the right channel) + * and the 'side' (which only comes out of the the side channels).

+ * + * Mid = (Left+Right)/sqrt(2); // obtain mid-signal from left and right
+ * Side = (Left-Right)/sqrt(2); // obtain side-signal from left and righ
+ *
+ * + * @extends {Tone} + * @constructor + */ + Tone.MidSideSplit = function () { + this.createInsOuts(0, 2); + /** + * split the incoming signal into left and right channels + * @type {Tone.Split} + * @private + */ + this._split = this.input = new Tone.Split(); + /** + * The mid send. Connect to mid processing. Alias for + * output[0] + * @type {Tone.Expr} + */ + this.mid = this.output[0] = new Tone.Expr('($0 + $1) * $2'); + /** + * The side output. Connect to side processing. Alias for + * output[1] + * @type {Tone.Expr} + */ + this.side = this.output[1] = new Tone.Expr('($0 - $1) * $2'); + this._split.connect(this.mid, 0, 0); + this._split.connect(this.mid, 1, 1); + this._split.connect(this.side, 0, 0); + this._split.connect(this.side, 1, 1); + this.context.getConstant(Math.SQRT1_2).connect(this.mid, 0, 2); + this.context.getConstant(Math.SQRT1_2).connect(this.side, 0, 2); + }; + Tone.extend(Tone.MidSideSplit); + /** + * clean up + * @returns {Tone.MidSideSplit} this + */ + Tone.MidSideSplit.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this.mid.dispose(); + this.mid = null; + this.side.dispose(); + this.side = null; + this._split.dispose(); + this._split = null; + return this; + }; + return Tone.MidSideSplit; + }); + Module(function (Tone) { + + /** + * @class Mid/Side processing separates the the 'mid' signal + * (which comes out of both the left and the right channel) + * and the 'side' (which only comes out of the the side channels). + * MidSideMerge merges the mid and side signal after they've been seperated + * by Tone.MidSideSplit.

+ * + * Left = (Mid+Side)/sqrt(2); // obtain left signal from mid and side
+ * Right = (Mid-Side)/sqrt(2); // obtain right signal from mid and side
+ *
+ * + * @extends {Tone.StereoEffect} + * @constructor + */ + Tone.MidSideMerge = function () { + this.createInsOuts(2, 0); + /** + * The mid signal input. Alias for + * input[0] + * @type {Tone.Gain} + */ + this.mid = this.input[0] = new Tone.Gain(); + /** + * recombine the mid/side into Left + * @type {Tone.Expr} + * @private + */ + this._left = new Tone.Expr('($0 + $1) * $2'); + /** + * The side signal input. Alias for + * input[1] + * @type {Tone.Gain} + */ + this.side = this.input[1] = new Tone.Gain(); + /** + * recombine the mid/side into Right + * @type {Tone.Expr} + * @private + */ + this._right = new Tone.Expr('($0 - $1) * $2'); + /** + * Merge the left/right signal back into a stereo signal. + * @type {Tone.Merge} + * @private + */ + this._merge = this.output = new Tone.Merge(); + this.mid.connect(this._left, 0, 0); + this.side.connect(this._left, 0, 1); + this.mid.connect(this._right, 0, 0); + this.side.connect(this._right, 0, 1); + this._left.connect(this._merge, 0, 0); + this._right.connect(this._merge, 0, 1); + this.context.getConstant(Math.SQRT1_2).connect(this._left, 0, 2); + this.context.getConstant(Math.SQRT1_2).connect(this._right, 0, 2); + }; + Tone.extend(Tone.MidSideMerge); + /** + * clean up + * @returns {Tone.MidSideMerge} this + */ + Tone.MidSideMerge.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this.mid.dispose(); + this.mid = null; + this.side.dispose(); + this.side = null; + this._left.dispose(); + this._left = null; + this._right.dispose(); + this._right = null; + this._merge.dispose(); + this._merge = null; + return this; + }; + return Tone.MidSideMerge; + }); + Module(function (Tone) { + + /** + * @class Tone.MidSideCompressor applies two different compressors to the mid + * and side signal components. See Tone.MidSideSplit. + * + * @extends {Tone} + * @param {Object} options The options that are passed to the mid and side + * compressors. + * @constructor + */ + Tone.MidSideCompressor = function (options) { + options = this.defaultArg(options, Tone.MidSideCompressor.defaults); + /** + * the mid/side split + * @type {Tone.MidSideSplit} + * @private + */ + this._midSideSplit = this.input = new Tone.MidSideSplit(); + /** + * the mid/side recombination + * @type {Tone.MidSideMerge} + * @private + */ + this._midSideMerge = this.output = new Tone.MidSideMerge(); + /** + * The compressor applied to the mid signal + * @type {Tone.Compressor} + */ + this.mid = new Tone.Compressor(options.mid); + /** + * The compressor applied to the side signal + * @type {Tone.Compressor} + */ + this.side = new Tone.Compressor(options.side); + this._midSideSplit.mid.chain(this.mid, this._midSideMerge.mid); + this._midSideSplit.side.chain(this.side, this._midSideMerge.side); + this._readOnly([ + 'mid', + 'side' + ]); + }; + Tone.extend(Tone.MidSideCompressor); + /** + * @const + * @static + * @type {Object} + */ + Tone.MidSideCompressor.defaults = { + 'mid': { + 'ratio': 3, + 'threshold': -24, + 'release': 0.03, + 'attack': 0.02, + 'knee': 16 + }, + 'side': { + 'ratio': 6, + 'threshold': -30, + 'release': 0.25, + 'attack': 0.03, + 'knee': 10 + } + }; + /** + * Clean up. + * @returns {Tone.MidSideCompressor} this + */ + Tone.MidSideCompressor.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'mid', + 'side' + ]); + this.mid.dispose(); + this.mid = null; + this.side.dispose(); + this.side = null; + this._midSideSplit.dispose(); + this._midSideSplit = null; + this._midSideMerge.dispose(); + this._midSideMerge = null; + return this; + }; + return Tone.MidSideCompressor; + }); + Module(function (Tone) { + + /** + * @class Tone.Mono coerces the incoming mono or stereo signal into a mono signal + * where both left and right channels have the same value. This can be useful + * for [stereo imaging](https://en.wikipedia.org/wiki/Stereo_imaging). + * + * @extends {Tone} + * @constructor + */ + Tone.Mono = function () { + this.createInsOuts(1, 0); + /** + * merge the signal + * @type {Tone.Merge} + * @private + */ + this._merge = this.output = new Tone.Merge(); + this.input.connect(this._merge, 0, 0); + this.input.connect(this._merge, 0, 1); + this.input.gain.value = this.dbToGain(-10); + }; + Tone.extend(Tone.Mono); + /** + * clean up + * @returns {Tone.Mono} this + */ + Tone.Mono.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._merge.dispose(); + this._merge = null; + return this; + }; + return Tone.Mono; + }); + Module(function (Tone) { + + /** + * @class A compressor with seperate controls over low/mid/high dynamics + * + * @extends {Tone} + * @constructor + * @param {Object} options The low/mid/high compressor settings. + * @example + * var multiband = new Tone.MultibandCompressor({ + * "lowFrequency" : 200, + * "highFrequency" : 1300 + * "low" : { + * "threshold" : -12 + * } + * }) + */ + Tone.MultibandCompressor = function (options) { + options = this.defaultArg(arguments, Tone.MultibandCompressor.defaults); + /** + * split the incoming signal into high/mid/low + * @type {Tone.MultibandSplit} + * @private + */ + this._splitter = this.input = new Tone.MultibandSplit({ + 'lowFrequency': options.lowFrequency, + 'highFrequency': options.highFrequency + }); + /** + * low/mid crossover frequency. + * @type {Frequency} + * @signal + */ + this.lowFrequency = this._splitter.lowFrequency; + /** + * mid/high crossover frequency. + * @type {Frequency} + * @signal + */ + this.highFrequency = this._splitter.highFrequency; + /** + * the output + * @type {Tone.Gain} + * @private + */ + this.output = new Tone.Gain(); + /** + * The compressor applied to the low frequencies. + * @type {Tone.Compressor} + */ + this.low = new Tone.Compressor(options.low); + /** + * The compressor applied to the mid frequencies. + * @type {Tone.Compressor} + */ + this.mid = new Tone.Compressor(options.mid); + /** + * The compressor applied to the high frequencies. + * @type {Tone.Compressor} + */ + this.high = new Tone.Compressor(options.high); + //connect the compressor + this._splitter.low.chain(this.low, this.output); + this._splitter.mid.chain(this.mid, this.output); + this._splitter.high.chain(this.high, this.output); + this._readOnly([ + 'high', + 'mid', + 'low', + 'highFrequency', + 'lowFrequency' + ]); + }; + Tone.extend(Tone.MultibandCompressor); + /** + * @const + * @static + * @type {Object} + */ + Tone.MultibandCompressor.defaults = { + 'low': Tone.Compressor.defaults, + 'mid': Tone.Compressor.defaults, + 'high': Tone.Compressor.defaults, + 'lowFrequency': 250, + 'highFrequency': 2000 + }; + /** + * clean up + * @returns {Tone.MultibandCompressor} this + */ + Tone.MultibandCompressor.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._splitter.dispose(); + this._writable([ + 'high', + 'mid', + 'low', + 'highFrequency', + 'lowFrequency' + ]); + this.low.dispose(); + this.mid.dispose(); + this.high.dispose(); + this._splitter = null; + this.low = null; + this.mid = null; + this.high = null; + this.lowFrequency = null; + this.highFrequency = null; + return this; + }; + return Tone.MultibandCompressor; + }); + Module(function (Tone) { + + /** + * @class Tone.Panner is an equal power Left/Right Panner and does not + * support 3D. Panner uses the StereoPannerNode when available. + * + * @constructor + * @extends {Tone} + * @param {NormalRange} [initialPan=0] The initail panner value (defaults to 0 = center) + * @example + * //pan the input signal hard right. + * var panner = new Tone.Panner(1); + */ + Tone.Panner = function (initialPan) { + if (this._hasStereoPanner) { + /** + * the panner node + * @type {StereoPannerNode} + * @private + */ + this._panner = this.input = this.output = this.context.createStereoPanner(); + /** + * The pan control. -1 = hard left, 1 = hard right. + * @type {NormalRange} + * @signal + */ + this.pan = this._panner.pan; + } else { + /** + * the dry/wet knob + * @type {Tone.CrossFade} + * @private + */ + this._crossFade = new Tone.CrossFade(); + /** + * @type {Tone.Merge} + * @private + */ + this._merger = this.output = new Tone.Merge(); + /** + * @type {Tone.Split} + * @private + */ + this._splitter = this.input = new Tone.Split(); + /** + * The pan control. -1 = hard left, 1 = hard right. + * @type {AudioRange} + * @signal + */ + this.pan = new Tone.Signal(0, Tone.Type.AudioRange); + /** + * always sends 0 + * @type {Tone.Zero} + * @private + */ + this._zero = new Tone.Zero(); + /** + * The analog to gain conversion + * @type {Tone.AudioToGain} + * @private + */ + this._a2g = new Tone.AudioToGain(); + //CONNECTIONS: + this._zero.connect(this._a2g); + this.pan.chain(this._a2g, this._crossFade.fade); + //left channel is a, right channel is b + this._splitter.connect(this._crossFade, 0, 0); + this._splitter.connect(this._crossFade, 1, 1); + //merge it back together + this._crossFade.a.connect(this._merger, 0, 0); + this._crossFade.b.connect(this._merger, 0, 1); + } + //initial value + this.pan.value = this.defaultArg(initialPan, 0); + this._readOnly('pan'); + }; + Tone.extend(Tone.Panner); + /** + * indicates if the panner is using the new StereoPannerNode internally + * @type {boolean} + * @private + */ + Tone.Panner.prototype._hasStereoPanner = Tone.prototype.isFunction(Tone.context.createStereoPanner); + /** + * Clean up. + * @returns {Tone.Panner} this + */ + Tone.Panner.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable('pan'); + if (this._hasStereoPanner) { + this._panner.disconnect(); + this._panner = null; + this.pan = null; + } else { + this._zero.dispose(); + this._zero = null; + this._crossFade.dispose(); + this._crossFade = null; + this._splitter.dispose(); + this._splitter = null; + this._merger.dispose(); + this._merger = null; + this.pan.dispose(); + this.pan = null; + this._a2g.dispose(); + this._a2g = null; + } + return this; + }; + return Tone.Panner; + }); + Module(function (Tone) { + + /** + * @class A spatialized panner node which supports equalpower or HRTF panning. + * Tries to normalize the API across various browsers. See Tone.Listener + * + * @constructor + * @extends {Tone} + * @param {Number} positionX The initial x position. + * @param {Number} positionY The initial y position. + * @param {Number} positionZ The initial z position. + */ + Tone.Panner3D = function () { + var options = this.optionsObject(arguments, [ + 'positionX', + 'positionY', + 'positionZ' + ], Tone.Panner3D.defaults); + /** + * The panner node + * @type {PannerNode} + * @private + */ + this._panner = this.input = this.output = this.context.createPanner(); + //set some values + this._panner.panningModel = options.panningModel; + this._panner.maxDistance = options.maxDistance; + this._panner.distanceModel = options.distanceModel; + this._panner.coneOuterGain = options.coneOuterGain; + this._panner.coneOuterAngle = options.coneOuterAngle; + this._panner.coneInnerAngle = options.coneInnerAngle; + this._panner.refDistance = options.refDistance; + this._panner.rolloffFactor = options.rolloffFactor; + /** + * Holds the current orientation + * @type {Array} + * @private + */ + this._orientation = [ + options.orientationX, + options.orientationY, + options.orientationZ + ]; + /** + * Holds the current position + * @type {Array} + * @private + */ + this._position = [ + options.positionX, + options.positionY, + options.positionZ + ]; + // set the default position/orientation + this.orientationX = options.orientationX; + this.orientationY = options.orientationY; + this.orientationZ = options.orientationZ; + this.positionX = options.positionX; + this.positionY = options.positionY; + this.positionZ = options.positionZ; + }; + Tone.extend(Tone.Panner3D); + /** + * the default parameters + * @static + * @const + * @type {Object} + * Defaults according to the specification + */ + Tone.Panner3D.defaults = { + 'positionX': 0, + 'positionY': 0, + 'positionZ': 0, + 'orientationX': 0, + 'orientationY': 0, + 'orientationZ': 0, + 'panningModel': 'equalpower', + 'maxDistance': 10000, + 'distanceModel': 'inverse', + 'coneOuterGain': 0, + 'coneOuterAngle': 360, + 'coneInnerAngle': 360, + 'refDistance': 1, + 'rolloffFactor': 1 + }; + /** + * The ramp time which is applied to the setTargetAtTime + * @type {Number} + * @private + */ + Tone.Panner3D.prototype._rampTimeConstant = 0.01; + /** + * Sets the position of the source in 3d space. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @return {Tone.Panner3D} this + */ + Tone.Panner3D.prototype.setPosition = function (x, y, z) { + if (this._panner.positionX) { + var now = this.now(); + this._panner.positionX.setTargetAtTime(x, now, this._rampTimeConstant); + this._panner.positionY.setTargetAtTime(y, now, this._rampTimeConstant); + this._panner.positionZ.setTargetAtTime(z, now, this._rampTimeConstant); + } else { + this._panner.setPosition(x, y, z); + } + this._position = Array.prototype.slice.call(arguments); + return this; + }; + /** + * Sets the orientation of the source in 3d space. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @return {Tone.Panner3D} this + */ + Tone.Panner3D.prototype.setOrientation = function (x, y, z) { + if (this._panner.orientationX) { + var now = this.now(); + this._panner.orientationX.setTargetAtTime(x, now, this._rampTimeConstant); + this._panner.orientationY.setTargetAtTime(y, now, this._rampTimeConstant); + this._panner.orientationZ.setTargetAtTime(z, now, this._rampTimeConstant); + } else { + this._panner.setOrientation(x, y, z); + } + this._orientation = Array.prototype.slice.call(arguments); + return this; + }; + /** + * The x position of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name positionX + */ + Object.defineProperty(Tone.Panner3D.prototype, 'positionX', { + set: function (pos) { + this._position[0] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[0]; + } + }); + /** + * The y position of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name positionY + */ + Object.defineProperty(Tone.Panner3D.prototype, 'positionY', { + set: function (pos) { + this._position[1] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[1]; + } + }); + /** + * The z position of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name positionZ + */ + Object.defineProperty(Tone.Panner3D.prototype, 'positionZ', { + set: function (pos) { + this._position[2] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[2]; + } + }); + /** + * The x orientation of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name orientationX + */ + Object.defineProperty(Tone.Panner3D.prototype, 'orientationX', { + set: function (pos) { + this._orientation[0] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[0]; + } + }); + /** + * The y orientation of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name orientationY + */ + Object.defineProperty(Tone.Panner3D.prototype, 'orientationY', { + set: function (pos) { + this._orientation[1] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[1]; + } + }); + /** + * The z orientation of the panner object. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name orientationZ + */ + Object.defineProperty(Tone.Panner3D.prototype, 'orientationZ', { + set: function (pos) { + this._orientation[2] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[2]; + } + }); + /** + * Proxy a property on the panner to an exposed public propery + * @param {String} prop + * @private + */ + Tone.Panner3D._aliasProperty = function (prop) { + Object.defineProperty(Tone.Panner3D.prototype, prop, { + set: function (val) { + this._panner[prop] = val; + }, + get: function () { + return this._panner[prop]; + } + }); + }; + /** + * The panning model. Either "equalpower" or "HRTF". + * @type {String} + * @memberOf Tone.Panner3D# + * @name panningModel + */ + Tone.Panner3D._aliasProperty('panningModel'); + /** + * A reference distance for reducing volume as source move further from the listener + * @type {Number} + * @memberOf Tone.Panner3D# + * @name refDistance + */ + Tone.Panner3D._aliasProperty('refDistance'); + /** + * Describes how quickly the volume is reduced as source moves away from listener. + * @type {Number} + * @memberOf Tone.Panner3D# + * @name rolloffFactor + */ + Tone.Panner3D._aliasProperty('rolloffFactor'); + /** + * The distance model used by, "linear", "inverse", or "exponential". + * @type {String} + * @memberOf Tone.Panner3D# + * @name distanceModel + */ + Tone.Panner3D._aliasProperty('distanceModel'); + /** + * The angle, in degrees, inside of which there will be no volume reduction + * @type {Degrees} + * @memberOf Tone.Panner3D# + * @name coneInnerAngle + */ + Tone.Panner3D._aliasProperty('coneInnerAngle'); + /** + * The angle, in degrees, outside of which the volume will be reduced + * to a constant value of coneOuterGain + * @type {Degrees} + * @memberOf Tone.Panner3D# + * @name coneOuterAngle + */ + Tone.Panner3D._aliasProperty('coneOuterAngle'); + /** + * The gain outside of the coneOuterAngle + * @type {Gain} + * @memberOf Tone.Panner3D# + * @name coneOuterGain + */ + Tone.Panner3D._aliasProperty('coneOuterGain'); + /** + * The maximum distance between source and listener, + * after which the volume will not be reduced any further. + * @type {Positive} + * @memberOf Tone.Panner3D# + * @name maxDistance + */ + Tone.Panner3D._aliasProperty('maxDistance'); + /** + * Clean up. + * @returns {Tone.Panner3D} this + */ + Tone.Panner3D.prototype.dispose = function () { + this._panner.disconnect(); + this._panner = null; + this._orientation = null; + this._position = null; + return this; + }; + return Tone.Panner3D; + }); + Module(function (Tone) { + + /** + * @class Tone.PanVol is a Tone.Panner and Tone.Volume in one. + * + * @extends {Tone} + * @constructor + * @param {AudioRange} pan the initial pan + * @param {number} volume The output volume. + * @example + * //pan the incoming signal left and drop the volume + * var panVol = new Tone.PanVol(0.25, -12); + */ + Tone.PanVol = function () { + var options = this.optionsObject(arguments, [ + 'pan', + 'volume' + ], Tone.PanVol.defaults); + /** + * The panning node + * @type {Tone.Panner} + * @private + */ + this._panner = this.input = new Tone.Panner(options.pan); + /** + * The L/R panning control. + * @type {AudioRange} + * @signal + */ + this.pan = this._panner.pan; + /** + * The volume node + * @type {Tone.Volume} + */ + this._volume = this.output = new Tone.Volume(options.volume); + /** + * The volume control in decibels. + * @type {Decibels} + * @signal + */ + this.volume = this._volume.volume; + //connections + this._panner.connect(this._volume); + this._readOnly([ + 'pan', + 'volume' + ]); + }; + Tone.extend(Tone.PanVol); + /** + * The defaults + * @type {Object} + * @const + * @static + */ + Tone.PanVol.defaults = { + 'pan': 0.5, + 'volume': 0 + }; + /** + * clean up + * @returns {Tone.PanVol} this + */ + Tone.PanVol.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable([ + 'pan', + 'volume' + ]); + this._panner.dispose(); + this._panner = null; + this.pan = null; + this._volume.dispose(); + this._volume = null; + this.volume = null; + return this; + }; + return Tone.PanVol; + }); + Module(function (Tone) { + + /** + * @class Tone.CtrlInterpolate will interpolate between given values based + * on the "index" property. Passing in an array or object literal + * will interpolate each of the parameters. Note (i.e. "C3") + * and Time (i.e. "4n + 2") can be interpolated. All other values are + * assumed to be numbers. + * @example + * var interp = new Tone.CtrlInterpolate([0, 2, 9, 4]); + * interp.index = 0.75; + * interp.value; //returns 1.5 + * + * @example + * var interp = new Tone.CtrlInterpolate([ + * [2, 4, 5], + * [9, 3, 2], + * ]); + * @param {Array} values The array of values to interpolate over + * @param {Positive} index The initial interpolation index. + * @extends {Tone} + */ + Tone.CtrlInterpolate = function () { + var options = this.optionsObject(arguments, [ + 'values', + 'index' + ], Tone.CtrlInterpolate.defaults); + /** + * The values to interpolate between + * @type {Array} + */ + this.values = options.values; + /** + * The interpolated index between values. For example: a value of 1.5 + * would interpolate equally between the value at index 1 + * and the value at index 2. + * @example + * interp.index = 0; + * interp.value; //returns the value at 0 + * interp.index = 0.5; + * interp.value; //returns the value between indices 0 and 1. + * @type {Positive} + */ + this.index = options.index; + }; + Tone.extend(Tone.CtrlInterpolate); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.CtrlInterpolate.defaults = { + 'index': 0, + 'values': [] + }; + /** + * The current interpolated value based on the index + * @readOnly + * @memberOf Tone.CtrlInterpolate# + * @type {*} + * @name value + */ + Object.defineProperty(Tone.CtrlInterpolate.prototype, 'value', { + get: function () { + var index = this.index; + index = Math.min(index, this.values.length - 1); + var lowerPosition = Math.floor(index); + var lower = this.values[lowerPosition]; + var upper = this.values[Math.ceil(index)]; + return this._interpolate(index - lowerPosition, lower, upper); + } + }); + /** + * Internal interpolation routine + * @param {NormalRange} index The index between the lower and upper + * @param {*} lower + * @param {*} upper + * @return {*} The interpolated value + * @private + */ + Tone.CtrlInterpolate.prototype._interpolate = function (index, lower, upper) { + if (this.isArray(lower)) { + var retArray = []; + for (var i = 0; i < lower.length; i++) { + retArray[i] = this._interpolate(index, lower[i], upper[i]); + } + return retArray; + } else if (this.isObject(lower)) { + var retObj = {}; + for (var attr in lower) { + retObj[attr] = this._interpolate(index, lower[attr], upper[attr]); + } + return retObj; + } else { + lower = this._toNumber(lower); + upper = this._toNumber(upper); + return (1 - index) * lower + index * upper; + } + }; + /** + * Convert from the given type into a number + * @param {Number|String} value + * @return {Number} + * @private + */ + Tone.CtrlInterpolate.prototype._toNumber = function (val) { + if (this.isNumber(val)) { + return val; + } else { + //otherwise assume that it's Time... + return this.toSeconds(val); + } + }; + /** + * Clean up + * @return {Tone.CtrlInterpolate} this + */ + Tone.CtrlInterpolate.prototype.dispose = function () { + this.values = null; + }; + return Tone.CtrlInterpolate; + }); + Module(function (Tone) { + + /** + * @class Tone.CtrlMarkov represents a Markov Chain where each call + * to Tone.CtrlMarkov.next will move to the next state. If the next + * state choice is an array, the next state is chosen randomly with + * even probability for all of the choices. For a weighted probability + * of the next choices, pass in an object with "state" and "probability" attributes. + * The probabilities will be normalized and then chosen. If no next options + * are given for the current state, the state will stay there. + * @extends {Tone} + * @example + * var chain = new Tone.CtrlMarkov({ + * "beginning" : ["end", "middle"], + * "middle" : "end" + * }); + * chain.value = "beginning"; + * chain.next(); //returns "end" or "middle" with 50% probability + * + * @example + * var chain = new Tone.CtrlMarkov({ + * "beginning" : [{"value" : "end", "probability" : 0.8}, + * {"value" : "middle", "probability" : 0.2}], + * "middle" : "end" + * }); + * chain.value = "beginning"; + * chain.next(); //returns "end" with 80% probability or "middle" with 20%. + * @param {Object} values An object with the state names as the keys + * and the next state(s) as the values. + */ + Tone.CtrlMarkov = function (values, initial) { + /** + * The Markov values with states as the keys + * and next state(s) as the values. + * @type {Object} + */ + this.values = this.defaultArg(values, {}); + /** + * The current state of the Markov values. The next + * state will be evaluated and returned when Tone.CtrlMarkov.next + * is invoked. + * @type {String} + */ + this.value = this.defaultArg(initial, Object.keys(this.values)[0]); + }; + Tone.extend(Tone.CtrlMarkov); + /** + * Returns the next state of the Markov values. + * @return {String} + */ + Tone.CtrlMarkov.prototype.next = function () { + if (this.values.hasOwnProperty(this.value)) { + var next = this.values[this.value]; + if (this.isArray(next)) { + var distribution = this._getProbDistribution(next); + var rand = Math.random(); + var total = 0; + for (var i = 0; i < distribution.length; i++) { + var dist = distribution[i]; + if (rand > total && rand < total + dist) { + var chosen = next[i]; + if (this.isObject(chosen)) { + this.value = chosen.value; + } else { + this.value = chosen; + } + } + total += dist; + } + } else { + this.value = next; + } + } + return this.value; + }; + /** + * Choose randomly from an array weighted options in the form + * {"state" : string, "probability" : number} or an array of values + * @param {Array} options + * @return {Array} The randomly selected choice + * @private + */ + Tone.CtrlMarkov.prototype._getProbDistribution = function (options) { + var distribution = []; + var total = 0; + var needsNormalizing = false; + for (var i = 0; i < options.length; i++) { + var option = options[i]; + if (this.isObject(option)) { + needsNormalizing = true; + distribution[i] = option.probability; + } else { + distribution[i] = 1 / options.length; + } + total += distribution[i]; + } + if (needsNormalizing) { + //normalize the values + for (var j = 0; j < distribution.length; j++) { + distribution[j] = distribution[j] / total; + } + } + return distribution; + }; + /** + * Clean up + * @return {Tone.CtrlMarkov} this + */ + Tone.CtrlMarkov.prototype.dispose = function () { + this.values = null; + }; + return Tone.CtrlMarkov; + }); + Module(function (Tone) { + + /** + * @class Generate patterns from an array of values. + * Has a number of arpeggiation and randomized + * selection patterns. + *
    + *
  • "up" - cycles upward
  • + *
  • "down" - cycles downward
  • + *
  • "upDown" - up then and down
  • + *
  • "downUp" - cycles down then and up
  • + *
  • "alternateUp" - jump up two and down one
  • + *
  • "alternateDown" - jump down two and up one
  • + *
  • "random" - randomly select an index
  • + *
  • "randomWalk" - randomly moves one index away from the current position
  • + *
  • "randomOnce" - randomly select an index without repeating until all values have been chosen.
  • + *
+ * @param {Array} values An array of options to choose from. + * @param {Tone.CtrlPattern.Type=} type The name of the pattern. + * @extends {Tone} + */ + Tone.CtrlPattern = function () { + var options = this.optionsObject(arguments, [ + 'values', + 'type' + ], Tone.CtrlPattern.defaults); + /** + * The array of values to arpeggiate over + * @type {Array} + */ + this.values = options.values; + /** + * The current position in the values array + * @type {Number} + */ + this.index = 0; + /** + * The type placeholder + * @type {Tone.CtrlPattern.Type} + * @private + */ + this._type = null; + /** + * Shuffled values for the RandomOnce type + * @type {Array} + * @private + */ + this._shuffled = null; + /** + * The direction of the movement + * @type {String} + * @private + */ + this._direction = null; + this.type = options.type; + }; + Tone.extend(Tone.CtrlPattern); + /** + * The Control Patterns + * @type {Object} + * @static + */ + Tone.CtrlPattern.Type = { + Up: 'up', + Down: 'down', + UpDown: 'upDown', + DownUp: 'downUp', + AlternateUp: 'alternateUp', + AlternateDown: 'alternateDown', + Random: 'random', + RandomWalk: 'randomWalk', + RandomOnce: 'randomOnce' + }; + /** + * The default values. + * @type {Object} + */ + Tone.CtrlPattern.defaults = { + 'type': Tone.CtrlPattern.Type.Up, + 'values': [] + }; + /** + * The value at the current index of the pattern. + * @readOnly + * @memberOf Tone.CtrlPattern# + * @type {*} + * @name value + */ + Object.defineProperty(Tone.CtrlPattern.prototype, 'value', { + get: function () { + //some safeguards + if (this.values.length === 0) { + return; + } else if (this.values.length === 1) { + return this.values[0]; + } + this.index = Math.min(this.index, this.values.length - 1); + var val = this.values[this.index]; + if (this.type === Tone.CtrlPattern.Type.RandomOnce) { + if (this.values.length !== this._shuffled.length) { + this._shuffleValues(); + } + val = this.values[this._shuffled[this.index]]; + } + return val; + } + }); + /** + * The pattern used to select the next + * item from the values array + * @memberOf Tone.CtrlPattern# + * @type {Tone.CtrlPattern.Type} + * @name type + */ + Object.defineProperty(Tone.CtrlPattern.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + this._type = type; + this._shuffled = null; + //the first index + if (this._type === Tone.CtrlPattern.Type.Up || this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.RandomOnce || this._type === Tone.CtrlPattern.Type.AlternateUp) { + this.index = 0; + } else if (this._type === Tone.CtrlPattern.Type.Down || this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { + this.index = this.values.length - 1; + } + //the direction + if (this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.AlternateUp) { + this._direction = Tone.CtrlPattern.Type.Up; + } else if (this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { + this._direction = Tone.CtrlPattern.Type.Down; + } + //randoms + if (this._type === Tone.CtrlPattern.Type.RandomOnce) { + this._shuffleValues(); + } else if (this._type === Tone.CtrlPattern.Random) { + this.index = Math.floor(Math.random() * this.values.length); + } + } + }); + /** + * Return the next value given the current position + * and pattern. + * @return {*} The next value + */ + Tone.CtrlPattern.prototype.next = function () { + var type = this.type; + //choose the next index + if (type === Tone.CtrlPattern.Type.Up) { + this.index++; + if (this.index >= this.values.length) { + this.index = 0; + } + } else if (type === Tone.CtrlPattern.Type.Down) { + this.index--; + if (this.index < 0) { + this.index = this.values.length - 1; + } + } else if (type === Tone.CtrlPattern.Type.UpDown || type === Tone.CtrlPattern.Type.DownUp) { + if (this._direction === Tone.CtrlPattern.Type.Up) { + this.index++; + } else { + this.index--; + } + if (this.index < 0) { + this.index = 1; + this._direction = Tone.CtrlPattern.Type.Up; + } else if (this.index >= this.values.length) { + this.index = this.values.length - 2; + this._direction = Tone.CtrlPattern.Type.Down; + } + } else if (type === Tone.CtrlPattern.Type.Random) { + this.index = Math.floor(Math.random() * this.values.length); + } else if (type === Tone.CtrlPattern.Type.RandomWalk) { + if (Math.random() < 0.5) { + this.index--; + this.index = Math.max(this.index, 0); + } else { + this.index++; + this.index = Math.min(this.index, this.values.length - 1); + } + } else if (type === Tone.CtrlPattern.Type.RandomOnce) { + this.index++; + if (this.index >= this.values.length) { + this.index = 0; + //reshuffle the values for next time + this._shuffleValues(); + } + } else if (type === Tone.CtrlPattern.Type.AlternateUp) { + if (this._direction === Tone.CtrlPattern.Type.Up) { + this.index += 2; + this._direction = Tone.CtrlPattern.Type.Down; + } else { + this.index -= 1; + this._direction = Tone.CtrlPattern.Type.Up; + } + if (this.index >= this.values.length) { + this.index = 0; + this._direction = Tone.CtrlPattern.Type.Up; + } + } else if (type === Tone.CtrlPattern.Type.AlternateDown) { + if (this._direction === Tone.CtrlPattern.Type.Up) { + this.index += 1; + this._direction = Tone.CtrlPattern.Type.Down; + } else { + this.index -= 2; + this._direction = Tone.CtrlPattern.Type.Up; + } + if (this.index < 0) { + this.index = this.values.length - 1; + this._direction = Tone.CtrlPattern.Type.Down; + } + } + return this.value; + }; + /** + * Shuffles the values and places the results into the _shuffled + * @private + */ + Tone.CtrlPattern.prototype._shuffleValues = function () { + var copy = []; + this._shuffled = []; + for (var i = 0; i < this.values.length; i++) { + copy[i] = i; + } + while (copy.length > 0) { + var randVal = copy.splice(Math.floor(copy.length * Math.random()), 1); + this._shuffled.push(randVal[0]); + } + }; + /** + * Clean up + * @returns {Tone.CtrlPattern} this + */ + Tone.CtrlPattern.prototype.dispose = function () { + this._shuffled = null; + this.values = null; + }; + return Tone.CtrlPattern; + }); + Module(function (Tone) { + + /** + * @class Choose a random value. + * @extends {Tone} + * @example + * var randomWalk = new Tone.CtrlRandom({ + * "min" : 0, + * "max" : 10, + * "integer" : true + * }); + * randomWalk.eval(); + * + * @param {Number|Time=} min The minimum return value. + * @param {Number|Time=} max The maximum return value. + */ + Tone.CtrlRandom = function () { + var options = this.optionsObject(arguments, [ + 'min', + 'max' + ], Tone.CtrlRandom.defaults); + /** + * The minimum return value + * @type {Number|Time} + */ + this.min = options.min; + /** + * The maximum return value + * @type {Number|Time} + */ + this.max = options.max; + /** + * If the return value should be an integer + * @type {Boolean} + */ + this.integer = options.integer; + }; + Tone.extend(Tone.CtrlRandom); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.CtrlRandom.defaults = { + 'min': 0, + 'max': 1, + 'integer': false + }; + /** + * Return a random value between min and max. + * @readOnly + * @memberOf Tone.CtrlRandom# + * @type {*} + * @name value + */ + Object.defineProperty(Tone.CtrlRandom.prototype, 'value', { + get: function () { + var min = this.toSeconds(this.min); + var max = this.toSeconds(this.max); + var rand = Math.random(); + var val = rand * min + (1 - rand) * max; + if (this.integer) { + val = Math.floor(val); + } + return val; + } + }); + return Tone.CtrlRandom; + }); + Module(function (Tone) { + + /** + * AudioBuffer.copyToChannel polyfill + * @private + */ + if (window.AudioBuffer && !AudioBuffer.prototype.copyToChannel) { + AudioBuffer.prototype.copyToChannel = function (src, chanNum, start) { + var channel = this.getChannelData(chanNum); + start = start || 0; + for (var i = 0; i < channel.length; i++) { + channel[i + start] = src[i]; + } + }; + AudioBuffer.prototype.copyFromChannel = function (dest, chanNum, start) { + var channel = this.getChannelData(chanNum); + start = start || 0; + for (var i = 0; i < channel.length; i++) { + dest[i] = channel[i + start]; + } + }; + } + /** + * @class Buffer loading and storage. Tone.Buffer is used internally by all + * classes that make requests for audio files such as Tone.Player, + * Tone.Sampler and Tone.Convolver. + *

+ * Aside from load callbacks from individual buffers, Tone.Buffer + * provides static methods which keep track of the loading progress + * of all of the buffers. These methods are Tone.Buffer.on("load" / "progress" / "error") + * + * @constructor + * @extends {Tone} + * @param {AudioBuffer|string} url The url to load, or the audio buffer to set. + * @param {Function=} onload A callback which is invoked after the buffer is loaded. + * It's recommended to use Tone.Buffer.onload instead + * since it will give you a callback when ALL buffers are loaded. + * @param {Function=} onerror The callback to invoke if there is an error + * @example + * var buffer = new Tone.Buffer("path/to/sound.mp3", function(){ + * //the buffer is now available. + * var buff = buffer.get(); + * }); + */ + Tone.Buffer = function () { + var options = this.optionsObject(arguments, [ + 'url', + 'onload', + 'onerror' + ], Tone.Buffer.defaults); + /** + * stores the loaded AudioBuffer + * @type {AudioBuffer} + * @private + */ + this._buffer = null; + /** + * indicates if the buffer should be reversed or not + * @type {Boolean} + * @private + */ + this._reversed = options.reverse; + /** + * The XHR + * @type {XMLHttpRequest} + * @private + */ + this._xhr = null; + if (options.url instanceof AudioBuffer || options.url instanceof Tone.Buffer) { + this.set(options.url); + // invoke the onload callback + if (options.onload) { + options.onload(this); + } + } else if (this.isString(options.url)) { + this.load(options.url, options.onload, options.onerror); + } + }; + Tone.extend(Tone.Buffer); + /** + * the default parameters + * @type {Object} + */ + Tone.Buffer.defaults = { + 'url': undefined, + 'reverse': false + }; + /** + * Pass in an AudioBuffer or Tone.Buffer to set the value + * of this buffer. + * @param {AudioBuffer|Tone.Buffer} buffer the buffer + * @returns {Tone.Buffer} this + */ + Tone.Buffer.prototype.set = function (buffer) { + if (buffer instanceof Tone.Buffer) { + this._buffer = buffer.get(); + } else { + this._buffer = buffer; + } + return this; + }; + /** + * @return {AudioBuffer} The audio buffer stored in the object. + */ + Tone.Buffer.prototype.get = function () { + return this._buffer; + }; + /** + * Makes an xhr reqest for the selected url then decodes + * the file as an audio buffer. Invokes + * the callback once the audio buffer loads. + * @param {String} url The url of the buffer to load. + * filetype support depends on the + * browser. + * @returns {Promise} returns a Promise which resolves with the Tone.Buffer + */ + Tone.Buffer.prototype.load = function (url, onload, onerror) { + var promise = new Promise(function (load, error) { + this._xhr = Tone.Buffer.load(url, //success + function (buff) { + this._xhr = null; + this.set(buff); + load(this); + if (onload) { + onload(this); + } + }.bind(this), //error + function (err) { + this._xhr = null; + error(err); + if (onerror) { + onerror(err); + } + }.bind(this)); + }.bind(this)); + return promise; + }; + /** + * dispose and disconnect + * @returns {Tone.Buffer} this + */ + Tone.Buffer.prototype.dispose = function () { + Tone.Emitter.prototype.dispose.call(this); + this._buffer = null; + if (this._xhr) { + Tone.Buffer._currentDownloads--; + this._xhr.abort(); + this._xhr = null; + } + return this; + }; + /** + * If the buffer is loaded or not + * @memberOf Tone.Buffer# + * @type {Boolean} + * @name loaded + * @readOnly + */ + Object.defineProperty(Tone.Buffer.prototype, 'loaded', { + get: function () { + return this.length > 0; + } + }); + /** + * The duration of the buffer. + * @memberOf Tone.Buffer# + * @type {Number} + * @name duration + * @readOnly + */ + Object.defineProperty(Tone.Buffer.prototype, 'duration', { + get: function () { + if (this._buffer) { + return this._buffer.duration; + } else { + return 0; + } + } + }); + /** + * The length of the buffer in samples + * @memberOf Tone.Buffer# + * @type {Number} + * @name length + * @readOnly + */ + Object.defineProperty(Tone.Buffer.prototype, 'length', { + get: function () { + if (this._buffer) { + return this._buffer.length; + } else { + return 0; + } + } + }); + /** + * The number of discrete audio channels. Returns 0 if no buffer + * is loaded. + * @memberOf Tone.Buffer# + * @type {Number} + * @name numberOfChannels + * @readOnly + */ + Object.defineProperty(Tone.Buffer.prototype, 'numberOfChannels', { + get: function () { + if (this._buffer) { + return this._buffer.numberOfChannels; + } else { + return 0; + } + } + }); + /** + * Set the audio buffer from the array + * @param {Float32Array} array The array to fill the audio buffer + * @param {Number} [channels=1] The number of channels contained in the array. + * If the channel is more than 1, the input array + * is expected to be a multidimensional array + * with dimensions equal to the number of channels. + * @return {Tone.Buffer} this + */ + Tone.Buffer.prototype.fromArray = function (array) { + var isMultidimensional = array[0].length > 0; + var channels = isMultidimensional ? array.length : 1; + var len = isMultidimensional ? array[0].length : array.length; + var buffer = this.context.createBuffer(channels, len, this.context.sampleRate); + if (!isMultidimensional && channels === 1) { + array = [array]; + } + for (var c = 0; c < channels; c++) { + buffer.copyToChannel(array[c], c); + } + this._buffer = buffer; + return this; + }; + /** + * Sums muliple channels into 1 channel + * @param {Number=} channel Optionally only copy a single channel from the array. + * @return {Array} + */ + Tone.Buffer.prototype.toMono = function (chanNum) { + if (this.isNumber(chanNum)) { + this.fromArray(this.toArray(chanNum)); + } else { + var outputArray = new Float32Array(this.length); + var numChannels = this.numberOfChannels; + for (var channel = 0; channel < numChannels; channel++) { + var channelArray = this.toArray(channel); + for (var i = 0; i < channelArray.length; i++) { + outputArray[i] += channelArray[i]; + } + } + //divide by the number of channels + outputArray = outputArray.map(function (sample) { + return sample / numChannels; + }); + this.fromArray(outputArray); + } + return this; + }; + /** + * Get the buffer as an array. Single channel buffers will return a 1-dimensional + * Float32Array, and multichannel buffers will return multidimensional arrays. + * @param {Number=} channel Optionally only copy a single channel from the array. + * @return {Array} + */ + Tone.Buffer.prototype.toArray = function (channel) { + if (this.isNumber(channel)) { + return this.getChannelData(channel); + } else if (this.numberOfChannels === 1) { + return this.toArray(0); + } else { + var ret = []; + for (var c = 0; c < this.numberOfChannels; c++) { + ret[c] = this.getChannelData(c); + } + return ret; + } + }; + /** + * Returns the Float32Array representing the PCM audio data for the specific channel. + * @param {Number} channel The channel number to return + * @return {Float32Array} The audio as a TypedArray + */ + Tone.Buffer.prototype.getChannelData = function (channel) { + return this._buffer.getChannelData(channel); + }; + /** + * Cut a subsection of the array and return a buffer of the + * subsection. Does not modify the original buffer + * @param {Time} start The time to start the slice + * @param {Time=} end The end time to slice. If none is given + * will default to the end of the buffer + * @return {Tone.Buffer} this + */ + Tone.Buffer.prototype.slice = function (start, end) { + end = this.defaultArg(end, this.duration); + var startSamples = Math.floor(this.context.sampleRate * this.toSeconds(start)); + var endSamples = Math.floor(this.context.sampleRate * this.toSeconds(end)); + var replacement = []; + for (var i = 0; i < this.numberOfChannels; i++) { + replacement[i] = this.toArray(i).slice(startSamples, endSamples); + } + var retBuffer = new Tone.Buffer().fromArray(replacement); + return retBuffer; + }; + /** + * Reverse the buffer. + * @private + * @return {Tone.Buffer} this + */ + Tone.Buffer.prototype._reverse = function () { + if (this.loaded) { + for (var i = 0; i < this.numberOfChannels; i++) { + Array.prototype.reverse.call(this.getChannelData(i)); + } + } + return this; + }; + /** + * Reverse the buffer. + * @memberOf Tone.Buffer# + * @type {Boolean} + * @name reverse + */ + Object.defineProperty(Tone.Buffer.prototype, 'reverse', { + get: function () { + return this._reversed; + }, + set: function (rev) { + if (this._reversed !== rev) { + this._reversed = rev; + this._reverse(); + } + } + }); + /////////////////////////////////////////////////////////////////////////// + // STATIC METHODS + /////////////////////////////////////////////////////////////////////////// + //statically inherits Emitter methods + Tone.Emitter.mixin(Tone.Buffer); + /** + * the static queue for all of the xhr requests + * @type {Array} + * @private + */ + Tone.Buffer._downloadQueue = []; + /** + * the total number of downloads + * @type {Number} + * @private + */ + Tone.Buffer._currentDownloads = 0; + /** + * A path which is prefixed before every url. + * @type {String} + * @static + */ + Tone.Buffer.baseUrl = ''; + /** + * Loads a url using XMLHttpRequest. + * @param {String} url + * @param {Function} onload + * @param {Function} onerror + * @param {Function} onprogress + * @return {XMLHttpRequest} + */ + Tone.Buffer.load = function (url, onload, onerror) { + //default + onload = onload || Tone.noOp; + function onError(e) { + if (onerror) { + onerror(e); + Tone.Buffer.emit('error', e); + } else { + throw new Error(e); + } + } + function onProgress() { + //calculate the progress + var totalProgress = 0; + for (var i = 0; i < Tone.Buffer._downloadQueue.length; i++) { + totalProgress += Tone.Buffer._downloadQueue[i].progress; + } + Tone.Buffer.emit('progress', totalProgress / Tone.Buffer._downloadQueue.length); + } + var request = new XMLHttpRequest(); + request.open('GET', Tone.Buffer.baseUrl + url, true); + request.responseType = 'arraybuffer'; + //start out as 0 + request.progress = 0; + Tone.Buffer._currentDownloads++; + Tone.Buffer._downloadQueue.push(request); + request.addEventListener('load', function () { + if (request.status === 200) { + Tone.context.decodeAudioData(request.response, function (buff) { + request.progress = 1; + onProgress(); + onload(buff); + Tone.Buffer._currentDownloads--; + if (Tone.Buffer._currentDownloads === 0) { + // clear the downloads + Tone.Buffer._downloadQueue = []; + //emit the event at the end + Tone.Buffer.emit('load'); + } + }, function () { + onError('Tone.Buffer: could not decode audio data: ' + url); + }); + } else { + onError('Tone.Buffer: could not locate file: ' + url); + } + }); + request.addEventListener('error', onError); + request.addEventListener('progress', function (event) { + if (event.lengthComputable) { + //only go to 95%, the last 5% is when the audio is decoded + request.progress = event.loaded / event.total * 0.95; + onProgress(); + } + }); + request.send(); + return request; + }; + /** + * Stop all of the downloads in progress + * @return {Tone.Buffer} + * @static + */ + Tone.Buffer.cancelDownloads = function () { + Tone.Buffer._downloadQueue.forEach(function (request) { + request.abort(); + }); + Tone.Buffer._currentDownloads = 0; + return Tone.Buffer; + }; + /** + * Checks a url's extension to see if the current browser can play that file type. + * @param {String} url The url/extension to test + * @return {Boolean} If the file extension can be played + * @static + * @example + * Tone.Buffer.supportsType("wav"); //returns true + * Tone.Buffer.supportsType("path/to/file.wav"); //returns true + */ + Tone.Buffer.supportsType = function (url) { + var extension = url.split('.'); + extension = extension[extension.length - 1]; + var response = document.createElement('audio').canPlayType('audio/' + extension); + return response !== ''; + }; + /** + * Returns a Promise which resolves when all of the buffers have loaded + * @return {Promise} + */ + Tone.loaded = function () { + var onload, onerror; + function removeEvents() { + //remove the events when it's resolved + Tone.Buffer.off('load', onload); + Tone.Buffer.off('error', onerror); + } + return new Promise(function (success, fail) { + onload = function () { + success(); + }; + onerror = function () { + fail(); + }; + //add the event listeners + Tone.Buffer.on('load', onload); + Tone.Buffer.on('error', onerror); + }).then(removeEvents).catch(function (e) { + removeEvents(); + throw new Error(e); + }); + }; + return Tone.Buffer; + }); + Module(function (Tone) { + /** + * @class A data structure for holding multiple buffers. + * + * @param {Object|Array} urls An object literal or array + * of urls to load. + * @param {Function=} callback The callback to invoke when + * the buffers are loaded. + * @extends {Tone} + * @example + * //load a whole bank of piano samples + * var pianoSamples = new Tone.Buffers({ + * "C4" : "path/to/C4.mp3" + * "C#4" : "path/to/C#4.mp3" + * "D4" : "path/to/D4.mp3" + * "D#4" : "path/to/D#4.mp3" + * ... + * }, function(){ + * //play one of the samples when they all load + * player.buffer = pianoSamples.get("C4"); + * player.start(); + * }); + * + */ + Tone.Buffers = function (urls, onload, baseUrl) { + /** + * All of the buffers + * @type {Object} + * @private + */ + this._buffers = {}; + /** + * A path which is prefixed before every url. + * @type {String} + */ + this.baseUrl = this.defaultArg(baseUrl, ''); + urls = this._flattenUrls(urls); + this._loadingCount = 0; + //add each one + for (var key in urls) { + this._loadingCount++; + this.add(key, urls[key], this._bufferLoaded.bind(this, onload)); + } + }; + Tone.extend(Tone.Buffers); + /** + * True if the buffers object has a buffer by that name. + * @param {String|Number} name The key or index of the + * buffer. + * @return {Boolean} + */ + Tone.Buffers.prototype.has = function (name) { + return this._buffers.hasOwnProperty(name); + }; + /** + * Get a buffer by name. If an array was loaded, + * then use the array index. + * @param {String|Number} name The key or index of the + * buffer. + * @return {Tone.Buffer} + */ + Tone.Buffers.prototype.get = function (name) { + if (this.has(name)) { + return this._buffers[name]; + } else { + throw new Error('Tone.Buffers: no buffer named ' + name); + } + }; + /** + * A buffer was loaded. decrement the counter. + * @param {Function} callback + * @private + */ + Tone.Buffers.prototype._bufferLoaded = function (callback) { + this._loadingCount--; + if (this._loadingCount === 0 && callback) { + callback(this); + } + }; + /** + * If the buffers are loaded or not + * @memberOf Tone.Buffers# + * @type {Boolean} + * @name loaded + * @readOnly + */ + Object.defineProperty(Tone.Buffers.prototype, 'loaded', { + get: function () { + var isLoaded = true; + for (var buffName in this._buffers) { + var buff = this.get(buffName); + isLoaded = isLoaded && buff.loaded; + } + return isLoaded; + } + }); + /** + * Add a buffer by name and url to the Buffers + * @param {String} name A unique name to give + * the buffer + * @param {String|Tone.Buffer|Audiobuffer} url Either the url of the bufer, + * or a buffer which will be added + * with the given name. + * @param {Function=} callback The callback to invoke + * when the url is loaded. + */ + Tone.Buffers.prototype.add = function (name, url, callback) { + callback = this.defaultArg(callback, Tone.noOp); + if (url instanceof Tone.Buffer) { + this._buffers[name] = url; + callback(this); + } else if (url instanceof AudioBuffer) { + this._buffers[name] = new Tone.Buffer(url); + callback(this); + } else if (this.isString(url)) { + this._buffers[name] = new Tone.Buffer(this.baseUrl + url, callback); + } + return this; + }; + /** + * Flatten an object into a single depth object. + * thanks to https://gist.github.com/penguinboy/762197 + * @param {Object} ob + * @return {Object} + * @private + */ + Tone.Buffers.prototype._flattenUrls = function (ob) { + var toReturn = {}; + for (var i in ob) { + if (!ob.hasOwnProperty(i)) + continue; + if (this.isObject(ob[i])) { + var flatObject = this._flattenUrls(ob[i]); + for (var x in flatObject) { + if (!flatObject.hasOwnProperty(x)) + continue; + toReturn[i + '.' + x] = flatObject[x]; + } + } else { + toReturn[i] = ob[i]; + } + } + return toReturn; + }; + /** + * Clean up. + * @return {Tone.Buffers} this + */ + Tone.Buffers.prototype.dispose = function () { + for (var name in this._buffers) { + this._buffers[name].dispose(); + } + this._buffers = null; + return this; + }; + return Tone.Buffers; + }); + Module(function (Tone) { + + /** + * buses are another way of routing audio + * + * augments Tone.prototype to include send and recieve + */ + /** + * All of the routes + * + * @type {Object} + * @static + * @private + */ + var Buses = {}; + /** + * Send this signal to the channel name. + * @param {string} channelName A named channel to send the signal to. + * @param {Decibels} amount The amount of the source to send to the bus. + * @return {GainNode} The gain node which connects this node to the desired channel. + * Can be used to adjust the levels of the send. + * @example + * source.send("reverb", -12); + */ + Tone.prototype.send = function (channelName, amount) { + if (!Buses.hasOwnProperty(channelName)) { + Buses[channelName] = this.context.createGain(); + } + amount = this.defaultArg(amount, 0); + var sendKnob = new Tone.Gain(amount, Tone.Type.Decibels); + this.output.chain(sendKnob, Buses[channelName]); + return sendKnob; + }; + /** + * Recieve the input from the desired channelName to the input + * + * @param {string} channelName A named channel to send the signal to. + * @param {AudioNode} [input] If no input is selected, the + * input of the current node is + * chosen. + * @returns {Tone} this + * @example + * reverbEffect.receive("reverb"); + */ + Tone.prototype.receive = function (channelName, input) { + if (!Buses.hasOwnProperty(channelName)) { + Buses[channelName] = this.context.createGain(); + } + if (this.isUndef(input)) { + input = this.input; + } + Buses[channelName].connect(input); + return this; + }; + //remove all the send/receives when a new audio context is passed in + Tone.Context.on('init', function (context) { + if (context.Buses) { + Buses = context.Buses; + } else { + Buses = {}; + context.Buses = Buses; + } + }); + return Tone; + }); + Module(function (Tone) { + + /** + * @class Tone.Draw is useful for synchronizing visuals and audio events. + * Callbacks from Tone.Transport or any of the Tone.Event classes + * always happen _before_ the scheduled time and are not synchronized + * to the animation frame so they are not good for triggering tightly + * synchronized visuals and sound. Tone.Draw makes it easy to schedule + * callbacks using the AudioContext time and uses requestAnimationFrame. + * + * @singleton + * @extends {Tone} + * @example + * Tone.Transport.schedule(function(time){ + * //use the time argument to schedule a callback with Tone.Draw + * Tone.Draw.schedule(function(){ + * //do drawing or DOM manipulation here + * }, time) + * }, "+0.5") + */ + Tone.Draw = function () { + /** + * All of the events. + * @type {Tone.Timeline} + * @private + */ + this._events = new Tone.Timeline(); + /** + * The duration after which events are not invoked. + * @type {Number} + * @default 0.25 + */ + this.expiration = 0.25; + /** + * The amount of time before the scheduled time + * that the callback can be invoked. Default is + * half the time of an animation frame (0.008 seconds). + * @type {Number} + * @default 0.008 + */ + this.anticipation = 0.008; + /** + * The draw loop + * @type {Function} + * @private + */ + this._boundDrawLoop = this._drawLoop.bind(this); + }; + Tone.extend(Tone.Draw); + /** + * Schedule a function at the given time to be invoked + * on the nearest animation frame. + * @param {Function} callback Callback is invoked at the given time. + * @param {Time} time The time relative to the AudioContext time + * to invoke the callback. + * @return {Tone.Draw} this + */ + Tone.Draw.prototype.schedule = function (callback, time) { + this._events.add({ + callback: callback, + time: this.toSeconds(time) + }); + //start the draw loop on the first event + if (this._events.length === 1) { + requestAnimationFrame(this._boundDrawLoop); + } + return this; + }; + /** + * Cancel events scheduled after the given time + * @param {Time=} after Time after which scheduled events will + * be removed from the scheduling timeline. + * @return {Tone.Draw} this + */ + Tone.Draw.prototype.cancel = function (after) { + this._events.cancel(this.toSeconds(after)); + return this; + }; + /** + * The draw loop + * @private + */ + Tone.Draw.prototype._drawLoop = function () { + var now = Tone.now(); + while (this._events.length && this._events.peek().time - this.anticipation <= now) { + var event = this._events.shift(); + if (now - event.time <= this.expiration) { + event.callback(); + } + } + if (this._events.length > 0) { + requestAnimationFrame(this._boundDrawLoop); + } + }; + //make a singleton + Tone.Draw = new Tone.Draw(); + return Tone.Draw; + }); + Module(function (Tone) { + + /** + * @class Both Tone.Panner3D and Tone.Listener have a position in 3D space + * using a right-handed cartesian coordinate system. + * The units used in the coordinate system are not defined; + * these coordinates are independent/invariant of any particular + * units such as meters or feet. Tone.Panner3D objects have an forward + * vector representing the direction the sound is projecting. Additionally, + * they have a sound cone representing how directional the sound is. + * For example, the sound could be omnidirectional, in which case it would + * be heard anywhere regardless of its forward, or it can be more directional + * and heard only if it is facing the listener. Tone.Listener objects + * (representing a person's ears) have an forward and up vector + * representing in which direction the person is facing. Because both the + * source stream and the listener can be moving, they both have a velocity + * vector representing both the speed and direction of movement. Taken together, + * these two velocities can be used to generate a doppler shift effect which changes the pitch. + *

+ * Note: the position of the Listener will have no effect on nodes not connected to a Tone.Panner3D + * + * @constructor + * @extends {Tone} + * @singleton + * @param {Number} positionX The initial x position. + * @param {Number} positionY The initial y position. + * @param {Number} positionZ The initial z position. + */ + Tone.Listener = function () { + var options = this.optionsObject(arguments, [ + 'positionX', + 'positionY', + 'positionZ' + ], ListenerConstructor.defaults); + /** + * Holds the current forward orientation + * @type {Array} + * @private + */ + this._orientation = [ + options.forwardX, + options.forwardY, + options.forwardZ, + options.upX, + options.upY, + options.upZ + ]; + /** + * Holds the current position + * @type {Array} + * @private + */ + this._position = [ + options.positionX, + options.positionY, + options.positionZ + ]; + // set the default position/forward + this.forwardX = options.forwardX; + this.forwardY = options.forwardY; + this.forwardZ = options.forwardZ; + this.upX = options.upX; + this.upY = options.upY; + this.upZ = options.upZ; + this.positionX = options.positionX; + this.positionY = options.positionY; + this.positionZ = options.positionZ; + }; + Tone.extend(Tone.Listener); + /** + * the default parameters + * @static + * @const + * @type {Object} + * Defaults according to the specification + */ + Tone.Listener.defaults = { + 'positionX': 0, + 'positionY': 0, + 'positionZ': 0, + 'forwardX': 0, + 'forwardY': 0, + 'forwardZ': 1, + 'upX': 0, + 'upY': 1, + 'upZ': 0 + }; + /** + * The ramp time which is applied to the setTargetAtTime + * @type {Number} + * @private + */ + Tone.Listener.prototype._rampTimeConstant = 0.01; + /** + * Sets the position of the listener in 3d space. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @return {Tone.Listener} this + */ + Tone.Listener.prototype.setPosition = function (x, y, z) { + if (this.context.listener.positionX) { + var now = this.now(); + this.context.listener.positionX.setTargetAtTime(x, now, this._rampTimeConstant); + this.context.listener.positionY.setTargetAtTime(y, now, this._rampTimeConstant); + this.context.listener.positionZ.setTargetAtTime(z, now, this._rampTimeConstant); + } else { + this.context.listener.setPosition(x, y, z); + } + this._position = Array.prototype.slice.call(arguments); + return this; + }; + /** + * Sets the orientation of the listener using two vectors, the forward + * vector (which direction the listener is facing) and the up vector + * (which the up direction of the listener). An up vector + * of 0, 0, 1 is equivalent to the listener standing up in the Z direction. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {Number} upX + * @param {Number} upY + * @param {Number} upZ + * @return {Tone.Listener} this + */ + Tone.Listener.prototype.setOrientation = function (x, y, z, upX, upY, upZ) { + if (this.context.listener.forwardX) { + var now = this.now(); + this.context.listener.forwardX.setTargetAtTime(x, now, this._rampTimeConstant); + this.context.listener.forwardY.setTargetAtTime(y, now, this._rampTimeConstant); + this.context.listener.forwardZ.setTargetAtTime(z, now, this._rampTimeConstant); + this.context.listener.upX.setTargetAtTime(upX, now, this._rampTimeConstant); + this.context.listener.upY.setTargetAtTime(upY, now, this._rampTimeConstant); + this.context.listener.upZ.setTargetAtTime(upZ, now, this._rampTimeConstant); + } else { + this.context.listener.setOrientation(x, y, z, upX, upY, upZ); + } + this._orientation = Array.prototype.slice.call(arguments); + return this; + }; + /** + * The x position of the panner object. + * @type {Number} + * @memberOf Tone.Listener# + * @name positionX + */ + Object.defineProperty(Tone.Listener.prototype, 'positionX', { + set: function (pos) { + this._position[0] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[0]; + } + }); + /** + * The y position of the panner object. + * @type {Number} + * @memberOf Tone.Listener# + * @name positionY + */ + Object.defineProperty(Tone.Listener.prototype, 'positionY', { + set: function (pos) { + this._position[1] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[1]; + } + }); + /** + * The z position of the panner object. + * @type {Number} + * @memberOf Tone.Listener# + * @name positionZ + */ + Object.defineProperty(Tone.Listener.prototype, 'positionZ', { + set: function (pos) { + this._position[2] = pos; + this.setPosition.apply(this, this._position); + }, + get: function () { + return this._position[2]; + } + }); + /** + * The x coordinate of the listeners front direction. i.e. + * which way they are facing. + * @type {Number} + * @memberOf Tone.Listener# + * @name forwardX + */ + Object.defineProperty(Tone.Listener.prototype, 'forwardX', { + set: function (pos) { + this._orientation[0] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[0]; + } + }); + /** + * The y coordinate of the listeners front direction. i.e. + * which way they are facing. + * @type {Number} + * @memberOf Tone.Listener# + * @name forwardY + */ + Object.defineProperty(Tone.Listener.prototype, 'forwardY', { + set: function (pos) { + this._orientation[1] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[1]; + } + }); + /** + * The z coordinate of the listeners front direction. i.e. + * which way they are facing. + * @type {Number} + * @memberOf Tone.Listener# + * @name forwardZ + */ + Object.defineProperty(Tone.Listener.prototype, 'forwardZ', { + set: function (pos) { + this._orientation[2] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[2]; + } + }); + /** + * The x coordinate of the listener's up direction. i.e. + * the direction the listener is standing in. + * @type {Number} + * @memberOf Tone.Listener# + * @name upX + */ + Object.defineProperty(Tone.Listener.prototype, 'upX', { + set: function (pos) { + this._orientation[3] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[3]; + } + }); + /** + * The y coordinate of the listener's up direction. i.e. + * the direction the listener is standing in. + * @type {Number} + * @memberOf Tone.Listener# + * @name upY + */ + Object.defineProperty(Tone.Listener.prototype, 'upY', { + set: function (pos) { + this._orientation[4] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[4]; + } + }); + /** + * The z coordinate of the listener's up direction. i.e. + * the direction the listener is standing in. + * @type {Number} + * @memberOf Tone.Listener# + * @name upZ + */ + Object.defineProperty(Tone.Listener.prototype, 'upZ', { + set: function (pos) { + this._orientation[5] = pos; + this.setOrientation.apply(this, this._orientation); + }, + get: function () { + return this._orientation[5]; + } + }); + /** + * Clean up. + * @returns {Tone.Listener} this + */ + Tone.Listener.prototype.dispose = function () { + this._orientation = null; + this._position = null; + return this; + }; + //SINGLETON SETUP + var ListenerConstructor = Tone.Listener; + Tone.Listener = new ListenerConstructor(); + Tone.Context.on('init', function (context) { + if (context.Listener instanceof ListenerConstructor) { + //a single listener object + Tone.Listener = context.Listener; + } else { + //make new Listener insides + Tone.Listener = new ListenerConstructor(); + } + context.Listener = Tone.Listener; + }); + //END SINGLETON SETUP + return Tone.Listener; + }); + Module(function (Tone) { + /** + * shim + * @private + */ + if (!window.hasOwnProperty('OfflineAudioContext') && window.hasOwnProperty('webkitOfflineAudioContext')) { + window.OfflineAudioContext = window.webkitOfflineAudioContext; + } + /** + * @class Wrapper around the OfflineAudioContext + * @extends {Tone.Context + * @param {Number} channels The number of channels to render + * @param {Number} duration The duration to render in samples + * @param {Number} sampleRate the sample rate to render at + */ + Tone.OfflineContext = function (channels, duration, sampleRate) { + /** + * The offline context + * @private + * @type {OfflineAudioContext} + */ + var offlineContext = new OfflineAudioContext(channels, duration * sampleRate, sampleRate); + //wrap the methods/members + Tone.Context.call(this, offlineContext); + /** + * A private reference to the duration + * @private + * @type {Number} + */ + this._duration = duration; + /** + * An artificial clock source + * @type {Number} + * @private + */ + this._currentTime = 0; + //modify the lookAhead and updateInterval to one block + this.lookAhead = this.blockTime; + this.updateInterval = this.blockTime; + }; + Tone.extend(Tone.OfflineContext, Tone.Context); + /** + * Override the now method to point to the internal clock time + * @return {Number} + */ + Tone.OfflineContext.prototype.now = function () { + return this._currentTime; + }; + /** + * Overwrite this method since the worker is not necessary for the offline context + * @private + */ + Tone.OfflineContext.prototype._createWorker = function () { + //dummy worker that does nothing + return { + postMessage: function () { + } + }; + }; + /** + * Render the output of the OfflineContext + * @return {Promise} + */ + Tone.OfflineContext.prototype.render = function () { + while (this._duration - this._currentTime >= 0) { + //invoke all the callbacks on that time + this.emit('tick'); + //increment the clock + this._currentTime += Tone.prototype.blockTime; + } + //promise returned is not yet implemented in all browsers + return new Promise(function (done) { + this._context.oncomplete = function (e) { + done(e.renderedBuffer); + }; + this._context.startRendering(); + }.bind(this)); + }; + return Tone.OfflineContext; + }); + Module(function (Tone) { + /** + * Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext. + * The OfflineAudioContext is capable of rendering much faster than real time in many cases. + * The callback function also passes in an offline instance of Tone.Transport which can be used + * to schedule events along the Transport. + * @param {Function} callback All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer. + * @param {Time} duration the amount of time to record for. + * @return {Promise} The promise which is invoked with the Tone.Buffer of the recorded output. + * @example + * //render 2 seconds of the oscillator + * Tone.Offline(function(){ + * //only nodes created in this callback will be recorded + * var oscillator = new Tone.Oscillator().toMaster().start(0) + * //schedule their events + * }, 2).then(function(buffer){ + * //do something with the output buffer + * }) + * @example + * //can also schedule events along the Transport + * //using the passed in Offline Transport + * Tone.Offline(function(Transport){ + * var osc = new Tone.Oscillator().toMaster() + * Transport.schedule(function(time){ + * osc.start(time).stop(time + 0.1) + * }, 1) + * Transport.start(0.2) + * }, 4).then(function(buffer){ + * //do something with the output buffer + * }) + */ + Tone.Offline = function (callback, duration) { + //set the OfflineAudioContext + var sampleRate = Tone.context.sampleRate; + var originalContext = Tone.context; + var context = new Tone.OfflineContext(2, duration, sampleRate); + Tone.context = context; + //invoke the callback/scheduling + callback(Tone.Transport); + //process the audio + var rendered = context.render(); + //return the original AudioContext + Tone.context = originalContext; + //return the audio + return rendered.then(function (buffer) { + //wrap it in a Tone.Buffer + return new Tone.Buffer(buffer); + }); + }; + return Tone.Offline; + }); + Module(function (Tone) { + + /** + * @class Tone.Effect is the base class for effects. Connect the effect between + * the effectSend and effectReturn GainNodes, then control the amount of + * effect which goes to the output using the wet control. + * + * @constructor + * @extends {Tone} + * @param {NormalRange|Object} [wet] The starting wet value. + */ + Tone.Effect = function () { + this.createInsOuts(1, 1); + //get all of the defaults + var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); + /** + * the drywet knob to control the amount of effect + * @type {Tone.CrossFade} + * @private + */ + this._dryWet = new Tone.CrossFade(options.wet); + /** + * The wet control is how much of the effected + * will pass through to the output. 1 = 100% effected + * signal, 0 = 100% dry signal. + * @type {NormalRange} + * @signal + */ + this.wet = this._dryWet.fade; + /** + * connect the effectSend to the input of hte effect + * @type {Tone.Gain} + * @private + */ + this.effectSend = new Tone.Gain(); + /** + * connect the output of the effect to the effectReturn + * @type {Tone.Gain} + * @private + */ + this.effectReturn = new Tone.Gain(); + //connections + this.input.connect(this._dryWet.a); + this.input.connect(this.effectSend); + this.effectReturn.connect(this._dryWet.b); + this._dryWet.connect(this.output); + this._readOnly(['wet']); + }; + Tone.extend(Tone.Effect); + /** + * @static + * @type {Object} + */ + Tone.Effect.defaults = { 'wet': 1 }; + /** + * chains the effect in between the effectSend and effectReturn + * @param {Tone} effect + * @private + * @returns {Tone.Effect} this + */ + Tone.Effect.prototype.connectEffect = function (effect) { + this.effectSend.chain(effect, this.effectReturn); + return this; + }; + /** + * Clean up. + * @returns {Tone.Effect} this + */ + Tone.Effect.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._dryWet.dispose(); + this._dryWet = null; + this.effectSend.dispose(); + this.effectSend = null; + this.effectReturn.dispose(); + this.effectReturn = null; + this._writable(['wet']); + this.wet = null; + return this; + }; + return Tone.Effect; + }); + Module(function (Tone) { + + /** + * @class Tone.AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency. + * Setting the LFO rate and depth allows for control over the filter modulation rate + * and depth. + * + * @constructor + * @extends {Tone.Effect} + * @param {Time|Object} [frequency] The rate of the LFO. + * @param {Frequency=} baseFrequency The lower value of the LFOs oscillation + * @param {Frequency=} octaves The number of octaves above the baseFrequency + * @example + * //create an autofilter and start it's LFO + * var autoFilter = new Tone.AutoFilter("4n").toMaster().start(); + * //route an oscillator through the filter and start it + * var oscillator = new Tone.Oscillator().connect(autoFilter).start(); + */ + Tone.AutoFilter = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'baseFrequency', + 'octaves' + ], Tone.AutoFilter.defaults); + Tone.Effect.call(this, options); + /** + * the lfo which drives the filter cutoff + * @type {Tone.LFO} + * @private + */ + this._lfo = new Tone.LFO({ + 'frequency': options.frequency, + 'amplitude': options.depth + }); + /** + * The range of the filter modulating between the min and max frequency. + * 0 = no modulation. 1 = full modulation. + * @type {NormalRange} + * @signal + */ + this.depth = this._lfo.amplitude; + /** + * How fast the filter modulates between min and max. + * @type {Frequency} + * @signal + */ + this.frequency = this._lfo.frequency; + /** + * The filter node + * @type {Tone.Filter} + */ + this.filter = new Tone.Filter(options.filter); + /** + * The octaves placeholder + * @type {Positive} + * @private + */ + this._octaves = 0; + //connections + this.connectEffect(this.filter); + this._lfo.connect(this.filter.frequency); + this.type = options.type; + this._readOnly([ + 'frequency', + 'depth' + ]); + this.octaves = options.octaves; + this.baseFrequency = options.baseFrequency; + }; + //extend Effect + Tone.extend(Tone.AutoFilter, Tone.Effect); + /** + * defaults + * @static + * @type {Object} + */ + Tone.AutoFilter.defaults = { + 'frequency': 1, + 'type': 'sine', + 'depth': 1, + 'baseFrequency': 200, + 'octaves': 2.6, + 'filter': { + 'type': 'lowpass', + 'rolloff': -12, + 'Q': 1 + } + }; + /** + * Start the effect. + * @param {Time} [time=now] When the LFO will start. + * @returns {Tone.AutoFilter} this + */ + Tone.AutoFilter.prototype.start = function (time) { + this._lfo.start(time); + return this; + }; + /** + * Stop the effect. + * @param {Time} [time=now] When the LFO will stop. + * @returns {Tone.AutoFilter} this + */ + Tone.AutoFilter.prototype.stop = function (time) { + this._lfo.stop(time); + return this; + }; + /** + * Sync the filter to the transport. + * @param {Time} [delay=0] Delay time before starting the effect after the + * Transport has started. + * @returns {Tone.AutoFilter} this + */ + Tone.AutoFilter.prototype.sync = function (delay) { + this._lfo.sync(delay); + return this; + }; + /** + * Unsync the filter from the transport. + * @returns {Tone.AutoFilter} this + */ + Tone.AutoFilter.prototype.unsync = function () { + this._lfo.unsync(); + return this; + }; + /** + * Type of oscillator attached to the AutoFilter. + * Possible values: "sine", "square", "triangle", "sawtooth". + * @memberOf Tone.AutoFilter# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.AutoFilter.prototype, 'type', { + get: function () { + return this._lfo.type; + }, + set: function (type) { + this._lfo.type = type; + } + }); + /** + * The minimum value of the filter's cutoff frequency. + * @memberOf Tone.AutoFilter# + * @type {Frequency} + * @name min + */ + Object.defineProperty(Tone.AutoFilter.prototype, 'baseFrequency', { + get: function () { + return this._lfo.min; + }, + set: function (freq) { + this._lfo.min = this.toFrequency(freq); + //and set the max + this.octaves = this._octaves; + } + }); + /** + * The maximum value of the filter's cutoff frequency. + * @memberOf Tone.AutoFilter# + * @type {Positive} + * @name octaves + */ + Object.defineProperty(Tone.AutoFilter.prototype, 'octaves', { + get: function () { + return this._octaves; + }, + set: function (oct) { + this._octaves = oct; + this._lfo.max = this.baseFrequency * Math.pow(2, oct); + } + }); + /** + * Clean up. + * @returns {Tone.AutoFilter} this + */ + Tone.AutoFilter.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._lfo.dispose(); + this._lfo = null; + this.filter.dispose(); + this.filter = null; + this._writable([ + 'frequency', + 'depth' + ]); + this.frequency = null; + this.depth = null; + return this; + }; + return Tone.AutoFilter; + }); + Module(function (Tone) { + + /** + * @class Tone.AutoPanner is a Tone.Panner with an LFO connected to the pan amount. + * More on using autopanners [here](https://www.ableton.com/en/blog/autopan-chopper-effect-and-more-liveschool/). + * + * @constructor + * @extends {Tone.Effect} + * @param {Frequency|Object} [frequency] Rate of left-right oscillation. + * @example + * //create an autopanner and start it's LFO + * var autoPanner = new Tone.AutoPanner("4n").toMaster().start(); + * //route an oscillator through the panner and start it + * var oscillator = new Tone.Oscillator().connect(autoPanner).start(); + */ + Tone.AutoPanner = function () { + var options = this.optionsObject(arguments, ['frequency'], Tone.AutoPanner.defaults); + Tone.Effect.call(this, options); + /** + * the lfo which drives the panning + * @type {Tone.LFO} + * @private + */ + this._lfo = new Tone.LFO({ + 'frequency': options.frequency, + 'amplitude': options.depth, + 'min': -1, + 'max': 1 + }); + /** + * The amount of panning between left and right. + * 0 = always center. 1 = full range between left and right. + * @type {NormalRange} + * @signal + */ + this.depth = this._lfo.amplitude; + /** + * the panner node which does the panning + * @type {Tone.Panner} + * @private + */ + this._panner = new Tone.Panner(); + /** + * How fast the panner modulates between left and right. + * @type {Frequency} + * @signal + */ + this.frequency = this._lfo.frequency; + //connections + this.connectEffect(this._panner); + this._lfo.connect(this._panner.pan); + this.type = options.type; + this._readOnly([ + 'depth', + 'frequency' + ]); + }; + //extend Effect + Tone.extend(Tone.AutoPanner, Tone.Effect); + /** + * defaults + * @static + * @type {Object} + */ + Tone.AutoPanner.defaults = { + 'frequency': 1, + 'type': 'sine', + 'depth': 1 + }; + /** + * Start the effect. + * @param {Time} [time=now] When the LFO will start. + * @returns {Tone.AutoPanner} this + */ + Tone.AutoPanner.prototype.start = function (time) { + this._lfo.start(time); + return this; + }; + /** + * Stop the effect. + * @param {Time} [time=now] When the LFO will stop. + * @returns {Tone.AutoPanner} this + */ + Tone.AutoPanner.prototype.stop = function (time) { + this._lfo.stop(time); + return this; + }; + /** + * Sync the panner to the transport. + * @param {Time} [delay=0] Delay time before starting the effect after the + * Transport has started. + * @returns {Tone.AutoPanner} this + */ + Tone.AutoPanner.prototype.sync = function (delay) { + this._lfo.sync(delay); + return this; + }; + /** + * Unsync the panner from the transport + * @returns {Tone.AutoPanner} this + */ + Tone.AutoPanner.prototype.unsync = function () { + this._lfo.unsync(); + return this; + }; + /** + * Type of oscillator attached to the AutoFilter. + * Possible values: "sine", "square", "triangle", "sawtooth". + * @memberOf Tone.AutoFilter# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.AutoPanner.prototype, 'type', { + get: function () { + return this._lfo.type; + }, + set: function (type) { + this._lfo.type = type; + } + }); + /** + * clean up + * @returns {Tone.AutoPanner} this + */ + Tone.AutoPanner.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._lfo.dispose(); + this._lfo = null; + this._panner.dispose(); + this._panner = null; + this._writable([ + 'depth', + 'frequency' + ]); + this.frequency = null; + this.depth = null; + return this; + }; + return Tone.AutoPanner; + }); + Module(function (Tone) { + + /** + * @class Tone.AutoWah connects a Tone.Follower to a bandpass filter (Tone.Filter). + * The frequency of the filter is adjusted proportionally to the + * incoming signal's amplitude. Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna). + * + * @constructor + * @extends {Tone.Effect} + * @param {Frequency|Object} [baseFrequency] The frequency the filter is set + * to at the low point of the wah + * @param {Positive} [octaves] The number of octaves above the baseFrequency + * the filter will sweep to when fully open + * @param {Decibels} [sensitivity] The decibel threshold sensitivity for + * the incoming signal. Normal range of -40 to 0. + * @example + * var autoWah = new Tone.AutoWah(50, 6, -30).toMaster(); + * //initialize the synth and connect to autowah + * var synth = new Synth.connect(autoWah); + * //Q value influences the effect of the wah - default is 2 + * autoWah.Q.value = 6; + * //more audible on higher notes + * synth.triggerAttackRelease("C4", "8n") + */ + Tone.AutoWah = function () { + var options = this.optionsObject(arguments, [ + 'baseFrequency', + 'octaves', + 'sensitivity' + ], Tone.AutoWah.defaults); + Tone.Effect.call(this, options); + /** + * The envelope follower. Set the attack/release + * timing to adjust how the envelope is followed. + * @type {Tone.Follower} + * @private + */ + this.follower = new Tone.Follower(options.follower); + /** + * scales the follower value to the frequency domain + * @type {Tone} + * @private + */ + this._sweepRange = new Tone.ScaleExp(0, 1, 0.5); + /** + * @type {number} + * @private + */ + this._baseFrequency = options.baseFrequency; + /** + * @type {number} + * @private + */ + this._octaves = options.octaves; + /** + * the input gain to adjust the sensitivity + * @type {Tone.Gain} + * @private + */ + this._inputBoost = new Tone.Gain(); + /** + * @type {BiquadFilterNode} + * @private + */ + this._bandpass = new Tone.Filter({ + 'rolloff': -48, + 'frequency': 0, + 'Q': options.Q + }); + /** + * @type {Tone.Filter} + * @private + */ + this._peaking = new Tone.Filter(0, 'peaking'); + this._peaking.gain.value = options.gain; + /** + * The gain of the filter. + * @type {Number} + * @signal + */ + this.gain = this._peaking.gain; + /** + * The quality of the filter. + * @type {Positive} + * @signal + */ + this.Q = this._bandpass.Q; + //the control signal path + this.effectSend.chain(this._inputBoost, this.follower, this._sweepRange); + this._sweepRange.connect(this._bandpass.frequency); + this._sweepRange.connect(this._peaking.frequency); + //the filtered path + this.effectSend.chain(this._bandpass, this._peaking, this.effectReturn); + //set the initial value + this._setSweepRange(); + this.sensitivity = options.sensitivity; + this._readOnly([ + 'gain', + 'Q' + ]); + }; + Tone.extend(Tone.AutoWah, Tone.Effect); + /** + * @static + * @type {Object} + */ + Tone.AutoWah.defaults = { + 'baseFrequency': 100, + 'octaves': 6, + 'sensitivity': 0, + 'Q': 2, + 'gain': 2, + 'follower': { + 'attack': 0.3, + 'release': 0.5 + } + }; + /** + * The number of octaves that the filter will sweep above the + * baseFrequency. + * @memberOf Tone.AutoWah# + * @type {Number} + * @name octaves + */ + Object.defineProperty(Tone.AutoWah.prototype, 'octaves', { + get: function () { + return this._octaves; + }, + set: function (octaves) { + this._octaves = octaves; + this._setSweepRange(); + } + }); + /** + * The base frequency from which the sweep will start from. + * @memberOf Tone.AutoWah# + * @type {Frequency} + * @name baseFrequency + */ + Object.defineProperty(Tone.AutoWah.prototype, 'baseFrequency', { + get: function () { + return this._baseFrequency; + }, + set: function (baseFreq) { + this._baseFrequency = baseFreq; + this._setSweepRange(); + } + }); + /** + * The sensitivity to control how responsive to the input signal the filter is. + * @memberOf Tone.AutoWah# + * @type {Decibels} + * @name sensitivity + */ + Object.defineProperty(Tone.AutoWah.prototype, 'sensitivity', { + get: function () { + return this.gainToDb(1 / this._inputBoost.gain.value); + }, + set: function (sensitivy) { + this._inputBoost.gain.value = 1 / this.dbToGain(sensitivy); + } + }); + /** + * sets the sweep range of the scaler + * @private + */ + Tone.AutoWah.prototype._setSweepRange = function () { + this._sweepRange.min = this._baseFrequency; + this._sweepRange.max = Math.min(this._baseFrequency * Math.pow(2, this._octaves), this.context.sampleRate / 2); + }; + /** + * Clean up. + * @returns {Tone.AutoWah} this + */ + Tone.AutoWah.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this.follower.dispose(); + this.follower = null; + this._sweepRange.dispose(); + this._sweepRange = null; + this._bandpass.dispose(); + this._bandpass = null; + this._peaking.dispose(); + this._peaking = null; + this._inputBoost.dispose(); + this._inputBoost = null; + this._writable([ + 'gain', + 'Q' + ]); + this.gain = null; + this.Q = null; + return this; + }; + return Tone.AutoWah; + }); + Module(function (Tone) { + + /** + * @class Tone.Bitcrusher downsamples the incoming signal to a different bitdepth. + * Lowering the bitdepth of the signal creates distortion. Read more about Bitcrushing + * on [Wikipedia](https://en.wikipedia.org/wiki/Bitcrusher). + * + * @constructor + * @extends {Tone.Effect} + * @param {Number} bits The number of bits to downsample the signal. Nominal range + * of 1 to 8. + * @example + * //initialize crusher and route a synth through it + * var crusher = new Tone.BitCrusher(4).toMaster(); + * var synth = new Tone.MonoSynth().connect(crusher); + */ + Tone.BitCrusher = function () { + var options = this.optionsObject(arguments, ['bits'], Tone.BitCrusher.defaults); + Tone.Effect.call(this, options); + var invStepSize = 1 / Math.pow(2, options.bits - 1); + /** + * Subtract the input signal and the modulus of the input signal + * @type {Tone.Subtract} + * @private + */ + this._subtract = new Tone.Subtract(); + /** + * The mod function + * @type {Tone.Modulo} + * @private + */ + this._modulo = new Tone.Modulo(invStepSize); + /** + * keeps track of the bits + * @type {number} + * @private + */ + this._bits = options.bits; + //connect it up + this.effectSend.fan(this._subtract, this._modulo); + this._modulo.connect(this._subtract, 0, 1); + this._subtract.connect(this.effectReturn); + }; + Tone.extend(Tone.BitCrusher, Tone.Effect); + /** + * the default values + * @static + * @type {Object} + */ + Tone.BitCrusher.defaults = { 'bits': 4 }; + /** + * The bit depth of the effect. Nominal range of 1-8. + * @memberOf Tone.BitCrusher# + * @type {number} + * @name bits + */ + Object.defineProperty(Tone.BitCrusher.prototype, 'bits', { + get: function () { + return this._bits; + }, + set: function (bits) { + this._bits = bits; + var invStepSize = 1 / Math.pow(2, bits - 1); + this._modulo.value = invStepSize; + } + }); + /** + * Clean up. + * @returns {Tone.BitCrusher} this + */ + Tone.BitCrusher.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._subtract.dispose(); + this._subtract = null; + this._modulo.dispose(); + this._modulo = null; + return this; + }; + return Tone.BitCrusher; + }); + Module(function (Tone) { + + /** + * @class Tone.ChebyShev is a Chebyshev waveshaper, an effect which is good + * for making different types of distortion sounds. + * Note that odd orders sound very different from even ones, + * and order = 1 is no change. + * Read more at [music.columbia.edu](http://music.columbia.edu/cmc/musicandcomputers/chapter4/04_06.php). + * + * @extends {Tone.Effect} + * @constructor + * @param {Positive|Object} [order] The order of the chebyshev polynomial. Normal range between 1-100. + * @example + * //create a new cheby + * var cheby = new Tone.Chebyshev(50); + * //create a monosynth connected to our cheby + * synth = new Tone.MonoSynth().connect(cheby); + */ + Tone.Chebyshev = function () { + var options = this.optionsObject(arguments, ['order'], Tone.Chebyshev.defaults); + Tone.Effect.call(this, options); + /** + * @type {WaveShaperNode} + * @private + */ + this._shaper = new Tone.WaveShaper(4096); + /** + * holds onto the order of the filter + * @type {number} + * @private + */ + this._order = options.order; + this.connectEffect(this._shaper); + this.order = options.order; + this.oversample = options.oversample; + }; + Tone.extend(Tone.Chebyshev, Tone.Effect); + /** + * @static + * @const + * @type {Object} + */ + Tone.Chebyshev.defaults = { + 'order': 1, + 'oversample': 'none' + }; + /** + * get the coefficient for that degree + * @param {number} x the x value + * @param {number} degree + * @param {Object} memo memoize the computed value. + * this speeds up computation greatly. + * @return {number} the coefficient + * @private + */ + Tone.Chebyshev.prototype._getCoefficient = function (x, degree, memo) { + if (memo.hasOwnProperty(degree)) { + return memo[degree]; + } else if (degree === 0) { + memo[degree] = 0; + } else if (degree === 1) { + memo[degree] = x; + } else { + memo[degree] = 2 * x * this._getCoefficient(x, degree - 1, memo) - this._getCoefficient(x, degree - 2, memo); + } + return memo[degree]; + }; + /** + * The order of the Chebyshev polynomial which creates + * the equation which is applied to the incoming + * signal through a Tone.WaveShaper. The equations + * are in the form:
+ * order 2: 2x^2 + 1
+ * order 3: 4x^3 + 3x
+ * @memberOf Tone.Chebyshev# + * @type {Positive} + * @name order + */ + Object.defineProperty(Tone.Chebyshev.prototype, 'order', { + get: function () { + return this._order; + }, + set: function (order) { + this._order = order; + var curve = new Array(4096); + var len = curve.length; + for (var i = 0; i < len; ++i) { + var x = i * 2 / len - 1; + if (x === 0) { + //should output 0 when input is 0 + curve[i] = 0; + } else { + curve[i] = this._getCoefficient(x, order, {}); + } + } + this._shaper.curve = curve; + } + }); + /** + * The oversampling of the effect. Can either be "none", "2x" or "4x". + * @memberOf Tone.Chebyshev# + * @type {string} + * @name oversample + */ + Object.defineProperty(Tone.Chebyshev.prototype, 'oversample', { + get: function () { + return this._shaper.oversample; + }, + set: function (oversampling) { + this._shaper.oversample = oversampling; + } + }); + /** + * Clean up. + * @returns {Tone.Chebyshev} this + */ + Tone.Chebyshev.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._shaper.dispose(); + this._shaper = null; + return this; + }; + return Tone.Chebyshev; + }); + Module(function (Tone) { + + /** + * @class Base class for Stereo effects. Provides effectSendL/R and effectReturnL/R. + * + * @constructor + * @extends {Tone.Effect} + */ + Tone.StereoEffect = function () { + this.createInsOuts(1, 1); + //get the defaults + var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); + /** + * the drywet knob to control the amount of effect + * @type {Tone.CrossFade} + * @private + */ + this._dryWet = new Tone.CrossFade(options.wet); + /** + * The wet control, i.e. how much of the effected + * will pass through to the output. + * @type {NormalRange} + * @signal + */ + this.wet = this._dryWet.fade; + /** + * then split it + * @type {Tone.Split} + * @private + */ + this._split = new Tone.Split(); + /** + * the effects send LEFT + * @type {GainNode} + * @private + */ + this.effectSendL = this._split.left; + /** + * the effects send RIGHT + * @type {GainNode} + * @private + */ + this.effectSendR = this._split.right; + /** + * the stereo effect merger + * @type {Tone.Merge} + * @private + */ + this._merge = new Tone.Merge(); + /** + * the effect return LEFT + * @type {GainNode} + * @private + */ + this.effectReturnL = this._merge.left; + /** + * the effect return RIGHT + * @type {GainNode} + * @private + */ + this.effectReturnR = this._merge.right; + //connections + this.input.connect(this._split); + //dry wet connections + this.input.connect(this._dryWet, 0, 0); + this._merge.connect(this._dryWet, 0, 1); + this._dryWet.connect(this.output); + this._readOnly(['wet']); + }; + Tone.extend(Tone.StereoEffect, Tone.Effect); + /** + * Clean up. + * @returns {Tone.StereoEffect} this + */ + Tone.StereoEffect.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._dryWet.dispose(); + this._dryWet = null; + this._split.dispose(); + this._split = null; + this._merge.dispose(); + this._merge = null; + this.effectSendL = null; + this.effectSendR = null; + this.effectReturnL = null; + this.effectReturnR = null; + this._writable(['wet']); + this.wet = null; + return this; + }; + return Tone.StereoEffect; + }); + Module(function (Tone) { + + /** + * @class Tone.FeedbackEffect provides a loop between an + * audio source and its own output. This is a base-class + * for feedback effects. + * + * @constructor + * @extends {Tone.Effect} + * @param {NormalRange|Object} [feedback] The initial feedback value. + */ + Tone.FeedbackEffect = function () { + var options = this.optionsObject(arguments, ['feedback']); + options = this.defaultArg(options, Tone.FeedbackEffect.defaults); + Tone.Effect.call(this, options); + /** + * the gain which controls the feedback + * @type {Tone.Gain} + * @private + */ + this._feedbackGain = new Tone.Gain(options.feedback, Tone.Type.NormalRange); + /** + * The amount of signal which is fed back into the effect input. + * @type {NormalRange} + * @signal + */ + this.feedback = this._feedbackGain.gain; + //the feedback loop + this.effectReturn.chain(this._feedbackGain, this.effectSend); + this._readOnly(['feedback']); + }; + Tone.extend(Tone.FeedbackEffect, Tone.Effect); + /** + * @static + * @type {Object} + */ + Tone.FeedbackEffect.defaults = { 'feedback': 0.125 }; + /** + * Clean up. + * @returns {Tone.FeedbackEffect} this + */ + Tone.FeedbackEffect.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._writable(['feedback']); + this._feedbackGain.dispose(); + this._feedbackGain = null; + this.feedback = null; + return this; + }; + return Tone.FeedbackEffect; + }); + Module(function (Tone) { + + /** + * @class Just like a stereo feedback effect, but the feedback is routed from left to right + * and right to left instead of on the same channel. + * + * @constructor + * @extends {Tone.FeedbackEffect} + */ + Tone.StereoXFeedbackEffect = function () { + var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); + Tone.StereoEffect.call(this, options); + /** + * The amount of feedback from the output + * back into the input of the effect (routed + * across left and right channels). + * @type {NormalRange} + * @signal + */ + this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); + /** + * the left side feeback + * @type {Tone.Gain} + * @private + */ + this._feedbackLR = new Tone.Gain(); + /** + * the right side feeback + * @type {Tone.Gain} + * @private + */ + this._feedbackRL = new Tone.Gain(); + //connect it up + this.effectReturnL.chain(this._feedbackLR, this.effectSendR); + this.effectReturnR.chain(this._feedbackRL, this.effectSendL); + this.feedback.fan(this._feedbackLR.gain, this._feedbackRL.gain); + this._readOnly(['feedback']); + }; + Tone.extend(Tone.StereoXFeedbackEffect, Tone.FeedbackEffect); + /** + * clean up + * @returns {Tone.StereoXFeedbackEffect} this + */ + Tone.StereoXFeedbackEffect.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + this._writable(['feedback']); + this.feedback.dispose(); + this.feedback = null; + this._feedbackLR.dispose(); + this._feedbackLR = null; + this._feedbackRL.dispose(); + this._feedbackRL = null; + return this; + }; + return Tone.StereoXFeedbackEffect; + }); + Module(function (Tone) { + + /** + * @class Tone.Chorus is a stereo chorus effect with feedback composed of + * a left and right delay with a Tone.LFO applied to the delayTime of each channel. + * Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna/blob/master/tuna.js). + * Read more on the chorus effect on [SoundOnSound](http://www.soundonsound.com/sos/jun04/articles/synthsecrets.htm). + * + * @constructor + * @extends {Tone.StereoXFeedbackEffect} + * @param {Frequency|Object} [frequency] The frequency of the LFO. + * @param {Milliseconds} [delayTime] The delay of the chorus effect in ms. + * @param {NormalRange} [depth] The depth of the chorus. + * @example + * var chorus = new Tone.Chorus(4, 2.5, 0.5); + * var synth = new Tone.PolySynth(4, Tone.MonoSynth).connect(chorus); + * synth.triggerAttackRelease(["C3","E3","G3"], "8n"); + */ + Tone.Chorus = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'delayTime', + 'depth' + ], Tone.Chorus.defaults); + Tone.StereoXFeedbackEffect.call(this, options); + /** + * the depth of the chorus + * @type {number} + * @private + */ + this._depth = options.depth; + /** + * the delayTime + * @type {number} + * @private + */ + this._delayTime = options.delayTime / 1000; + /** + * the lfo which controls the delayTime + * @type {Tone.LFO} + * @private + */ + this._lfoL = new Tone.LFO({ + 'frequency': options.frequency, + 'min': 0, + 'max': 1 + }); + /** + * another LFO for the right side with a 180 degree phase diff + * @type {Tone.LFO} + * @private + */ + this._lfoR = new Tone.LFO({ + 'frequency': options.frequency, + 'min': 0, + 'max': 1, + 'phase': 180 + }); + /** + * delay for left + * @type {Tone.Delay} + * @private + */ + this._delayNodeL = new Tone.Delay(); + /** + * delay for right + * @type {Tone.Delay} + * @private + */ + this._delayNodeR = new Tone.Delay(); + /** + * The frequency of the LFO which modulates the delayTime. + * @type {Frequency} + * @signal + */ + this.frequency = this._lfoL.frequency; + //connections + this.effectSendL.chain(this._delayNodeL, this.effectReturnL); + this.effectSendR.chain(this._delayNodeR, this.effectReturnR); + //and pass through to make the detune apparent + this.effectSendL.connect(this.effectReturnL); + this.effectSendR.connect(this.effectReturnR); + //lfo setup + this._lfoL.connect(this._delayNodeL.delayTime); + this._lfoR.connect(this._delayNodeR.delayTime); + //start the lfo + this._lfoL.start(); + this._lfoR.start(); + //have one LFO frequency control the other + this._lfoL.frequency.connect(this._lfoR.frequency); + //set the initial values + this.depth = this._depth; + this.frequency.value = options.frequency; + this.type = options.type; + this._readOnly(['frequency']); + this.spread = options.spread; + }; + Tone.extend(Tone.Chorus, Tone.StereoXFeedbackEffect); + /** + * @static + * @type {Object} + */ + Tone.Chorus.defaults = { + 'frequency': 1.5, + 'delayTime': 3.5, + 'depth': 0.7, + 'feedback': 0.1, + 'type': 'sine', + 'spread': 180 + }; + /** + * The depth of the effect. A depth of 1 makes the delayTime + * modulate between 0 and 2*delayTime (centered around the delayTime). + * @memberOf Tone.Chorus# + * @type {NormalRange} + * @name depth + */ + Object.defineProperty(Tone.Chorus.prototype, 'depth', { + get: function () { + return this._depth; + }, + set: function (depth) { + this._depth = depth; + var deviation = this._delayTime * depth; + this._lfoL.min = Math.max(this._delayTime - deviation, 0); + this._lfoL.max = this._delayTime + deviation; + this._lfoR.min = Math.max(this._delayTime - deviation, 0); + this._lfoR.max = this._delayTime + deviation; + } + }); + /** + * The delayTime in milliseconds of the chorus. A larger delayTime + * will give a more pronounced effect. Nominal range a delayTime + * is between 2 and 20ms. + * @memberOf Tone.Chorus# + * @type {Milliseconds} + * @name delayTime + */ + Object.defineProperty(Tone.Chorus.prototype, 'delayTime', { + get: function () { + return this._delayTime * 1000; + }, + set: function (delayTime) { + this._delayTime = delayTime / 1000; + this.depth = this._depth; + } + }); + /** + * The oscillator type of the LFO. + * @memberOf Tone.Chorus# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.Chorus.prototype, 'type', { + get: function () { + return this._lfoL.type; + }, + set: function (type) { + this._lfoL.type = type; + this._lfoR.type = type; + } + }); + /** + * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. + * When set to 180, LFO's will be panned hard left and right respectively. + * @memberOf Tone.Chorus# + * @type {Degrees} + * @name spread + */ + Object.defineProperty(Tone.Chorus.prototype, 'spread', { + get: function () { + return this._lfoR.phase - this._lfoL.phase; //180 + }, + set: function (spread) { + this._lfoL.phase = 90 - spread / 2; + this._lfoR.phase = spread / 2 + 90; + } + }); + /** + * Clean up. + * @returns {Tone.Chorus} this + */ + Tone.Chorus.prototype.dispose = function () { + Tone.StereoXFeedbackEffect.prototype.dispose.call(this); + this._lfoL.dispose(); + this._lfoL = null; + this._lfoR.dispose(); + this._lfoR = null; + this._delayNodeL.dispose(); + this._delayNodeL = null; + this._delayNodeR.dispose(); + this._delayNodeR = null; + this._writable('frequency'); + this.frequency = null; + return this; + }; + return Tone.Chorus; + }); + Module(function (Tone) { + + /** + * @class Tone.Convolver is a wrapper around the Native Web Audio + * [ConvolverNode](http://webaudio.github.io/web-audio-api/#the-convolvernode-interface). + * Convolution is useful for reverb and filter emulation. Read more about convolution reverb on + * [Wikipedia](https://en.wikipedia.org/wiki/Convolution_reverb). + * + * @constructor + * @extends {Tone.Effect} + * @param {string|Tone.Buffer|Object} [url] The URL of the impulse response or the Tone.Buffer + * contianing the impulse response. + * @param {Function} onload The callback to invoke when the url is loaded. + * @example + * //initializing the convolver with an impulse response + * var convolver = new Tone.Convolver("./path/to/ir.wav").toMaster(); + */ + Tone.Convolver = function () { + var options = this.optionsObject(arguments, [ + 'url', + 'onload' + ], Tone.Convolver.defaults); + Tone.Effect.call(this, options); + /** + * convolver node + * @type {ConvolverNode} + * @private + */ + this._convolver = this.context.createConvolver(); + /** + * the convolution buffer + * @type {Tone.Buffer} + * @private + */ + this._buffer = new Tone.Buffer(); + if (this.isString(options.url)) { + this._buffer.load(options.url, function (buffer) { + this.buffer = buffer; + options.onload(); + }.bind(this)); + } else if (options.url) { + this.buffer = options.url; + options.onload(); + } + this.connectEffect(this._convolver); + }; + Tone.extend(Tone.Convolver, Tone.Effect); + /** + * @static + * @const + * @type {Object} + */ + Tone.Convolver.defaults = { 'onload': Tone.noOp }; + /** + * The convolver's buffer + * @memberOf Tone.Convolver# + * @type {AudioBuffer} + * @name buffer + */ + Object.defineProperty(Tone.Convolver.prototype, 'buffer', { + get: function () { + return this._buffer.get(); + }, + set: function (buffer) { + this._buffer.set(buffer); + this._convolver.buffer = this._buffer.get(); + } + }); + /** + * Load an impulse response url as an audio buffer. + * Decodes the audio asynchronously and invokes + * the callback once the audio buffer loads. + * @param {string} url The url of the buffer to load. + * filetype support depends on the + * browser. + * @param {function=} callback + * @returns {Promise} + */ + Tone.Convolver.prototype.load = function (url, callback) { + return this._buffer.load(url, function (buff) { + this.buffer = buff; + if (callback) { + callback(); + } + }.bind(this)); + }; + /** + * Clean up. + * @returns {Tone.Convolver} this + */ + Tone.Convolver.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._convolver.disconnect(); + this._convolver = null; + this._buffer.dispose(); + this._buffer = null; + return this; + }; + return Tone.Convolver; + }); + Module(function (Tone) { + + /** + * @class Tone.Distortion is a simple distortion effect using Tone.WaveShaper. + * Algorithm from [a stackoverflow answer](http://stackoverflow.com/a/22313408). + * + * @extends {Tone.Effect} + * @constructor + * @param {Number|Object} [distortion] The amount of distortion (nominal range of 0-1) + * @example + * var dist = new Tone.Distortion(0.8).toMaster(); + * var fm = new Tone.SimpleFM().connect(dist); + * //this sounds good on bass notes + * fm.triggerAttackRelease("A1", "8n"); + */ + Tone.Distortion = function () { + var options = this.optionsObject(arguments, ['distortion'], Tone.Distortion.defaults); + Tone.Effect.call(this, options); + /** + * @type {Tone.WaveShaper} + * @private + */ + this._shaper = new Tone.WaveShaper(4096); + /** + * holds the distortion amount + * @type {number} + * @private + */ + this._distortion = options.distortion; + this.connectEffect(this._shaper); + this.distortion = options.distortion; + this.oversample = options.oversample; + }; + Tone.extend(Tone.Distortion, Tone.Effect); + /** + * @static + * @const + * @type {Object} + */ + Tone.Distortion.defaults = { + 'distortion': 0.4, + 'oversample': 'none' + }; + /** + * The amount of distortion. + * @memberOf Tone.Distortion# + * @type {NormalRange} + * @name distortion + */ + Object.defineProperty(Tone.Distortion.prototype, 'distortion', { + get: function () { + return this._distortion; + }, + set: function (amount) { + this._distortion = amount; + var k = amount * 100; + var deg = Math.PI / 180; + this._shaper.setMap(function (x) { + if (Math.abs(x) < 0.001) { + //should output 0 when input is 0 + return 0; + } else { + return (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); + } + }); + } + }); + /** + * The oversampling of the effect. Can either be "none", "2x" or "4x". + * @memberOf Tone.Distortion# + * @type {string} + * @name oversample + */ + Object.defineProperty(Tone.Distortion.prototype, 'oversample', { + get: function () { + return this._shaper.oversample; + }, + set: function (oversampling) { + this._shaper.oversample = oversampling; + } + }); + /** + * Clean up. + * @returns {Tone.Distortion} this + */ + Tone.Distortion.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._shaper.dispose(); + this._shaper = null; + return this; + }; + return Tone.Distortion; + }); + Module(function (Tone) { + + /** + * @class Tone.FeedbackDelay is a DelayNode in which part of output + * signal is fed back into the delay. + * + * @constructor + * @extends {Tone.FeedbackEffect} + * @param {Time|Object} [delayTime] The delay applied to the incoming signal. + * @param {NormalRange=} feedback The amount of the effected signal which + * is fed back through the delay. + * @example + * var feedbackDelay = new Tone.FeedbackDelay("8n", 0.5).toMaster(); + * var tom = new Tone.DrumSynth({ + * "octaves" : 4, + * "pitchDecay" : 0.1 + * }).connect(feedbackDelay); + * tom.triggerAttackRelease("A2","32n"); + */ + Tone.FeedbackDelay = function () { + var options = this.optionsObject(arguments, [ + 'delayTime', + 'feedback' + ], Tone.FeedbackDelay.defaults); + Tone.FeedbackEffect.call(this, options); + /** + * the delay node + * @type {Tone.Delay} + * @private + */ + this._delayNode = new Tone.Delay(options.delayTime); + /** + * The delayTime of the DelayNode. + * @type {Time} + * @signal + */ + this.delayTime = this._delayNode.delayTime; + // connect it up + this.connectEffect(this._delayNode); + this._readOnly(['delayTime']); + }; + Tone.extend(Tone.FeedbackDelay, Tone.FeedbackEffect); + /** + * The default values. + * @const + * @static + * @type {Object} + */ + Tone.FeedbackDelay.defaults = { 'delayTime': 0.25 }; + /** + * clean up + * @returns {Tone.FeedbackDelay} this + */ + Tone.FeedbackDelay.prototype.dispose = function () { + Tone.FeedbackEffect.prototype.dispose.call(this); + this._delayNode.dispose(); + this._delayNode = null; + this._writable(['delayTime']); + this.delayTime = null; + return this; + }; + return Tone.FeedbackDelay; + }); + Module(function (Tone) { + + /** + * an array of comb filter delay values from Freeverb implementation + * @static + * @private + * @type {Array} + */ + var combFilterTunings = [ + 1557 / 44100, + 1617 / 44100, + 1491 / 44100, + 1422 / 44100, + 1277 / 44100, + 1356 / 44100, + 1188 / 44100, + 1116 / 44100 + ]; + /** + * an array of allpass filter frequency values from Freeverb implementation + * @private + * @static + * @type {Array} + */ + var allpassFilterFrequencies = [ + 225, + 556, + 441, + 341 + ]; + /** + * @class Tone.Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html). + * Read more on reverb on [SoundOnSound](http://www.soundonsound.com/sos/may00/articles/reverb.htm). + * + * @extends {Tone.Effect} + * @constructor + * @param {NormalRange|Object} [roomSize] Correlated to the decay time. + * @param {Frequency} [dampening] The cutoff frequency of a lowpass filter as part + * of the reverb. + * @example + * var freeverb = new Tone.Freeverb().toMaster(); + * freeverb.dampening.value = 1000; + * //routing synth through the reverb + * var synth = new Tone.AMSynth().connect(freeverb); + */ + Tone.Freeverb = function () { + var options = this.optionsObject(arguments, [ + 'roomSize', + 'dampening' + ], Tone.Freeverb.defaults); + Tone.StereoEffect.call(this, options); + /** + * The roomSize value between. A larger roomSize + * will result in a longer decay. + * @type {NormalRange} + * @signal + */ + this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); + /** + * The amount of dampening of the reverberant signal. + * @type {Frequency} + * @signal + */ + this.dampening = new Tone.Signal(options.dampening, Tone.Type.Frequency); + /** + * the comb filters + * @type {Array} + * @private + */ + this._combFilters = []; + /** + * the allpass filters on the left + * @type {Array} + * @private + */ + this._allpassFiltersL = []; + /** + * the allpass filters on the right + * @type {Array} + * @private + */ + this._allpassFiltersR = []; + //make the allpass filters on the right + for (var l = 0; l < allpassFilterFrequencies.length; l++) { + var allpassL = this.context.createBiquadFilter(); + allpassL.type = 'allpass'; + allpassL.frequency.value = allpassFilterFrequencies[l]; + this._allpassFiltersL.push(allpassL); + } + //make the allpass filters on the left + for (var r = 0; r < allpassFilterFrequencies.length; r++) { + var allpassR = this.context.createBiquadFilter(); + allpassR.type = 'allpass'; + allpassR.frequency.value = allpassFilterFrequencies[r]; + this._allpassFiltersR.push(allpassR); + } + //make the comb filters + for (var c = 0; c < combFilterTunings.length; c++) { + var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]); + if (c < combFilterTunings.length / 2) { + this.effectSendL.chain(lfpf, this._allpassFiltersL[0]); + } else { + this.effectSendR.chain(lfpf, this._allpassFiltersR[0]); + } + this.roomSize.connect(lfpf.resonance); + this.dampening.connect(lfpf.dampening); + this._combFilters.push(lfpf); + } + //chain the allpass filters togetehr + this.connectSeries.apply(this, this._allpassFiltersL); + this.connectSeries.apply(this, this._allpassFiltersR); + this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL); + this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR); + this._readOnly([ + 'roomSize', + 'dampening' + ]); + }; + Tone.extend(Tone.Freeverb, Tone.StereoEffect); + /** + * @static + * @type {Object} + */ + Tone.Freeverb.defaults = { + 'roomSize': 0.7, + 'dampening': 3000 + }; + /** + * Clean up. + * @returns {Tone.Freeverb} this + */ + Tone.Freeverb.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + for (var al = 0; al < this._allpassFiltersL.length; al++) { + this._allpassFiltersL[al].disconnect(); + this._allpassFiltersL[al] = null; + } + this._allpassFiltersL = null; + for (var ar = 0; ar < this._allpassFiltersR.length; ar++) { + this._allpassFiltersR[ar].disconnect(); + this._allpassFiltersR[ar] = null; + } + this._allpassFiltersR = null; + for (var cf = 0; cf < this._combFilters.length; cf++) { + this._combFilters[cf].dispose(); + this._combFilters[cf] = null; + } + this._combFilters = null; + this._writable([ + 'roomSize', + 'dampening' + ]); + this.roomSize.dispose(); + this.roomSize = null; + this.dampening.dispose(); + this.dampening = null; + return this; + }; + return Tone.Freeverb; + }); + Module(function (Tone) { + + /** + * an array of the comb filter delay time values + * @private + * @static + * @type {Array} + */ + var combFilterDelayTimes = [ + 1687 / 25000, + 1601 / 25000, + 2053 / 25000, + 2251 / 25000 + ]; + /** + * the resonances of each of the comb filters + * @private + * @static + * @type {Array} + */ + var combFilterResonances = [ + 0.773, + 0.802, + 0.753, + 0.733 + ]; + /** + * the allpass filter frequencies + * @private + * @static + * @type {Array} + */ + var allpassFilterFreqs = [ + 347, + 113, + 37 + ]; + /** + * @class Tone.JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html) + * tuned by John Chowning in 1970. + * It is made up of three allpass filters and four Tone.FeedbackCombFilter. + * + * + * @extends {Tone.Effect} + * @constructor + * @param {NormalRange|Object} [roomSize] Coorelates to the decay time. + * @example + * var reverb = new Tone.JCReverb(0.4).connect(Tone.Master); + * var delay = new Tone.FeedbackDelay(0.5); + * //connecting the synth to reverb through delay + * var synth = new Tone.DuoSynth().chain(delay, reverb); + * synth.triggerAttackRelease("A4","8n"); + */ + Tone.JCReverb = function () { + var options = this.optionsObject(arguments, ['roomSize'], Tone.JCReverb.defaults); + Tone.StereoEffect.call(this, options); + /** + * room size control values between [0,1] + * @type {NormalRange} + * @signal + */ + this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); + /** + * scale the room size + * @type {Tone.Scale} + * @private + */ + this._scaleRoomSize = new Tone.Scale(-0.733, 0.197); + /** + * a series of allpass filters + * @type {Array} + * @private + */ + this._allpassFilters = []; + /** + * parallel feedback comb filters + * @type {Array} + * @private + */ + this._feedbackCombFilters = []; + //make the allpass filters + for (var af = 0; af < allpassFilterFreqs.length; af++) { + var allpass = this.context.createBiquadFilter(); + allpass.type = 'allpass'; + allpass.frequency.value = allpassFilterFreqs[af]; + this._allpassFilters.push(allpass); + } + //and the comb filters + for (var cf = 0; cf < combFilterDelayTimes.length; cf++) { + var fbcf = new Tone.FeedbackCombFilter(combFilterDelayTimes[cf], 0.1); + this._scaleRoomSize.connect(fbcf.resonance); + fbcf.resonance.value = combFilterResonances[cf]; + this._allpassFilters[this._allpassFilters.length - 1].connect(fbcf); + if (cf < combFilterDelayTimes.length / 2) { + fbcf.connect(this.effectReturnL); + } else { + fbcf.connect(this.effectReturnR); + } + this._feedbackCombFilters.push(fbcf); + } + //chain the allpass filters together + this.roomSize.connect(this._scaleRoomSize); + this.connectSeries.apply(this, this._allpassFilters); + this.effectSendL.connect(this._allpassFilters[0]); + this.effectSendR.connect(this._allpassFilters[0]); + this._readOnly(['roomSize']); + }; + Tone.extend(Tone.JCReverb, Tone.StereoEffect); + /** + * the default values + * @static + * @const + * @type {Object} + */ + Tone.JCReverb.defaults = { 'roomSize': 0.5 }; + /** + * Clean up. + * @returns {Tone.JCReverb} this + */ + Tone.JCReverb.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + for (var apf = 0; apf < this._allpassFilters.length; apf++) { + this._allpassFilters[apf].disconnect(); + this._allpassFilters[apf] = null; + } + this._allpassFilters = null; + for (var fbcf = 0; fbcf < this._feedbackCombFilters.length; fbcf++) { + this._feedbackCombFilters[fbcf].dispose(); + this._feedbackCombFilters[fbcf] = null; + } + this._feedbackCombFilters = null; + this._writable(['roomSize']); + this.roomSize.dispose(); + this.roomSize = null; + this._scaleRoomSize.dispose(); + this._scaleRoomSize = null; + return this; + }; + return Tone.JCReverb; + }); + Module(function (Tone) { + + /** + * @class Mid/Side processing separates the the 'mid' signal + * (which comes out of both the left and the right channel) + * and the 'side' (which only comes out of the the side channels) + * and effects them separately before being recombined. + * Applies a Mid/Side seperation and recombination. + * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). + *

+ * This is a base-class for Mid/Side Effects. + * + * @extends {Tone.Effect} + * @constructor + */ + Tone.MidSideEffect = function () { + Tone.Effect.apply(this, arguments); + /** + * The mid/side split + * @type {Tone.MidSideSplit} + * @private + */ + this._midSideSplit = new Tone.MidSideSplit(); + /** + * The mid/side merge + * @type {Tone.MidSideMerge} + * @private + */ + this._midSideMerge = new Tone.MidSideMerge(); + /** + * The mid send. Connect to mid processing + * @type {Tone.Expr} + * @private + */ + this.midSend = this._midSideSplit.mid; + /** + * The side send. Connect to side processing + * @type {Tone.Expr} + * @private + */ + this.sideSend = this._midSideSplit.side; + /** + * The mid return connection + * @type {GainNode} + * @private + */ + this.midReturn = this._midSideMerge.mid; + /** + * The side return connection + * @type {GainNode} + * @private + */ + this.sideReturn = this._midSideMerge.side; + //the connections + this.effectSend.connect(this._midSideSplit); + this._midSideMerge.connect(this.effectReturn); + }; + Tone.extend(Tone.MidSideEffect, Tone.Effect); + /** + * Clean up. + * @returns {Tone.MidSideEffect} this + */ + Tone.MidSideEffect.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._midSideSplit.dispose(); + this._midSideSplit = null; + this._midSideMerge.dispose(); + this._midSideMerge = null; + this.midSend = null; + this.sideSend = null; + this.midReturn = null; + this.sideReturn = null; + return this; + }; + return Tone.MidSideEffect; + }); + Module(function (Tone) { + + /** + * @class Tone.Phaser is a phaser effect. Phasers work by changing the phase + * of different frequency components of an incoming signal. Read more on + * [Wikipedia](https://en.wikipedia.org/wiki/Phaser_(effect)). + * Inspiration for this phaser comes from [Tuna.js](https://github.com/Dinahmoe/tuna/). + * + * @extends {Tone.StereoEffect} + * @constructor + * @param {Frequency|Object} [frequency] The speed of the phasing. + * @param {number} [octaves] The octaves of the effect. + * @param {Frequency} [baseFrequency] The base frequency of the filters. + * @example + * var phaser = new Tone.Phaser({ + * "frequency" : 15, + * "octaves" : 5, + * "baseFrequency" : 1000 + * }).toMaster(); + * var synth = new Tone.FMSynth().connect(phaser); + * synth.triggerAttackRelease("E3", "2n"); + */ + Tone.Phaser = function () { + //set the defaults + var options = this.optionsObject(arguments, [ + 'frequency', + 'octaves', + 'baseFrequency' + ], Tone.Phaser.defaults); + Tone.StereoEffect.call(this, options); + /** + * the lfo which controls the frequency on the left side + * @type {Tone.LFO} + * @private + */ + this._lfoL = new Tone.LFO(options.frequency, 0, 1); + /** + * the lfo which controls the frequency on the right side + * @type {Tone.LFO} + * @private + */ + this._lfoR = new Tone.LFO(options.frequency, 0, 1); + this._lfoR.phase = 180; + /** + * the base modulation frequency + * @type {number} + * @private + */ + this._baseFrequency = options.baseFrequency; + /** + * the octaves of the phasing + * @type {number} + * @private + */ + this._octaves = options.octaves; + /** + * The quality factor of the filters + * @type {Positive} + * @signal + */ + this.Q = new Tone.Signal(options.Q, Tone.Type.Positive); + /** + * the array of filters for the left side + * @type {Array} + * @private + */ + this._filtersL = this._makeFilters(options.stages, this._lfoL, this.Q); + /** + * the array of filters for the left side + * @type {Array} + * @private + */ + this._filtersR = this._makeFilters(options.stages, this._lfoR, this.Q); + /** + * the frequency of the effect + * @type {Tone.Signal} + */ + this.frequency = this._lfoL.frequency; + this.frequency.value = options.frequency; + //connect them up + this.effectSendL.connect(this._filtersL[0]); + this.effectSendR.connect(this._filtersR[0]); + this._filtersL[options.stages - 1].connect(this.effectReturnL); + this._filtersR[options.stages - 1].connect(this.effectReturnR); + //control the frequency with one LFO + this._lfoL.frequency.connect(this._lfoR.frequency); + //set the options + this.baseFrequency = options.baseFrequency; + this.octaves = options.octaves; + //start the lfo + this._lfoL.start(); + this._lfoR.start(); + this._readOnly([ + 'frequency', + 'Q' + ]); + }; + Tone.extend(Tone.Phaser, Tone.StereoEffect); + /** + * defaults + * @static + * @type {object} + */ + Tone.Phaser.defaults = { + 'frequency': 0.5, + 'octaves': 3, + 'stages': 10, + 'Q': 10, + 'baseFrequency': 350 + }; + /** + * @param {number} stages + * @returns {Array} the number of filters all connected together + * @private + */ + Tone.Phaser.prototype._makeFilters = function (stages, connectToFreq, Q) { + var filters = new Array(stages); + //make all the filters + for (var i = 0; i < stages; i++) { + var filter = this.context.createBiquadFilter(); + filter.type = 'allpass'; + Q.connect(filter.Q); + connectToFreq.connect(filter.frequency); + filters[i] = filter; + } + this.connectSeries.apply(this, filters); + return filters; + }; + /** + * The number of octaves the phase goes above + * the baseFrequency + * @memberOf Tone.Phaser# + * @type {Positive} + * @name octaves + */ + Object.defineProperty(Tone.Phaser.prototype, 'octaves', { + get: function () { + return this._octaves; + }, + set: function (octaves) { + this._octaves = octaves; + var max = this._baseFrequency * Math.pow(2, octaves); + this._lfoL.max = max; + this._lfoR.max = max; + } + }); + /** + * The the base frequency of the filters. + * @memberOf Tone.Phaser# + * @type {number} + * @name baseFrequency + */ + Object.defineProperty(Tone.Phaser.prototype, 'baseFrequency', { + get: function () { + return this._baseFrequency; + }, + set: function (freq) { + this._baseFrequency = freq; + this._lfoL.min = freq; + this._lfoR.min = freq; + this.octaves = this._octaves; + } + }); + /** + * clean up + * @returns {Tone.Phaser} this + */ + Tone.Phaser.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'Q' + ]); + this.Q.dispose(); + this.Q = null; + this._lfoL.dispose(); + this._lfoL = null; + this._lfoR.dispose(); + this._lfoR = null; + for (var i = 0; i < this._filtersL.length; i++) { + this._filtersL[i].disconnect(); + this._filtersL[i] = null; + } + this._filtersL = null; + for (var j = 0; j < this._filtersR.length; j++) { + this._filtersR[j].disconnect(); + this._filtersR[j] = null; + } + this._filtersR = null; + this.frequency = null; + return this; + }; + return Tone.Phaser; + }); + Module(function (Tone) { + + /** + * @class Tone.PingPongDelay is a feedback delay effect where the echo is heard + * first in one channel and next in the opposite channel. In a stereo + * system these are the right and left channels. + * PingPongDelay in more simplified terms is two Tone.FeedbackDelays + * with independent delay values. Each delay is routed to one channel + * (left or right), and the channel triggered second will always + * trigger at the same interval after the first. + * + * @constructor + * @extends {Tone.StereoXFeedbackEffect} + * @param {Time|Object} [delayTime] The delayTime between consecutive echos. + * @param {NormalRange=} feedback The amount of the effected signal which + * is fed back through the delay. + * @example + * var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster(); + * var drum = new Tone.DrumSynth().connect(pingPong); + * drum.triggerAttackRelease("C4", "32n"); + */ + Tone.PingPongDelay = function () { + var options = this.optionsObject(arguments, [ + 'delayTime', + 'feedback' + ], Tone.PingPongDelay.defaults); + Tone.StereoXFeedbackEffect.call(this, options); + /** + * the delay node on the left side + * @type {Tone.Delay} + * @private + */ + this._leftDelay = new Tone.Delay(0, options.maxDelayTime); + /** + * the delay node on the right side + * @type {Tone.Delay} + * @private + */ + this._rightDelay = new Tone.Delay(0, options.maxDelayTime); + /** + * the predelay on the right side + * @type {Tone.Delay} + * @private + */ + this._rightPreDelay = new Tone.Delay(0, options.maxDelayTime); + /** + * the delay time signal + * @type {Time} + * @signal + */ + this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); + //connect it up + this.effectSendL.chain(this._leftDelay, this.effectReturnL); + this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR); + this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime); + //rearranged the feedback to be after the rightPreDelay + this._feedbackLR.disconnect(); + this._feedbackLR.connect(this._rightDelay); + this._readOnly(['delayTime']); + }; + Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect); + /** + * @static + * @type {Object} + */ + Tone.PingPongDelay.defaults = { + 'delayTime': 0.25, + 'maxDelayTime': 1 + }; + /** + * Clean up. + * @returns {Tone.PingPongDelay} this + */ + Tone.PingPongDelay.prototype.dispose = function () { + Tone.StereoXFeedbackEffect.prototype.dispose.call(this); + this._leftDelay.dispose(); + this._leftDelay = null; + this._rightDelay.dispose(); + this._rightDelay = null; + this._rightPreDelay.dispose(); + this._rightPreDelay = null; + this._writable(['delayTime']); + this.delayTime.dispose(); + this.delayTime = null; + return this; + }; + return Tone.PingPongDelay; + }); + Module(function (Tone) { + + /** + * @class Tone.PitchShift does near-realtime pitch shifting to the incoming signal. + * The effect is achieved by speeding up or slowing down the delayTime + * of a DelayNode using a sawtooth wave. + * Algorithm found in [this pdf](http://dsp-book.narod.ru/soundproc.pdf). + * Additional reference by [Miller Pucket](http://msp.ucsd.edu/techniques/v0.11/book-html/node115.html). + * + * @extends {Tone.FeedbackEffect} + * @param {Interval=} pitch The interval to transpose the incoming signal by. + */ + Tone.PitchShift = function () { + var options = this.optionsObject(arguments, ['pitch'], Tone.PitchShift.defaults); + Tone.FeedbackEffect.call(this, options); + /** + * The pitch signal + * @type {Tone.Signal} + * @private + */ + this._frequency = new Tone.Signal(0); + /** + * Uses two DelayNodes to cover up the jump in + * the sawtooth wave. + * @type {DelayNode} + * @private + */ + this._delayA = new Tone.Delay(0, 1); + /** + * The first LFO. + * @type {Tone.LFO} + * @private + */ + this._lfoA = new Tone.LFO({ + 'min': 0, + 'max': 0.1, + 'type': 'sawtooth' + }).connect(this._delayA.delayTime); + /** + * The second DelayNode + * @type {DelayNode} + * @private + */ + this._delayB = new Tone.Delay(0, 1); + /** + * The first LFO. + * @type {Tone.LFO} + * @private + */ + this._lfoB = new Tone.LFO({ + 'min': 0, + 'max': 0.1, + 'type': 'sawtooth', + 'phase': 180 + }).connect(this._delayB.delayTime); + /** + * Crossfade quickly between the two delay lines + * to cover up the jump in the sawtooth wave + * @type {Tone.CrossFade} + * @private + */ + this._crossFade = new Tone.CrossFade(); + /** + * LFO which alternates between the two + * delay lines to cover up the disparity in the + * sawtooth wave. + * @type {Tone.LFO} + * @private + */ + this._crossFadeLFO = new Tone.LFO({ + 'min': 0, + 'max': 1, + 'type': 'triangle', + 'phase': 90 + }).connect(this._crossFade.fade); + /** + * The delay node + * @type {Tone.Delay} + * @private + */ + this._feedbackDelay = new Tone.Delay(options.delayTime); + /** + * The amount of delay on the input signal + * @type {Time} + * @signal + */ + this.delayTime = this._feedbackDelay.delayTime; + this._readOnly('delayTime'); + /** + * Hold the current pitch + * @type {Number} + * @private + */ + this._pitch = options.pitch; + /** + * Hold the current windowSize + * @type {Number} + * @private + */ + this._windowSize = options.windowSize; + //connect the two delay lines up + this._delayA.connect(this._crossFade.a); + this._delayB.connect(this._crossFade.b); + //connect the frequency + this._frequency.fan(this._lfoA.frequency, this._lfoB.frequency, this._crossFadeLFO.frequency); + //route the input + this.effectSend.fan(this._delayA, this._delayB); + this._crossFade.chain(this._feedbackDelay, this.effectReturn); + //start the LFOs at the same time + var now = this.now(); + this._lfoA.start(now); + this._lfoB.start(now); + this._crossFadeLFO.start(now); + //set the initial value + this.windowSize = this._windowSize; + }; + Tone.extend(Tone.PitchShift, Tone.FeedbackEffect); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.PitchShift.defaults = { + 'pitch': 0, + 'windowSize': 0.1, + 'delayTime': 0, + 'feedback': 0 + }; + /** + * Repitch the incoming signal by some interval (measured + * in semi-tones). + * @memberOf Tone.PitchShift# + * @type {Interval} + * @name pitch + * @example + * pitchShift.pitch = -12; //down one octave + * pitchShift.pitch = 7; //up a fifth + */ + Object.defineProperty(Tone.PitchShift.prototype, 'pitch', { + get: function () { + return this._pitch; + }, + set: function (interval) { + this._pitch = interval; + var factor = 0; + if (interval < 0) { + this._lfoA.min = 0; + this._lfoA.max = this._windowSize; + this._lfoB.min = 0; + this._lfoB.max = this._windowSize; + factor = this.intervalToFrequencyRatio(interval - 1) + 1; + } else { + this._lfoA.min = this._windowSize; + this._lfoA.max = 0; + this._lfoB.min = this._windowSize; + this._lfoB.max = 0; + factor = this.intervalToFrequencyRatio(interval) - 1; + } + this._frequency.value = factor * (1.2 / this._windowSize); + } + }); + /** + * The window size corresponds roughly to the sample length in a looping sampler. + * Smaller values are desirable for a less noticeable delay time of the pitch shifted + * signal, but larger values will result in smoother pitch shifting for larger intervals. + * A nominal range of 0.03 to 0.1 is recommended. + * @memberOf Tone.PitchShift# + * @type {Time} + * @name windowSize + * @example + * pitchShift.windowSize = 0.1; + */ + Object.defineProperty(Tone.PitchShift.prototype, 'windowSize', { + get: function () { + return this._windowSize; + }, + set: function (size) { + this._windowSize = this.toSeconds(size); + this.pitch = this._pitch; + } + }); + /** + * Clean up. + * @return {Tone.PitchShift} this + */ + Tone.PitchShift.prototype.dispose = function () { + Tone.FeedbackEffect.prototype.dispose.call(this); + this._frequency.dispose(); + this._frequency = null; + this._delayA.disconnect(); + this._delayA = null; + this._delayB.disconnect(); + this._delayB = null; + this._lfoA.dispose(); + this._lfoA = null; + this._lfoB.dispose(); + this._lfoB = null; + this._crossFade.dispose(); + this._crossFade = null; + this._crossFadeLFO.dispose(); + this._crossFadeLFO = null; + this._writable('delayTime'); + this._feedbackDelay.dispose(); + this._feedbackDelay = null; + this.delayTime = null; + return this; + }; + return Tone.PitchShift; + }); + Module(function (Tone) { + + /** + * @class Base class for stereo feedback effects where the effectReturn + * is fed back into the same channel. + * + * @constructor + * @extends {Tone.FeedbackEffect} + */ + Tone.StereoFeedbackEffect = function () { + var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); + Tone.StereoEffect.call(this, options); + /** + * controls the amount of feedback + * @type {NormalRange} + * @signal + */ + this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); + /** + * the left side feeback + * @type {Tone.Gain} + * @private + */ + this._feedbackL = new Tone.Gain(); + /** + * the right side feeback + * @type {Tone.Gain} + * @private + */ + this._feedbackR = new Tone.Gain(); + //connect it up + this.effectReturnL.chain(this._feedbackL, this.effectSendL); + this.effectReturnR.chain(this._feedbackR, this.effectSendR); + this.feedback.fan(this._feedbackL.gain, this._feedbackR.gain); + this._readOnly(['feedback']); + }; + Tone.extend(Tone.StereoFeedbackEffect, Tone.FeedbackEffect); + /** + * clean up + * @returns {Tone.StereoFeedbackEffect} this + */ + Tone.StereoFeedbackEffect.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + this._writable(['feedback']); + this.feedback.dispose(); + this.feedback = null; + this._feedbackL.dispose(); + this._feedbackL = null; + this._feedbackR.dispose(); + this._feedbackR = null; + return this; + }; + return Tone.StereoFeedbackEffect; + }); + Module(function (Tone) { + + /** + * @class Applies a width factor to the mid/side seperation. + * 0 is all mid and 1 is all side. + * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). + *

+ * + * Mid *= 2*(1-width)
+ * Side *= 2*width + *
+ * + * @extends {Tone.MidSideEffect} + * @constructor + * @param {NormalRange|Object} [width] The stereo width. A width of 0 is mono and 1 is stereo. 0.5 is no change. + */ + Tone.StereoWidener = function () { + var options = this.optionsObject(arguments, ['width'], Tone.StereoWidener.defaults); + Tone.MidSideEffect.call(this, options); + /** + * The width control. 0 = 100% mid. 1 = 100% side. 0.5 = no change. + * @type {NormalRange} + * @signal + */ + this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); + /** + * Mid multiplier + * @type {Tone.Expr} + * @private + */ + this._midMult = new Tone.Expr('$0 * ($1 * (1 - $2))'); + /** + * Side multiplier + * @type {Tone.Expr} + * @private + */ + this._sideMult = new Tone.Expr('$0 * ($1 * $2)'); + /** + * constant output of 2 + * @type {Tone} + * @private + */ + this._two = new Tone.Signal(2); + //the mid chain + this._two.connect(this._midMult, 0, 1); + this.width.connect(this._midMult, 0, 2); + //the side chain + this._two.connect(this._sideMult, 0, 1); + this.width.connect(this._sideMult, 0, 2); + //connect it to the effect send/return + this.midSend.chain(this._midMult, this.midReturn); + this.sideSend.chain(this._sideMult, this.sideReturn); + this._readOnly(['width']); + }; + Tone.extend(Tone.StereoWidener, Tone.MidSideEffect); + /** + * the default values + * @static + * @type {Object} + */ + Tone.StereoWidener.defaults = { 'width': 0.5 }; + /** + * Clean up. + * @returns {Tone.StereoWidener} this + */ + Tone.StereoWidener.prototype.dispose = function () { + Tone.MidSideEffect.prototype.dispose.call(this); + this._writable(['width']); + this.width.dispose(); + this.width = null; + this._midMult.dispose(); + this._midMult = null; + this._sideMult.dispose(); + this._sideMult = null; + this._two.dispose(); + this._two = null; + return this; + }; + return Tone.StereoWidener; + }); + Module(function (Tone) { + + /** + * @class Tone.Tremolo modulates the amplitude of an incoming signal using a Tone.LFO. + * The type, frequency, and depth of the LFO is controllable. + * + * @extends {Tone.StereoEffect} + * @constructor + * @param {Frequency} [frequency] The rate of the effect. + * @param {NormalRange} [depth] The depth of the effect. + * @example + * //create a tremolo and start it's LFO + * var tremolo = new Tone.Tremolo(9, 0.75).toMaster().start(); + * //route an oscillator through the tremolo and start it + * var oscillator = new Tone.Oscillator().connect(tremolo).start(); + */ + Tone.Tremolo = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'depth' + ], Tone.Tremolo.defaults); + Tone.StereoEffect.call(this, options); + /** + * The tremelo LFO in the left channel + * @type {Tone.LFO} + * @private + */ + this._lfoL = new Tone.LFO({ + 'phase': options.spread, + 'min': 1, + 'max': 0 + }); + /** + * The tremelo LFO in the left channel + * @type {Tone.LFO} + * @private + */ + this._lfoR = new Tone.LFO({ + 'phase': options.spread, + 'min': 1, + 'max': 0 + }); + /** + * Where the gain is multiplied + * @type {Tone.Gain} + * @private + */ + this._amplitudeL = new Tone.Gain(); + /** + * Where the gain is multiplied + * @type {Tone.Gain} + * @private + */ + this._amplitudeR = new Tone.Gain(); + /** + * The frequency of the tremolo. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The depth of the effect. A depth of 0, has no effect + * on the amplitude, and a depth of 1 makes the amplitude + * modulate fully between 0 and 1. + * @type {NormalRange} + * @signal + */ + this.depth = new Tone.Signal(options.depth, Tone.Type.NormalRange); + this._readOnly([ + 'frequency', + 'depth' + ]); + this.effectSendL.chain(this._amplitudeL, this.effectReturnL); + this.effectSendR.chain(this._amplitudeR, this.effectReturnR); + this._lfoL.connect(this._amplitudeL.gain); + this._lfoR.connect(this._amplitudeR.gain); + this.frequency.fan(this._lfoL.frequency, this._lfoR.frequency); + this.depth.fan(this._lfoR.amplitude, this._lfoL.amplitude); + this.type = options.type; + this.spread = options.spread; + }; + Tone.extend(Tone.Tremolo, Tone.StereoEffect); + /** + * @static + * @const + * @type {Object} + */ + Tone.Tremolo.defaults = { + 'frequency': 10, + 'type': 'sine', + 'depth': 0.5, + 'spread': 180 + }; + /** + * Start the tremolo. + * @param {Time} [time=now] When the tremolo begins. + * @returns {Tone.Tremolo} this + */ + Tone.Tremolo.prototype.start = function (time) { + this._lfoL.start(time); + this._lfoR.start(time); + return this; + }; + /** + * Stop the tremolo. + * @param {Time} [time=now] When the tremolo stops. + * @returns {Tone.Tremolo} this + */ + Tone.Tremolo.prototype.stop = function (time) { + this._lfoL.stop(time); + this._lfoR.stop(time); + return this; + }; + /** + * Sync the effect to the transport. + * @param {Time} [delay=0] Delay time before starting the effect after the + * Transport has started. + * @returns {Tone.AutoFilter} this + */ + Tone.Tremolo.prototype.sync = function (delay) { + this._lfoL.sync(delay); + this._lfoR.sync(delay); + return this; + }; + /** + * Unsync the filter from the transport + * @returns {Tone.Tremolo} this + */ + Tone.Tremolo.prototype.unsync = function () { + this._lfoL.unsync(); + this._lfoR.unsync(); + return this; + }; + /** + * The Tremolo's oscillator type. + * @memberOf Tone.Tremolo# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.Tremolo.prototype, 'type', { + get: function () { + return this._lfoL.type; + }, + set: function (type) { + this._lfoL.type = type; + this._lfoR.type = type; + } + }); + /** + * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. + * When set to 180, LFO's will be panned hard left and right respectively. + * @memberOf Tone.Tremolo# + * @type {Degrees} + * @name spread + */ + Object.defineProperty(Tone.Tremolo.prototype, 'spread', { + get: function () { + return this._lfoR.phase - this._lfoL.phase; //180 + }, + set: function (spread) { + this._lfoL.phase = 90 - spread / 2; + this._lfoR.phase = spread / 2 + 90; + } + }); + /** + * clean up + * @returns {Tone.Tremolo} this + */ + Tone.Tremolo.prototype.dispose = function () { + Tone.StereoEffect.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'depth' + ]); + this._lfoL.dispose(); + this._lfoL = null; + this._lfoR.dispose(); + this._lfoR = null; + this._amplitudeL.dispose(); + this._amplitudeL = null; + this._amplitudeR.dispose(); + this._amplitudeR = null; + this.frequency = null; + this.depth = null; + return this; + }; + return Tone.Tremolo; + }); + Module(function (Tone) { + + /** + * @class A Vibrato effect composed of a Tone.Delay and a Tone.LFO. The LFO + * modulates the delayTime of the delay, causing the pitch to rise + * and fall. + * @extends {Tone.Effect} + * @param {Frequency} frequency The frequency of the vibrato. + * @param {NormalRange} depth The amount the pitch is modulated. + */ + Tone.Vibrato = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'depth' + ], Tone.Vibrato.defaults); + Tone.Effect.call(this, options); + /** + * The delay node used for the vibrato effect + * @type {Tone.Delay} + * @private + */ + this._delayNode = new Tone.Delay(0, options.maxDelay); + /** + * The LFO used to control the vibrato + * @type {Tone.LFO} + * @private + */ + this._lfo = new Tone.LFO({ + 'type': options.type, + 'min': 0, + 'max': options.maxDelay, + 'frequency': options.frequency, + 'phase': -90 //offse the phase so the resting position is in the center + }).start().connect(this._delayNode.delayTime); + /** + * The frequency of the vibrato + * @type {Frequency} + * @signal + */ + this.frequency = this._lfo.frequency; + /** + * The depth of the vibrato. + * @type {NormalRange} + * @signal + */ + this.depth = this._lfo.amplitude; + this.depth.value = options.depth; + this._readOnly([ + 'frequency', + 'depth' + ]); + this.effectSend.chain(this._delayNode, this.effectReturn); + }; + Tone.extend(Tone.Vibrato, Tone.Effect); + /** + * The defaults + * @type {Object} + * @const + */ + Tone.Vibrato.defaults = { + 'maxDelay': 0.005, + 'frequency': 5, + 'depth': 0.1, + 'type': 'sine' + }; + /** + * Type of oscillator attached to the Vibrato. + * @memberOf Tone.Vibrato# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.Vibrato.prototype, 'type', { + get: function () { + return this._lfo.type; + }, + set: function (type) { + this._lfo.type = type; + } + }); + /** + * Clean up. + * @returns {Tone.Vibrato} this + */ + Tone.Vibrato.prototype.dispose = function () { + Tone.Effect.prototype.dispose.call(this); + this._delayNode.dispose(); + this._delayNode = null; + this._lfo.dispose(); + this._lfo = null; + this._writable([ + 'frequency', + 'depth' + ]); + this.frequency = null; + this.depth = null; + }; + return Tone.Vibrato; + }); + Module(function (Tone) { + + /** + * @class Tone.Event abstracts away Tone.Transport.schedule and provides a schedulable + * callback for a single or repeatable events along the timeline. + * + * @extends {Tone} + * @param {function} callback The callback to invoke at the time. + * @param {*} value The value or values which should be passed to + * the callback function on invocation. + * @example + * var chord = new Tone.Event(function(time, chord){ + * //the chord as well as the exact time of the event + * //are passed in as arguments to the callback function + * }, ["D4", "E4", "F4"]); + * //start the chord at the beginning of the transport timeline + * chord.start(); + * //loop it every measure for 8 measures + * chord.loop = 8; + * chord.loopEnd = "1m"; + */ + Tone.Event = function () { + var options = this.optionsObject(arguments, [ + 'callback', + 'value' + ], Tone.Event.defaults); + /** + * Loop value + * @type {Boolean|Positive} + * @private + */ + this._loop = options.loop; + /** + * The callback to invoke. + * @type {Function} + */ + this.callback = options.callback; + /** + * The value which is passed to the + * callback function. + * @type {*} + * @private + */ + this.value = options.value; + /** + * When the note is scheduled to start. + * @type {Number} + * @private + */ + this._loopStart = this.toTicks(options.loopStart); + /** + * When the note is scheduled to start. + * @type {Number} + * @private + */ + this._loopEnd = this.toTicks(options.loopEnd); + /** + * Tracks the scheduled events + * @type {Tone.TimelineState} + * @private + */ + this._state = new Tone.TimelineState(Tone.State.Stopped); + /** + * The playback speed of the note. A speed of 1 + * is no change. + * @private + * @type {Positive} + */ + this._playbackRate = 1; + /** + * A delay time from when the event is scheduled to start + * @type {Ticks} + * @private + */ + this._startOffset = 0; + /** + * The probability that the callback will be invoked + * at the scheduled time. + * @type {NormalRange} + * @example + * //the callback will be invoked 50% of the time + * event.probability = 0.5; + */ + this.probability = options.probability; + /** + * If set to true, will apply small (+/-0.02 seconds) random variation + * to the callback time. If the value is given as a time, it will randomize + * by that amount. + * @example + * event.humanize = true; + * @type {Boolean|Time} + */ + this.humanize = options.humanize; + /** + * If mute is true, the callback won't be + * invoked. + * @type {Boolean} + */ + this.mute = options.mute; + //set the initial values + this.playbackRate = options.playbackRate; + }; + Tone.extend(Tone.Event); + /** + * The default values + * @type {Object} + * @const + */ + Tone.Event.defaults = { + 'callback': Tone.noOp, + 'loop': false, + 'loopEnd': '1m', + 'loopStart': 0, + 'playbackRate': 1, + 'value': null, + 'probability': 1, + 'mute': false, + 'humanize': false + }; + /** + * Reschedule all of the events along the timeline + * with the updated values. + * @param {Time} after Only reschedules events after the given time. + * @return {Tone.Event} this + * @private + */ + Tone.Event.prototype._rescheduleEvents = function (after) { + //if no argument is given, schedules all of the events + after = this.defaultArg(after, -1); + this._state.forEachFrom(after, function (event) { + var duration; + if (event.state === Tone.State.Started) { + if (!this.isUndef(event.id)) { + Tone.Transport.clear(event.id); + } + var startTick = event.time + Math.round(this.startOffset / this._playbackRate); + if (this._loop) { + duration = Infinity; + if (this.isNumber(this._loop)) { + duration = this._loop * this._getLoopDuration(); + } + var nextEvent = this._state.getAfter(startTick); + if (nextEvent !== null) { + duration = Math.min(duration, nextEvent.time - startTick); + } + if (duration !== Infinity) { + //schedule a stop since it's finite duration + this._state.setStateAtTime(Tone.State.Stopped, startTick + duration + 1); + duration = Tone.Time(duration, 'i'); + } + var interval = Tone.Time(this._getLoopDuration(), 'i'); + event.id = Tone.Transport.scheduleRepeat(this._tick.bind(this), interval, Tone.TransportTime(startTick, 'i'), duration); + } else { + event.id = Tone.Transport.schedule(this._tick.bind(this), startTick + 'i'); + } + } + }.bind(this)); + return this; + }; + /** + * Returns the playback state of the note, either "started" or "stopped". + * @type {String} + * @readOnly + * @memberOf Tone.Event# + * @name state + */ + Object.defineProperty(Tone.Event.prototype, 'state', { + get: function () { + return this._state.getValueAtTime(Tone.Transport.ticks); + } + }); + /** + * The start from the scheduled start time + * @type {Ticks} + * @memberOf Tone.Event# + * @name startOffset + * @private + */ + Object.defineProperty(Tone.Event.prototype, 'startOffset', { + get: function () { + return this._startOffset; + }, + set: function (offset) { + this._startOffset = offset; + } + }); + /** + * Start the note at the given time. + * @param {TimelinePosition} time When the note should start. + * @return {Tone.Event} this + */ + Tone.Event.prototype.start = function (time) { + time = this.toTicks(time); + if (this._state.getValueAtTime(time) === Tone.State.Stopped) { + this._state.add({ + 'state': Tone.State.Started, + 'time': time, + 'id': undefined + }); + this._rescheduleEvents(time); + } + return this; + }; + /** + * Stop the Event at the given time. + * @param {TimelinePosition} time When the note should stop. + * @return {Tone.Event} this + */ + Tone.Event.prototype.stop = function (time) { + this.cancel(time); + time = this.toTicks(time); + if (this._state.getValueAtTime(time) === Tone.State.Started) { + this._state.setStateAtTime(Tone.State.Stopped, time); + var previousEvent = this._state.getBefore(time); + var reschedulTime = time; + if (previousEvent !== null) { + reschedulTime = previousEvent.time; + } + this._rescheduleEvents(reschedulTime); + } + return this; + }; + /** + * Cancel all scheduled events greater than or equal to the given time + * @param {TimelinePosition} [time=0] The time after which events will be cancel. + * @return {Tone.Event} this + */ + Tone.Event.prototype.cancel = function (time) { + time = this.defaultArg(time, -Infinity); + time = this.toTicks(time); + this._state.forEachFrom(time, function (event) { + Tone.Transport.clear(event.id); + }); + this._state.cancel(time); + return this; + }; + /** + * The callback function invoker. Also + * checks if the Event is done playing + * @param {Number} time The time of the event in seconds + * @private + */ + Tone.Event.prototype._tick = function (time) { + if (!this.mute && this._state.getValueAtTime(Tone.Transport.ticks) === Tone.State.Started) { + if (this.probability < 1 && Math.random() > this.probability) { + return; + } + if (this.humanize) { + var variation = 0.02; + if (!this.isBoolean(this.humanize)) { + variation = this.toSeconds(this.humanize); + } + time += (Math.random() * 2 - 1) * variation; + } + this.callback(time, this.value); + } + }; + /** + * Get the duration of the loop. + * @return {Ticks} + * @private + */ + Tone.Event.prototype._getLoopDuration = function () { + return Math.round((this._loopEnd - this._loopStart) / this._playbackRate); + }; + /** + * If the note should loop or not + * between Tone.Event.loopStart and + * Tone.Event.loopEnd. An integer + * value corresponds to the number of + * loops the Event does after it starts. + * @memberOf Tone.Event# + * @type {Boolean|Positive} + * @name loop + */ + Object.defineProperty(Tone.Event.prototype, 'loop', { + get: function () { + return this._loop; + }, + set: function (loop) { + this._loop = loop; + this._rescheduleEvents(); + } + }); + /** + * The playback rate of the note. Defaults to 1. + * @memberOf Tone.Event# + * @type {Positive} + * @name playbackRate + * @example + * note.loop = true; + * //repeat the note twice as fast + * note.playbackRate = 2; + */ + Object.defineProperty(Tone.Event.prototype, 'playbackRate', { + get: function () { + return this._playbackRate; + }, + set: function (rate) { + this._playbackRate = rate; + this._rescheduleEvents(); + } + }); + /** + * The loopEnd point is the time the event will loop + * if Tone.Event.loop is true. + * @memberOf Tone.Event# + * @type {TransportTime} + * @name loopEnd + */ + Object.defineProperty(Tone.Event.prototype, 'loopEnd', { + get: function () { + return Tone.TransportTime(this._loopEnd, 'i').toNotation(); + }, + set: function (loopEnd) { + this._loopEnd = this.toTicks(loopEnd); + if (this._loop) { + this._rescheduleEvents(); + } + } + }); + /** + * The time when the loop should start. + * @memberOf Tone.Event# + * @type {TransportTime} + * @name loopStart + */ + Object.defineProperty(Tone.Event.prototype, 'loopStart', { + get: function () { + return Tone.TransportTime(this._loopStart, 'i').toNotation(); + }, + set: function (loopStart) { + this._loopStart = this.toTicks(loopStart); + if (this._loop) { + this._rescheduleEvents(); + } + } + }); + /** + * The current progress of the loop interval. + * Returns 0 if the event is not started yet or + * it is not set to loop. + * @memberOf Tone.Event# + * @type {NormalRange} + * @name progress + * @readOnly + */ + Object.defineProperty(Tone.Event.prototype, 'progress', { + get: function () { + if (this._loop) { + var ticks = Tone.Transport.ticks; + var lastEvent = this._state.get(ticks); + if (lastEvent !== null && lastEvent.state === Tone.State.Started) { + var loopDuration = this._getLoopDuration(); + var progress = (ticks - lastEvent.time) % loopDuration; + return progress / loopDuration; + } else { + return 0; + } + } else { + return 0; + } + } + }); + /** + * Clean up + * @return {Tone.Event} this + */ + Tone.Event.prototype.dispose = function () { + this.cancel(); + this._state.dispose(); + this._state = null; + this.callback = null; + this.value = null; + }; + return Tone.Event; + }); + Module(function (Tone) { + /** + * @class Tone.Loop creates a looped callback at the + * specified interval. The callback can be + * started, stopped and scheduled along + * the Transport's timeline. + * @example + * var loop = new Tone.Loop(function(time){ + * //triggered every eighth note. + * console.log(time); + * }, "8n").start(0); + * Tone.Transport.start(); + * @extends {Tone} + * @param {Function} callback The callback to invoke with the event. + * @param {Time} interval The time between successive callback calls. + */ + Tone.Loop = function () { + var options = this.optionsObject(arguments, [ + 'callback', + 'interval' + ], Tone.Loop.defaults); + /** + * The event which produces the callbacks + */ + this._event = new Tone.Event({ + 'callback': this._tick.bind(this), + 'loop': true, + 'loopEnd': options.interval, + 'playbackRate': options.playbackRate, + 'probability': options.probability + }); + /** + * The callback to invoke with the next event in the pattern + * @type {Function} + */ + this.callback = options.callback; + //set the iterations + this.iterations = options.iterations; + }; + Tone.extend(Tone.Loop); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.Loop.defaults = { + 'interval': '4n', + 'callback': Tone.noOp, + 'playbackRate': 1, + 'iterations': Infinity, + 'probability': true, + 'mute': false + }; + /** + * Start the loop at the specified time along the Transport's + * timeline. + * @param {TimelinePosition=} time When to start the Loop. + * @return {Tone.Loop} this + */ + Tone.Loop.prototype.start = function (time) { + this._event.start(time); + return this; + }; + /** + * Stop the loop at the given time. + * @param {TimelinePosition=} time When to stop the Arpeggio + * @return {Tone.Loop} this + */ + Tone.Loop.prototype.stop = function (time) { + this._event.stop(time); + return this; + }; + /** + * Cancel all scheduled events greater than or equal to the given time + * @param {TimelinePosition} [time=0] The time after which events will be cancel. + * @return {Tone.Loop} this + */ + Tone.Loop.prototype.cancel = function (time) { + this._event.cancel(time); + return this; + }; + /** + * Internal function called when the notes should be called + * @param {Number} time The time the event occurs + * @private + */ + Tone.Loop.prototype._tick = function (time) { + this.callback(time); + }; + /** + * The state of the Loop, either started or stopped. + * @memberOf Tone.Loop# + * @type {String} + * @name state + * @readOnly + */ + Object.defineProperty(Tone.Loop.prototype, 'state', { + get: function () { + return this._event.state; + } + }); + /** + * The progress of the loop as a value between 0-1. 0, when + * the loop is stopped or done iterating. + * @memberOf Tone.Loop# + * @type {NormalRange} + * @name progress + * @readOnly + */ + Object.defineProperty(Tone.Loop.prototype, 'progress', { + get: function () { + return this._event.progress; + } + }); + /** + * The time between successive callbacks. + * @example + * loop.interval = "8n"; //loop every 8n + * @memberOf Tone.Loop# + * @type {Time} + * @name interval + */ + Object.defineProperty(Tone.Loop.prototype, 'interval', { + get: function () { + return this._event.loopEnd; + }, + set: function (interval) { + this._event.loopEnd = interval; + } + }); + /** + * The playback rate of the loop. The normal playback rate is 1 (no change). + * A `playbackRate` of 2 would be twice as fast. + * @memberOf Tone.Loop# + * @type {Time} + * @name playbackRate + */ + Object.defineProperty(Tone.Loop.prototype, 'playbackRate', { + get: function () { + return this._event.playbackRate; + }, + set: function (rate) { + this._event.playbackRate = rate; + } + }); + /** + * Random variation +/-0.01s to the scheduled time. + * Or give it a time value which it will randomize by. + * @type {Boolean|Time} + * @memberOf Tone.Loop# + * @name humanize + */ + Object.defineProperty(Tone.Loop.prototype, 'humanize', { + get: function () { + return this._event.humanize; + }, + set: function (variation) { + this._event.humanize = variation; + } + }); + /** + * The probably of the callback being invoked. + * @memberOf Tone.Loop# + * @type {NormalRange} + * @name probability + */ + Object.defineProperty(Tone.Loop.prototype, 'probability', { + get: function () { + return this._event.probability; + }, + set: function (prob) { + this._event.probability = prob; + } + }); + /** + * Muting the Loop means that no callbacks are invoked. + * @memberOf Tone.Loop# + * @type {Boolean} + * @name mute + */ + Object.defineProperty(Tone.Loop.prototype, 'mute', { + get: function () { + return this._event.mute; + }, + set: function (mute) { + this._event.mute = mute; + } + }); + /** + * The number of iterations of the loop. The default + * value is Infinity (loop forever). + * @memberOf Tone.Loop# + * @type {Positive} + * @name iterations + */ + Object.defineProperty(Tone.Loop.prototype, 'iterations', { + get: function () { + if (this._event.loop === true) { + return Infinity; + } else { + return this._event.loop; + } + return this._pattern.index; + }, + set: function (iters) { + if (iters === Infinity) { + this._event.loop = true; + } else { + this._event.loop = iters; + } + } + }); + /** + * Clean up + * @return {Tone.Loop} this + */ + Tone.Loop.prototype.dispose = function () { + this._event.dispose(); + this._event = null; + this.callback = null; + }; + return Tone.Loop; + }); + Module(function (Tone) { + + /** + * @class Tone.Part is a collection Tone.Events which can be + * started/stoped and looped as a single unit. + * + * @extends {Tone.Event} + * @param {Function} callback The callback to invoke on each event + * @param {Array} events the array of events + * @example + * var part = new Tone.Part(function(time, note){ + * //the notes given as the second element in the array + * //will be passed in as the second argument + * synth.triggerAttackRelease(note, "8n", time); + * }, [[0, "C2"], ["0:2", "C3"], ["0:3:2", "G2"]]); + * @example + * //use an array of objects as long as the object has a "time" attribute + * var part = new Tone.Part(function(time, value){ + * //the value is an object which contains both the note and the velocity + * synth.triggerAttackRelease(value.note, "8n", time, value.velocity); + * }, [{"time" : 0, "note" : "C3", "velocity": 0.9}, + * {"time" : "0:2", "note" : "C4", "velocity": 0.5} + * ]).start(0); + */ + Tone.Part = function () { + var options = this.optionsObject(arguments, [ + 'callback', + 'events' + ], Tone.Part.defaults); + /** + * If the part is looping or not + * @type {Boolean|Positive} + * @private + */ + this._loop = options.loop; + /** + * When the note is scheduled to start. + * @type {Ticks} + * @private + */ + this._loopStart = this.toTicks(options.loopStart); + /** + * When the note is scheduled to start. + * @type {Ticks} + * @private + */ + this._loopEnd = this.toTicks(options.loopEnd); + /** + * The playback rate of the part + * @type {Positive} + * @private + */ + this._playbackRate = options.playbackRate; + /** + * private holder of probability value + * @type {NormalRange} + * @private + */ + this._probability = options.probability; + /** + * the amount of variation from the + * given time. + * @type {Boolean|Time} + * @private + */ + this._humanize = options.humanize; + /** + * The start offset + * @type {Ticks} + * @private + */ + this._startOffset = 0; + /** + * Keeps track of the current state + * @type {Tone.TimelineState} + * @private + */ + this._state = new Tone.TimelineState(Tone.State.Stopped); + /** + * An array of Objects. + * @type {Array} + * @private + */ + this._events = []; + /** + * The callback to invoke at all the scheduled events. + * @type {Function} + */ + this.callback = options.callback; + /** + * If mute is true, the callback won't be + * invoked. + * @type {Boolean} + */ + this.mute = options.mute; + //add the events + var events = this.defaultArg(options.events, []); + if (!this.isUndef(options.events)) { + for (var i = 0; i < events.length; i++) { + if (Array.isArray(events[i])) { + this.add(events[i][0], events[i][1]); + } else { + this.add(events[i]); + } + } + } + }; + Tone.extend(Tone.Part, Tone.Event); + /** + * The default values + * @type {Object} + * @const + */ + Tone.Part.defaults = { + 'callback': Tone.noOp, + 'loop': false, + 'loopEnd': '1m', + 'loopStart': 0, + 'playbackRate': 1, + 'probability': 1, + 'humanize': false, + 'mute': false + }; + /** + * Start the part at the given time. + * @param {TransportTime} time When to start the part. + * @param {Time=} offset The offset from the start of the part + * to begin playing at. + * @return {Tone.Part} this + */ + Tone.Part.prototype.start = function (time, offset) { + var ticks = this.toTicks(time); + if (this._state.getValueAtTime(ticks) !== Tone.State.Started) { + if (this._loop) { + offset = this.defaultArg(offset, this._loopStart); + } else { + offset = this.defaultArg(offset, 0); + } + offset = this.toTicks(offset); + this._state.add({ + 'state': Tone.State.Started, + 'time': ticks, + 'offset': offset + }); + this._forEach(function (event) { + this._startNote(event, ticks, offset); + }); + } + return this; + }; + /** + * Start the event in the given event at the correct time given + * the ticks and offset and looping. + * @param {Tone.Event} event + * @param {Ticks} ticks + * @param {Ticks} offset + * @private + */ + Tone.Part.prototype._startNote = function (event, ticks, offset) { + ticks -= offset; + if (this._loop) { + if (event.startOffset >= this._loopStart && event.startOffset < this._loopEnd) { + if (event.startOffset < offset) { + //start it on the next loop + ticks += this._getLoopDuration(); + } + event.start(Tone.TransportTime(ticks, 'i')); + } else if (event.startOffset < this._loopStart && event.startOffset >= offset) { + event.loop = false; + event.start(Tone.TransportTime(ticks, 'i')); + } + } else { + if (event.startOffset >= offset) { + event.start(Tone.TransportTime(ticks, 'i')); + } + } + }; + /** + * The start from the scheduled start time + * @type {Ticks} + * @memberOf Tone.Part# + * @name startOffset + * @private + */ + Object.defineProperty(Tone.Part.prototype, 'startOffset', { + get: function () { + return this._startOffset; + }, + set: function (offset) { + this._startOffset = offset; + this._forEach(function (event) { + event.startOffset += this._startOffset; + }); + } + }); + /** + * Stop the part at the given time. + * @param {TimelinePosition} time When to stop the part. + * @return {Tone.Part} this + */ + Tone.Part.prototype.stop = function (time) { + var ticks = this.toTicks(time); + this._state.cancel(ticks); + this._state.setStateAtTime(Tone.State.Stopped, ticks); + this._forEach(function (event) { + event.stop(time); + }); + return this; + }; + /** + * Get/Set an Event's value at the given time. + * If a value is passed in and no event exists at + * the given time, one will be created with that value. + * If two events are at the same time, the first one will + * be returned. + * @example + * part.at("1m"); //returns the part at the first measure + * + * part.at("2m", "C2"); //set the value at "2m" to C2. + * //if an event didn't exist at that time, it will be created. + * @param {TransportTime} time The time of the event to get or set. + * @param {*=} value If a value is passed in, the value of the + * event at the given time will be set to it. + * @return {Tone.Event} the event at the time + */ + Tone.Part.prototype.at = function (time, value) { + time = Tone.TransportTime(time); + var tickTime = Tone.Time(1, 'i').toSeconds(); + for (var i = 0; i < this._events.length; i++) { + var event = this._events[i]; + if (Math.abs(time.toTicks() - event.startOffset) < tickTime) { + if (!this.isUndef(value)) { + event.value = value; + } + return event; + } + } + //if there was no event at that time, create one + if (!this.isUndef(value)) { + this.add(time, value); + //return the new event + return this._events[this._events.length - 1]; + } else { + return null; + } + }; + /** + * Add a an event to the part. + * @param {Time} time The time the note should start. + * If an object is passed in, it should + * have a 'time' attribute and the rest + * of the object will be used as the 'value'. + * @param {Tone.Event|*} value + * @returns {Tone.Part} this + * @example + * part.add("1m", "C#+11"); + */ + Tone.Part.prototype.add = function (time, value) { + //extract the parameters + if (time.hasOwnProperty('time')) { + value = time; + time = value.time; + } + time = this.toTicks(time); + var event; + if (value instanceof Tone.Event) { + event = value; + event.callback = this._tick.bind(this); + } else { + event = new Tone.Event({ + 'callback': this._tick.bind(this), + 'value': value + }); + } + //the start offset + event.startOffset = time; + //initialize the values + event.set({ + 'loopEnd': this.loopEnd, + 'loopStart': this.loopStart, + 'loop': this.loop, + 'humanize': this.humanize, + 'playbackRate': this.playbackRate, + 'probability': this.probability + }); + this._events.push(event); + //start the note if it should be played right now + this._restartEvent(event); + return this; + }; + /** + * Restart the given event + * @param {Tone.Event} event + * @private + */ + Tone.Part.prototype._restartEvent = function (event) { + this._state.forEach(function (stateEvent) { + if (stateEvent.state === Tone.State.Started) { + this._startNote(event, stateEvent.time, stateEvent.offset); + } else { + //stop the note + event.stop(Tone.TransportTime(stateEvent.time, 'i')); + } + }.bind(this)); + }; + /** + * Remove an event from the part. Will recursively iterate + * into nested parts to find the event. + * @param {Time} time The time of the event + * @param {*} value Optionally select only a specific event value + * @return {Tone.Part} this + */ + Tone.Part.prototype.remove = function (time, value) { + //extract the parameters + if (time.hasOwnProperty('time')) { + value = time; + time = value.time; + } + time = this.toTicks(time); + for (var i = this._events.length - 1; i >= 0; i--) { + var event = this._events[i]; + if (event instanceof Tone.Part) { + event.remove(time, value); + } else { + if (event.startOffset === time) { + if (this.isUndef(value) || !this.isUndef(value) && event.value === value) { + this._events.splice(i, 1); + event.dispose(); + } + } + } + } + return this; + }; + /** + * Remove all of the notes from the group. + * @return {Tone.Part} this + */ + Tone.Part.prototype.removeAll = function () { + this._forEach(function (event) { + event.dispose(); + }); + this._events = []; + return this; + }; + /** + * Cancel scheduled state change events: i.e. "start" and "stop". + * @param {TimelinePosition} after The time after which to cancel the scheduled events. + * @return {Tone.Part} this + */ + Tone.Part.prototype.cancel = function (after) { + after = this.toTicks(after); + this._forEach(function (event) { + event.cancel(after); + }); + this._state.cancel(after); + return this; + }; + /** + * Iterate over all of the events + * @param {Function} callback + * @param {Object} ctx The context + * @private + */ + Tone.Part.prototype._forEach = function (callback, ctx) { + ctx = this.defaultArg(ctx, this); + for (var i = this._events.length - 1; i >= 0; i--) { + var e = this._events[i]; + if (e instanceof Tone.Part) { + e._forEach(callback, ctx); + } else { + callback.call(ctx, e); + } + } + return this; + }; + /** + * Set the attribute of all of the events + * @param {String} attr the attribute to set + * @param {*} value The value to set it to + * @private + */ + Tone.Part.prototype._setAll = function (attr, value) { + this._forEach(function (event) { + event[attr] = value; + }); + }; + /** + * Internal tick method + * @param {Number} time The time of the event in seconds + * @private + */ + Tone.Part.prototype._tick = function (time, value) { + if (!this.mute) { + this.callback(time, value); + } + }; + /** + * Determine if the event should be currently looping + * given the loop boundries of this Part. + * @param {Tone.Event} event The event to test + * @private + */ + Tone.Part.prototype._testLoopBoundries = function (event) { + if (event.startOffset < this._loopStart || event.startOffset >= this._loopEnd) { + event.cancel(0); + } else { + //reschedule it if it's stopped + if (event.state === Tone.State.Stopped) { + this._restartEvent(event); + } + } + }; + /** + * The probability of the notes being triggered. + * @memberOf Tone.Part# + * @type {NormalRange} + * @name probability + */ + Object.defineProperty(Tone.Part.prototype, 'probability', { + get: function () { + return this._probability; + }, + set: function (prob) { + this._probability = prob; + this._setAll('probability', prob); + } + }); + /** + * If set to true, will apply small random variation + * to the callback time. If the value is given as a time, it will randomize + * by that amount. + * @example + * event.humanize = true; + * @type {Boolean|Time} + * @name humanize + */ + Object.defineProperty(Tone.Part.prototype, 'humanize', { + get: function () { + return this._humanize; + }, + set: function (variation) { + this._humanize = variation; + this._setAll('humanize', variation); + } + }); + /** + * If the part should loop or not + * between Tone.Part.loopStart and + * Tone.Part.loopEnd. An integer + * value corresponds to the number of + * loops the Part does after it starts. + * @memberOf Tone.Part# + * @type {Boolean|Positive} + * @name loop + * @example + * //loop the part 8 times + * part.loop = 8; + */ + Object.defineProperty(Tone.Part.prototype, 'loop', { + get: function () { + return this._loop; + }, + set: function (loop) { + this._loop = loop; + this._forEach(function (event) { + event._loopStart = this._loopStart; + event._loopEnd = this._loopEnd; + event.loop = loop; + this._testLoopBoundries(event); + }); + } + }); + /** + * The loopEnd point determines when it will + * loop if Tone.Part.loop is true. + * @memberOf Tone.Part# + * @type {TransportTime} + * @name loopEnd + */ + Object.defineProperty(Tone.Part.prototype, 'loopEnd', { + get: function () { + return Tone.TransportTime(this._loopEnd, 'i').toNotation(); + }, + set: function (loopEnd) { + this._loopEnd = this.toTicks(loopEnd); + if (this._loop) { + this._forEach(function (event) { + event.loopEnd = loopEnd; + this._testLoopBoundries(event); + }); + } + } + }); + /** + * The loopStart point determines when it will + * loop if Tone.Part.loop is true. + * @memberOf Tone.Part# + * @type {TransportTime} + * @name loopStart + */ + Object.defineProperty(Tone.Part.prototype, 'loopStart', { + get: function () { + return Tone.TransportTime(this._loopStart, 'i').toNotation(); + }, + set: function (loopStart) { + this._loopStart = this.toTicks(loopStart); + if (this._loop) { + this._forEach(function (event) { + event.loopStart = this.loopStart; + this._testLoopBoundries(event); + }); + } + } + }); + /** + * The playback rate of the part + * @memberOf Tone.Part# + * @type {Positive} + * @name playbackRate + */ + Object.defineProperty(Tone.Part.prototype, 'playbackRate', { + get: function () { + return this._playbackRate; + }, + set: function (rate) { + this._playbackRate = rate; + this._setAll('playbackRate', rate); + } + }); + /** + * The number of scheduled notes in the part. + * @memberOf Tone.Part# + * @type {Positive} + * @name length + * @readOnly + */ + Object.defineProperty(Tone.Part.prototype, 'length', { + get: function () { + return this._events.length; + } + }); + /** + * Clean up + * @return {Tone.Part} this + */ + Tone.Part.prototype.dispose = function () { + this.removeAll(); + this._state.dispose(); + this._state = null; + this.callback = null; + this._events = null; + return this; + }; + return Tone.Part; + }); + Module(function (Tone) { + /** + * @class Tone.Pattern arpeggiates between the given notes + * in a number of patterns. See Tone.CtrlPattern for + * a full list of patterns. + * @example + * var pattern = new Tone.Pattern(function(time, note){ + * //the order of the notes passed in depends on the pattern + * }, ["C2", "D4", "E5", "A6"], "upDown"); + * @extends {Tone.Loop} + * @param {Function} callback The callback to invoke with the + * event. + * @param {Array} values The values to arpeggiate over. + */ + Tone.Pattern = function () { + var options = this.optionsObject(arguments, [ + 'callback', + 'values', + 'pattern' + ], Tone.Pattern.defaults); + Tone.Loop.call(this, options); + /** + * The pattern manager + * @type {Tone.CtrlPattern} + * @private + */ + this._pattern = new Tone.CtrlPattern({ + 'values': options.values, + 'type': options.pattern, + 'index': options.index + }); + }; + Tone.extend(Tone.Pattern, Tone.Loop); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.Pattern.defaults = { + 'pattern': Tone.CtrlPattern.Type.Up, + 'values': [] + }; + /** + * Internal function called when the notes should be called + * @param {Number} time The time the event occurs + * @private + */ + Tone.Pattern.prototype._tick = function (time) { + this.callback(time, this._pattern.value); + this._pattern.next(); + }; + /** + * The current index in the values array. + * @memberOf Tone.Pattern# + * @type {Positive} + * @name index + */ + Object.defineProperty(Tone.Pattern.prototype, 'index', { + get: function () { + return this._pattern.index; + }, + set: function (i) { + this._pattern.index = i; + } + }); + /** + * The array of events. + * @memberOf Tone.Pattern# + * @type {Array} + * @name values + */ + Object.defineProperty(Tone.Pattern.prototype, 'values', { + get: function () { + return this._pattern.values; + }, + set: function (vals) { + this._pattern.values = vals; + } + }); + /** + * The current value of the pattern. + * @memberOf Tone.Pattern# + * @type {*} + * @name value + * @readOnly + */ + Object.defineProperty(Tone.Pattern.prototype, 'value', { + get: function () { + return this._pattern.value; + } + }); + /** + * The pattern type. See Tone.CtrlPattern for the full list of patterns. + * @memberOf Tone.Pattern# + * @type {String} + * @name pattern + */ + Object.defineProperty(Tone.Pattern.prototype, 'pattern', { + get: function () { + return this._pattern.type; + }, + set: function (pattern) { + this._pattern.type = pattern; + } + }); + /** + * Clean up + * @return {Tone.Pattern} this + */ + Tone.Pattern.prototype.dispose = function () { + Tone.Loop.prototype.dispose.call(this); + this._pattern.dispose(); + this._pattern = null; + }; + return Tone.Pattern; + }); + Module(function (Tone) { + + /** + * @class A sequence is an alternate notation of a part. Instead + * of passing in an array of [time, event] pairs, pass + * in an array of events which will be spaced at the + * given subdivision. Sub-arrays will subdivide that beat + * by the number of items are in the array. + * Sequence notation inspiration from [Tidal](http://yaxu.org/tidal/) + * @param {Function} callback The callback to invoke with every note + * @param {Array} events The sequence + * @param {Time} subdivision The subdivision between which events are placed. + * @extends {Tone.Part} + * @example + * var seq = new Tone.Sequence(function(time, note){ + * console.log(note); + * //straight quater notes + * }, ["C4", "E4", "G4", "A4"], "4n"); + * @example + * var seq = new Tone.Sequence(function(time, note){ + * console.log(note); + * //subdivisions are given as subarrays + * }, ["C4", ["E4", "D4", "E4"], "G4", ["A4", "G4"]]); + */ + Tone.Sequence = function () { + var options = this.optionsObject(arguments, [ + 'callback', + 'events', + 'subdivision' + ], Tone.Sequence.defaults); + //remove the events + var events = options.events; + delete options.events; + Tone.Part.call(this, options); + /** + * The subdivison of each note + * @type {Ticks} + * @private + */ + this._subdivision = this.toTicks(options.subdivision); + //if no time was passed in, the loop end is the end of the cycle + if (this.isUndef(options.loopEnd) && !this.isUndef(events)) { + this._loopEnd = events.length * this._subdivision; + } + //defaults to looping + this._loop = true; + //add all of the events + if (!this.isUndef(events)) { + for (var i = 0; i < events.length; i++) { + this.add(i, events[i]); + } + } + }; + Tone.extend(Tone.Sequence, Tone.Part); + /** + * The default values. + * @type {Object} + */ + Tone.Sequence.defaults = { 'subdivision': '4n' }; + /** + * The subdivision of the sequence. This can only be + * set in the constructor. The subdivision is the + * interval between successive steps. + * @type {Time} + * @memberOf Tone.Sequence# + * @name subdivision + * @readOnly + */ + Object.defineProperty(Tone.Sequence.prototype, 'subdivision', { + get: function () { + return Tone.Time(this._subdivision, 'i').toNotation(); + } + }); + /** + * Get/Set an index of the sequence. If the index contains a subarray, + * a Tone.Sequence representing that sub-array will be returned. + * @example + * var sequence = new Tone.Sequence(playNote, ["E4", "C4", "F#4", ["A4", "Bb3"]]) + * sequence.at(0)// => returns "E4" + * //set a value + * sequence.at(0, "G3"); + * //get a nested sequence + * sequence.at(3).at(1)// => returns "Bb3" + * @param {Positive} index The index to get or set + * @param {*} value Optionally pass in the value to set at the given index. + */ + Tone.Sequence.prototype.at = function (index, value) { + //if the value is an array, + if (this.isArray(value)) { + //remove the current event at that index + this.remove(index); + } + //call the parent's method + return Tone.Part.prototype.at.call(this, this._indexTime(index), value); + }; + /** + * Add an event at an index, if there's already something + * at that index, overwrite it. If `value` is an array, + * it will be parsed as a subsequence. + * @param {Number} index The index to add the event to + * @param {*} value The value to add at that index + * @returns {Tone.Sequence} this + */ + Tone.Sequence.prototype.add = function (index, value) { + if (value === null) { + return this; + } + if (this.isArray(value)) { + //make a subsequence and add that to the sequence + var subSubdivision = Math.round(this._subdivision / value.length); + value = new Tone.Sequence(this._tick.bind(this), value, Tone.Time(subSubdivision, 'i')); + } + Tone.Part.prototype.add.call(this, this._indexTime(index), value); + return this; + }; + /** + * Remove a value from the sequence by index + * @param {Number} index The index of the event to remove + * @returns {Tone.Sequence} this + */ + Tone.Sequence.prototype.remove = function (index, value) { + Tone.Part.prototype.remove.call(this, this._indexTime(index), value); + return this; + }; + /** + * Get the time of the index given the Sequence's subdivision + * @param {Number} index + * @return {Time} The time of that index + * @private + */ + Tone.Sequence.prototype._indexTime = function (index) { + if (index instanceof Tone.TransportTime) { + return index; + } else { + return Tone.TransportTime(index * this._subdivision + this.startOffset, 'i'); + } + }; + /** + * Clean up. + * @return {Tone.Sequence} this + */ + Tone.Sequence.prototype.dispose = function () { + Tone.Part.prototype.dispose.call(this); + return this; + }; + return Tone.Sequence; + }); + Module(function (Tone) { + + /** + * @class Tone.PulseOscillator is a pulse oscillator with control over pulse width, + * also known as the duty cycle. At 50% duty cycle (width = 0.5) the wave is + * a square and only odd-numbered harmonics are present. At all other widths + * even-numbered harmonics are present. Read more + * [here](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/). + * + * @constructor + * @extends {Tone.Oscillator} + * @param {Frequency} [frequency] The frequency of the oscillator + * @param {NormalRange} [width] The width of the pulse + * @example + * var pulse = new Tone.PulseOscillator("E5", 0.4).toMaster().start(); + */ + Tone.PulseOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'width' + ], Tone.Oscillator.defaults); + Tone.Source.call(this, options); + /** + * The width of the pulse. + * @type {NormalRange} + * @signal + */ + this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); + /** + * gate the width amount + * @type {Tone.Gain} + * @private + */ + this._widthGate = new Tone.Gain(); + /** + * the sawtooth oscillator + * @type {Tone.Oscillator} + * @private + */ + this._sawtooth = new Tone.Oscillator({ + frequency: options.frequency, + detune: options.detune, + type: 'sawtooth', + phase: options.phase + }); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = this._sawtooth.frequency; + /** + * The detune in cents. + * @type {Cents} + * @signal + */ + this.detune = this._sawtooth.detune; + /** + * Threshold the signal to turn it into a square + * @type {Tone.WaveShaper} + * @private + */ + this._thresh = new Tone.WaveShaper(function (val) { + if (val < 0) { + return -1; + } else { + return 1; + } + }); + //connections + this._sawtooth.chain(this._thresh, this.output); + this.width.chain(this._widthGate, this._thresh); + this._readOnly([ + 'width', + 'frequency', + 'detune' + ]); + }; + Tone.extend(Tone.PulseOscillator, Tone.Oscillator); + /** + * The default parameters. + * @static + * @const + * @type {Object} + */ + Tone.PulseOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'width': 0.2 + }; + /** + * start the oscillator + * @param {Time} time + * @private + */ + Tone.PulseOscillator.prototype._start = function (time) { + time = this.toSeconds(time); + this._sawtooth.start(time); + this._widthGate.gain.setValueAtTime(1, time); + }; + /** + * stop the oscillator + * @param {Time} time + * @private + */ + Tone.PulseOscillator.prototype._stop = function (time) { + time = this.toSeconds(time); + this._sawtooth.stop(time); + //the width is still connected to the output. + //that needs to be stopped also + this._widthGate.gain.setValueAtTime(0, time); + }; + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.PulseOscillator# + * @type {Degrees} + * @name phase + */ + Object.defineProperty(Tone.PulseOscillator.prototype, 'phase', { + get: function () { + return this._sawtooth.phase; + }, + set: function (phase) { + this._sawtooth.phase = phase; + } + }); + /** + * The type of the oscillator. Always returns "pulse". + * @readOnly + * @memberOf Tone.PulseOscillator# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.PulseOscillator.prototype, 'type', { + get: function () { + return 'pulse'; + } + }); + /** + * The partials of the waveform. Cannot set partials for this waveform type + * @memberOf Tone.PulseOscillator# + * @type {Array} + * @name partials + * @private + */ + Object.defineProperty(Tone.PulseOscillator.prototype, 'partials', { + get: function () { + return []; + } + }); + /** + * Clean up method. + * @return {Tone.PulseOscillator} this + */ + Tone.PulseOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._sawtooth.dispose(); + this._sawtooth = null; + this._writable([ + 'width', + 'frequency', + 'detune' + ]); + this.width.dispose(); + this.width = null; + this._widthGate.dispose(); + this._widthGate = null; + this._thresh.dispose(); + this._thresh = null; + this.frequency = null; + this.detune = null; + return this; + }; + return Tone.PulseOscillator; + }); + Module(function (Tone) { + + /** + * @class Tone.PWMOscillator modulates the width of a Tone.PulseOscillator + * at the modulationFrequency. This has the effect of continuously + * changing the timbre of the oscillator by altering the harmonics + * generated. + * + * @extends {Tone.Oscillator} + * @constructor + * @param {Frequency} frequency The starting frequency of the oscillator. + * @param {Frequency} modulationFrequency The modulation frequency of the width of the pulse. + * @example + * var pwm = new Tone.PWMOscillator("Ab3", 0.3).toMaster().start(); + */ + Tone.PWMOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'modulationFrequency' + ], Tone.PWMOscillator.defaults); + Tone.Source.call(this, options); + /** + * the pulse oscillator + * @type {Tone.PulseOscillator} + * @private + */ + this._pulse = new Tone.PulseOscillator(options.modulationFrequency); + //change the pulse oscillator type + this._pulse._sawtooth.type = 'sine'; + /** + * the modulator + * @type {Tone.Oscillator} + * @private + */ + this._modulator = new Tone.Oscillator({ + 'frequency': options.frequency, + 'detune': options.detune, + 'phase': options.phase + }); + /** + * Scale the oscillator so it doesn't go silent + * at the extreme values. + * @type {Tone.Multiply} + * @private + */ + this._scale = new Tone.Multiply(2); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = this._modulator.frequency; + /** + * The detune of the oscillator. + * @type {Cents} + * @signal + */ + this.detune = this._modulator.detune; + /** + * The modulation rate of the oscillator. + * @type {Frequency} + * @signal + */ + this.modulationFrequency = this._pulse.frequency; + //connections + this._modulator.chain(this._scale, this._pulse.width); + this._pulse.connect(this.output); + this._readOnly([ + 'modulationFrequency', + 'frequency', + 'detune' + ]); + }; + Tone.extend(Tone.PWMOscillator, Tone.Oscillator); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.PWMOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'modulationFrequency': 0.4 + }; + /** + * start the oscillator + * @param {Time} [time=now] + * @private + */ + Tone.PWMOscillator.prototype._start = function (time) { + time = this.toSeconds(time); + this._modulator.start(time); + this._pulse.start(time); + }; + /** + * stop the oscillator + * @param {Time} time (optional) timing parameter + * @private + */ + Tone.PWMOscillator.prototype._stop = function (time) { + time = this.toSeconds(time); + this._modulator.stop(time); + this._pulse.stop(time); + }; + /** + * The type of the oscillator. Always returns "pwm". + * @readOnly + * @memberOf Tone.PWMOscillator# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.PWMOscillator.prototype, 'type', { + get: function () { + return 'pwm'; + } + }); + /** + * The partials of the waveform. Cannot set partials for this waveform type + * @memberOf Tone.PWMOscillator# + * @type {Array} + * @name partials + * @private + */ + Object.defineProperty(Tone.PWMOscillator.prototype, 'partials', { + get: function () { + return []; + } + }); + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.PWMOscillator# + * @type {number} + * @name phase + */ + Object.defineProperty(Tone.PWMOscillator.prototype, 'phase', { + get: function () { + return this._modulator.phase; + }, + set: function (phase) { + this._modulator.phase = phase; + } + }); + /** + * Clean up. + * @return {Tone.PWMOscillator} this + */ + Tone.PWMOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._pulse.dispose(); + this._pulse = null; + this._scale.dispose(); + this._scale = null; + this._modulator.dispose(); + this._modulator = null; + this._writable([ + 'modulationFrequency', + 'frequency', + 'detune' + ]); + this.frequency = null; + this.detune = null; + this.modulationFrequency = null; + return this; + }; + return Tone.PWMOscillator; + }); + Module(function (Tone) { + + /** + * @class Tone.FMOscillator + * + * @extends {Tone.Oscillator} + * @constructor + * @param {Frequency} frequency The starting frequency of the oscillator. + * @param {String} type The type of the carrier oscillator. + * @param {String} modulationType The type of the modulator oscillator. + * @example + * //a sine oscillator frequency-modulated by a square wave + * var fmOsc = new Tone.FMOscillator("Ab3", "sine", "square").toMaster().start(); + */ + Tone.FMOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'type', + 'modulationType' + ], Tone.FMOscillator.defaults); + Tone.Source.call(this, options); + /** + * The carrier oscillator + * @type {Tone.Oscillator} + * @private + */ + this._carrier = new Tone.Oscillator(options.frequency, options.type); + /** + * The oscillator's frequency + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The detune control signal. + * @type {Cents} + * @signal + */ + this.detune = this._carrier.detune; + this.detune.value = options.detune; + /** + * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the + * ratio of the frequency of the modulating signal (mf) to the amplitude of the + * modulating signal (ma) -- as in ma/mf. + * @type {Positive} + * @signal + */ + this.modulationIndex = new Tone.Multiply(options.modulationIndex); + this.modulationIndex.units = Tone.Type.Positive; + /** + * The modulating oscillator + * @type {Tone.Oscillator} + * @private + */ + this._modulator = new Tone.Oscillator(options.frequency, options.modulationType); + /** + * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. + * A harmonicity of 1 gives both oscillators the same frequency. + * Harmonicity = 2 means a change of an octave. + * @type {Positive} + * @signal + * @example + * //pitch the modulator an octave below carrier + * synth.harmonicity.value = 0.5; + */ + this.harmonicity = new Tone.Multiply(options.harmonicity); + this.harmonicity.units = Tone.Type.Positive; + /** + * the node where the modulation happens + * @type {Tone.Gain} + * @private + */ + this._modulationNode = new Tone.Gain(0); + //connections + this.frequency.connect(this._carrier.frequency); + this.frequency.chain(this.harmonicity, this._modulator.frequency); + this.frequency.chain(this.modulationIndex, this._modulationNode); + this._modulator.connect(this._modulationNode.gain); + this._modulationNode.connect(this._carrier.frequency); + this._carrier.connect(this.output); + this.detune.connect(this._modulator.detune); + this.phase = options.phase; + this._readOnly([ + 'modulationIndex', + 'frequency', + 'detune', + 'harmonicity' + ]); + }; + Tone.extend(Tone.FMOscillator, Tone.Oscillator); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.FMOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'modulationIndex': 2, + 'modulationType': 'square', + 'harmonicity': 1 + }; + /** + * start the oscillator + * @param {Time} [time=now] + * @private + */ + Tone.FMOscillator.prototype._start = function (time) { + time = this.toSeconds(time); + this._modulator.start(time); + this._carrier.start(time); + }; + /** + * stop the oscillator + * @param {Time} time (optional) timing parameter + * @private + */ + Tone.FMOscillator.prototype._stop = function (time) { + time = this.toSeconds(time); + this._modulator.stop(time); + this._carrier.stop(time); + }; + /** + * The type of the carrier oscillator + * @memberOf Tone.FMOscillator# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.FMOscillator.prototype, 'type', { + get: function () { + return this._carrier.type; + }, + set: function (type) { + this._carrier.type = type; + } + }); + /** + * The type of the modulator oscillator + * @memberOf Tone.FMOscillator# + * @type {String} + * @name modulationType + */ + Object.defineProperty(Tone.FMOscillator.prototype, 'modulationType', { + get: function () { + return this._modulator.type; + }, + set: function (type) { + this._modulator.type = type; + } + }); + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.FMOscillator# + * @type {number} + * @name phase + */ + Object.defineProperty(Tone.FMOscillator.prototype, 'phase', { + get: function () { + return this._carrier.phase; + }, + set: function (phase) { + this._carrier.phase = phase; + this._modulator.phase = phase; + } + }); + /** + * The partials of the carrier waveform. A partial represents + * the amplitude at a harmonic. The first harmonic is the + * fundamental frequency, the second is the octave and so on + * following the harmonic series. + * Setting this value will automatically set the type to "custom". + * The value is an empty array when the type is not "custom". + * @memberOf Tone.FMOscillator# + * @type {Array} + * @name partials + * @example + * osc.partials = [1, 0.2, 0.01]; + */ + Object.defineProperty(Tone.FMOscillator.prototype, 'partials', { + get: function () { + return this._carrier.partials; + }, + set: function (partials) { + this._carrier.partials = partials; + } + }); + /** + * Clean up. + * @return {Tone.FMOscillator} this + */ + Tone.FMOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._writable([ + 'modulationIndex', + 'frequency', + 'detune', + 'harmonicity' + ]); + this.frequency.dispose(); + this.frequency = null; + this.detune = null; + this.harmonicity.dispose(); + this.harmonicity = null; + this._carrier.dispose(); + this._carrier = null; + this._modulator.dispose(); + this._modulator = null; + this._modulationNode.dispose(); + this._modulationNode = null; + this.modulationIndex.dispose(); + this.modulationIndex = null; + return this; + }; + return Tone.FMOscillator; + }); + Module(function (Tone) { + + /** + * @class Tone.AMOscillator + * + * @extends {Tone.Oscillator} + * @constructor + * @param {Frequency} frequency The starting frequency of the oscillator. + * @param {String} type The type of the carrier oscillator. + * @param {String} modulationType The type of the modulator oscillator. + * @example + * //a sine oscillator frequency-modulated by a square wave + * var fmOsc = new Tone.AMOscillator("Ab3", "sine", "square").toMaster().start(); + */ + Tone.AMOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'type', + 'modulationType' + ], Tone.AMOscillator.defaults); + Tone.Source.call(this, options); + /** + * The carrier oscillator + * @type {Tone.Oscillator} + * @private + */ + this._carrier = new Tone.Oscillator(options.frequency, options.type); + /** + * The oscillator's frequency + * @type {Frequency} + * @signal + */ + this.frequency = this._carrier.frequency; + /** + * The detune control signal. + * @type {Cents} + * @signal + */ + this.detune = this._carrier.detune; + this.detune.value = options.detune; + /** + * The modulating oscillator + * @type {Tone.Oscillator} + * @private + */ + this._modulator = new Tone.Oscillator(options.frequency, options.modulationType); + /** + * convert the -1,1 output to 0,1 + * @type {Tone.AudioToGain} + * @private + */ + this._modulationScale = new Tone.AudioToGain(); + /** + * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. + * A harmonicity of 1 gives both oscillators the same frequency. + * Harmonicity = 2 means a change of an octave. + * @type {Positive} + * @signal + * @example + * //pitch the modulator an octave below carrier + * synth.harmonicity.value = 0.5; + */ + this.harmonicity = new Tone.Multiply(options.harmonicity); + this.harmonicity.units = Tone.Type.Positive; + /** + * the node where the modulation happens + * @type {Tone.Gain} + * @private + */ + this._modulationNode = new Tone.Gain(0); + //connections + this.frequency.chain(this.harmonicity, this._modulator.frequency); + this.detune.connect(this._modulator.detune); + this._modulator.chain(this._modulationScale, this._modulationNode.gain); + this._carrier.chain(this._modulationNode, this.output); + this.phase = options.phase; + this._readOnly([ + 'frequency', + 'detune', + 'harmonicity' + ]); + }; + Tone.extend(Tone.AMOscillator, Tone.Oscillator); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.AMOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'modulationType': 'square', + 'harmonicity': 1 + }; + /** + * start the oscillator + * @param {Time} [time=now] + * @private + */ + Tone.AMOscillator.prototype._start = function (time) { + time = this.toSeconds(time); + this._modulator.start(time); + this._carrier.start(time); + }; + /** + * stop the oscillator + * @param {Time} time (optional) timing parameter + * @private + */ + Tone.AMOscillator.prototype._stop = function (time) { + time = this.toSeconds(time); + this._modulator.stop(time); + this._carrier.stop(time); + }; + /** + * The type of the carrier oscillator + * @memberOf Tone.AMOscillator# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.AMOscillator.prototype, 'type', { + get: function () { + return this._carrier.type; + }, + set: function (type) { + this._carrier.type = type; + } + }); + /** + * The type of the modulator oscillator + * @memberOf Tone.AMOscillator# + * @type {string} + * @name modulationType + */ + Object.defineProperty(Tone.AMOscillator.prototype, 'modulationType', { + get: function () { + return this._modulator.type; + }, + set: function (type) { + this._modulator.type = type; + } + }); + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.AMOscillator# + * @type {number} + * @name phase + */ + Object.defineProperty(Tone.AMOscillator.prototype, 'phase', { + get: function () { + return this._carrier.phase; + }, + set: function (phase) { + this._carrier.phase = phase; + this._modulator.phase = phase; + } + }); + /** + * The partials of the carrier waveform. A partial represents + * the amplitude at a harmonic. The first harmonic is the + * fundamental frequency, the second is the octave and so on + * following the harmonic series. + * Setting this value will automatically set the type to "custom". + * The value is an empty array when the type is not "custom". + * @memberOf Tone.AMOscillator# + * @type {Array} + * @name partials + * @example + * osc.partials = [1, 0.2, 0.01]; + */ + Object.defineProperty(Tone.AMOscillator.prototype, 'partials', { + get: function () { + return this._carrier.partials; + }, + set: function (partials) { + this._carrier.partials = partials; + } + }); + /** + * Clean up. + * @return {Tone.AMOscillator} this + */ + Tone.AMOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'detune', + 'harmonicity' + ]); + this.frequency = null; + this.detune = null; + this.harmonicity.dispose(); + this.harmonicity = null; + this._carrier.dispose(); + this._carrier = null; + this._modulator.dispose(); + this._modulator = null; + this._modulationNode.dispose(); + this._modulationNode = null; + this._modulationScale.dispose(); + this._modulationScale = null; + return this; + }; + return Tone.AMOscillator; + }); + Module(function (Tone) { + + /** + * @class Tone.FatOscillator + * + * @extends {Tone.Oscillator} + * @constructor + * @param {Frequency} frequency The starting frequency of the oscillator. + * @param {String} type The type of the carrier oscillator. + * @param {String} modulationType The type of the modulator oscillator. + * @example + * //a sine oscillator frequency-modulated by a square wave + * var fmOsc = new Tone.FatOscillator("Ab3", "sine", "square").toMaster().start(); + */ + Tone.FatOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'type', + 'spread' + ], Tone.FatOscillator.defaults); + Tone.Source.call(this, options); + /** + * The oscillator's frequency + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The detune control signal. + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + /** + * The array of oscillators + * @type {Array} + * @private + */ + this._oscillators = []; + /** + * The total spread of the oscillators + * @type {Cents} + * @private + */ + this._spread = options.spread; + /** + * The type of the oscillator + * @type {String} + * @private + */ + this._type = options.type; + /** + * The phase of the oscillators + * @type {Degrees} + * @private + */ + this._phase = options.phase; + /** + * The partials array + * @type {Array} + * @private + */ + this._partials = this.defaultArg(options.partials, []); + //set the count initially + this.count = options.count; + this._readOnly([ + 'frequency', + 'detune' + ]); + }; + Tone.extend(Tone.FatOscillator, Tone.Oscillator); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.FatOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'phase': 0, + 'spread': 20, + 'count': 3, + 'type': 'sawtooth' + }; + /** + * start the oscillator + * @param {Time} [time=now] + * @private + */ + Tone.FatOscillator.prototype._start = function (time) { + time = this.toSeconds(time); + this._forEach(function (osc) { + osc.start(time); + }); + }; + /** + * stop the oscillator + * @param {Time} time (optional) timing parameter + * @private + */ + Tone.FatOscillator.prototype._stop = function (time) { + time = this.toSeconds(time); + this._forEach(function (osc) { + osc.stop(time); + }); + }; + /** + * Iterate over all of the oscillators + * @param {Function} iterator The iterator function + * @private + */ + Tone.FatOscillator.prototype._forEach = function (iterator) { + for (var i = 0; i < this._oscillators.length; i++) { + iterator.call(this, this._oscillators[i], i); + } + }; + /** + * The type of the carrier oscillator + * @memberOf Tone.FatOscillator# + * @type {string} + * @name type + */ + Object.defineProperty(Tone.FatOscillator.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + this._type = type; + this._forEach(function (osc) { + osc.type = type; + }); + } + }); + /** + * The detune spread between the oscillators. If "count" is + * set to 3 oscillators and the "spread" is set to 40, + * the three oscillators would be detuned like this: [-20, 0, 20] + * for a total detune spread of 40 cents. + * @memberOf Tone.FatOscillator# + * @type {Cents} + * @name spread + */ + Object.defineProperty(Tone.FatOscillator.prototype, 'spread', { + get: function () { + return this._spread; + }, + set: function (spread) { + this._spread = spread; + if (this._oscillators.length > 1) { + var start = -spread / 2; + var step = spread / (this._oscillators.length - 1); + this._forEach(function (osc, i) { + osc.detune.value = start + step * i; + }); + } + } + }); + /** + * The number of detuned oscillators + * @memberOf Tone.FatOscillator# + * @type {Number} + * @name count + */ + Object.defineProperty(Tone.FatOscillator.prototype, 'count', { + get: function () { + return this._oscillators.length; + }, + set: function (count) { + count = Math.max(count, 1); + if (this._oscillators.length !== count) { + // var partials = this.partials; + // var type = this.type; + //dispose the previous oscillators + this._forEach(function (osc) { + osc.dispose(); + }); + this._oscillators = []; + for (var i = 0; i < count; i++) { + var osc = new Tone.Oscillator(); + if (this.type === Tone.Oscillator.Type.Custom) { + osc.partials = this._partials; + } else { + osc.type = this._type; + } + osc.phase = this._phase; + osc.volume.value = -6 - count; + this.frequency.connect(osc.frequency); + this.detune.connect(osc.detune); + osc.connect(this.output); + this._oscillators[i] = osc; + } + //set the spread + this.spread = this._spread; + if (this.state === Tone.State.Started) { + this._forEach(function (osc) { + osc.start(); + }); + } + } + } + }); + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.FatOscillator# + * @type {Number} + * @name phase + */ + Object.defineProperty(Tone.FatOscillator.prototype, 'phase', { + get: function () { + return this._phase; + }, + set: function (phase) { + this._phase = phase; + this._forEach(function (osc) { + osc.phase = phase; + }); + } + }); + /** + * The partials of the carrier waveform. A partial represents + * the amplitude at a harmonic. The first harmonic is the + * fundamental frequency, the second is the octave and so on + * following the harmonic series. + * Setting this value will automatically set the type to "custom". + * The value is an empty array when the type is not "custom". + * @memberOf Tone.FatOscillator# + * @type {Array} + * @name partials + * @example + * osc.partials = [1, 0.2, 0.01]; + */ + Object.defineProperty(Tone.FatOscillator.prototype, 'partials', { + get: function () { + return this._partials; + }, + set: function (partials) { + this._partials = partials; + this._type = Tone.Oscillator.Type.Custom; + this._forEach(function (osc) { + osc.partials = partials; + }); + } + }); + /** + * Clean up. + * @return {Tone.FatOscillator} this + */ + Tone.FatOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'detune' + ]); + this.frequency.dispose(); + this.frequency = null; + this.detune.dispose(); + this.detune = null; + this._forEach(function (osc) { + osc.dispose(); + }); + this._oscillators = null; + this._partials = null; + return this; + }; + return Tone.FatOscillator; + }); + Module(function (Tone) { + + /** + * @class Tone.OmniOscillator aggregates Tone.Oscillator, Tone.PulseOscillator, + * Tone.PWMOscillator, Tone.FMOscillator, Tone.AMOscillator, and Tone.FatOscillator + * into one class. The oscillator class can be changed by setting the `type`. + * `omniOsc.type = "pwm"` will set it to the Tone.PWMOscillator. Prefixing + * any of the basic types ("sine", "square4", etc.) with "fm", "am", or "fat" + * will use the FMOscillator, AMOscillator or FatOscillator respectively. + * For example: `omniOsc.type = "fatsawtooth"` will create set the oscillator + * to a FatOscillator of type "sawtooth". + * + * @extends {Tone.Oscillator} + * @constructor + * @param {Frequency} frequency The initial frequency of the oscillator. + * @param {String} type The type of the oscillator. + * @example + * var omniOsc = new Tone.OmniOscillator("C#4", "pwm"); + */ + Tone.OmniOscillator = function () { + var options = this.optionsObject(arguments, [ + 'frequency', + 'type' + ], Tone.OmniOscillator.defaults); + Tone.Source.call(this, options); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The detune control + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + /** + * the type of the oscillator source + * @type {String} + * @private + */ + this._sourceType = undefined; + /** + * the oscillator + * @type {Tone.Oscillator} + * @private + */ + this._oscillator = null; + //set the oscillator + this.type = options.type; + this._readOnly([ + 'frequency', + 'detune' + ]); + //set the options + this.set(options); + }; + Tone.extend(Tone.OmniOscillator, Tone.Oscillator); + /** + * default values + * @static + * @type {Object} + * @const + */ + Tone.OmniOscillator.defaults = { + 'frequency': 440, + 'detune': 0, + 'type': 'sine', + 'phase': 0 + }; + /** + * @enum {String} + * @private + */ + var OmniOscType = { + Pulse: 'PulseOscillator', + PWM: 'PWMOscillator', + Osc: 'Oscillator', + FM: 'FMOscillator', + AM: 'AMOscillator', + Fat: 'FatOscillator' + }; + /** + * start the oscillator + * @param {Time} [time=now] the time to start the oscillator + * @private + */ + Tone.OmniOscillator.prototype._start = function (time) { + this._oscillator.start(time); + }; + /** + * start the oscillator + * @param {Time} [time=now] the time to start the oscillator + * @private + */ + Tone.OmniOscillator.prototype._stop = function (time) { + this._oscillator.stop(time); + }; + /** + * The type of the oscillator. Can be any of the basic types: sine, square, triangle, sawtooth. Or + * prefix the basic types with "fm", "am", or "fat" to use the FMOscillator, AMOscillator or FatOscillator + * types. The oscillator could also be set to "pwm" or "pulse". All of the parameters of the + * oscillator's class are accessible when the oscillator is set to that type, but throws an error + * when it's not. + * + * @memberOf Tone.OmniOscillator# + * @type {String} + * @name type + * @example + * omniOsc.type = "pwm"; + * //modulationFrequency is parameter which is available + * //only when the type is "pwm". + * omniOsc.modulationFrequency.value = 0.5; + * @example + * //an square wave frequency modulated by a sawtooth + * omniOsc.type = "fmsquare"; + * omniOsc.modulationType = "sawtooth"; + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'type', { + get: function () { + var prefix = ''; + if (this._sourceType === OmniOscType.FM) { + prefix = 'fm'; + } else if (this._sourceType === OmniOscType.AM) { + prefix = 'am'; + } else if (this._sourceType === OmniOscType.Fat) { + prefix = 'fat'; + } + return prefix + this._oscillator.type; + }, + set: function (type) { + if (type.substr(0, 2) === 'fm') { + this._createNewOscillator(OmniOscType.FM); + this._oscillator.type = type.substr(2); + } else if (type.substr(0, 2) === 'am') { + this._createNewOscillator(OmniOscType.AM); + this._oscillator.type = type.substr(2); + } else if (type.substr(0, 3) === 'fat') { + this._createNewOscillator(OmniOscType.Fat); + this._oscillator.type = type.substr(3); + } else if (type === 'pwm') { + this._createNewOscillator(OmniOscType.PWM); + } else if (type === 'pulse') { + this._createNewOscillator(OmniOscType.Pulse); + } else { + this._createNewOscillator(OmniOscType.Osc); + this._oscillator.type = type; + } + } + }); + /** + * The partials of the waveform. A partial represents + * the amplitude at a harmonic. The first harmonic is the + * fundamental frequency, the second is the octave and so on + * following the harmonic series. + * Setting this value will automatically set the type to "custom". + * The value is an empty array when the type is not "custom". + * This is not available on "pwm" and "pulse" oscillator types. + * @memberOf Tone.OmniOscillator# + * @type {Array} + * @name partials + * @example + * osc.partials = [1, 0.2, 0.01]; + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'partials', { + get: function () { + return this._oscillator.partials; + }, + set: function (partials) { + this._oscillator.partials = partials; + } + }); + /** + * Set a member/attribute of the oscillator. + * @param {Object|String} params + * @param {number=} value + * @param {Time=} rampTime + * @returns {Tone.OmniOscillator} this + */ + Tone.OmniOscillator.prototype.set = function (params, value) { + //make sure the type is set first + if (params === 'type') { + this.type = value; + } else if (this.isObject(params) && params.hasOwnProperty('type')) { + this.type = params.type; + } + //then set the rest + Tone.prototype.set.apply(this, arguments); + return this; + }; + /** + * connect the oscillator to the frequency and detune signals + * @private + */ + Tone.OmniOscillator.prototype._createNewOscillator = function (oscType) { + if (oscType !== this._sourceType) { + this._sourceType = oscType; + var OscillatorConstructor = Tone[oscType]; + //short delay to avoid clicks on the change + var now = this.now() + this.blockTime; + if (this._oscillator !== null) { + var oldOsc = this._oscillator; + oldOsc.stop(now); + //dispose the old one + setTimeout(function () { + oldOsc.dispose(); + oldOsc = null; + }, this.blockTime * 1000); + } + this._oscillator = new OscillatorConstructor(); + this.frequency.connect(this._oscillator.frequency); + this.detune.connect(this._oscillator.detune); + this._oscillator.connect(this.output); + if (this.state === Tone.State.Started) { + this._oscillator.start(now); + } + } + }; + /** + * The phase of the oscillator in degrees. + * @memberOf Tone.OmniOscillator# + * @type {Degrees} + * @name phase + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'phase', { + get: function () { + return this._oscillator.phase; + }, + set: function (phase) { + this._oscillator.phase = phase; + } + }); + /** + * The width of the oscillator (only if the oscillator is set to "pulse") + * @memberOf Tone.OmniOscillator# + * @type {NormalRange} + * @signal + * @name width + * @example + * var omniOsc = new Tone.OmniOscillator(440, "pulse"); + * //can access the width attribute only if type === "pulse" + * omniOsc.width.value = 0.2; + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'width', { + get: function () { + if (this._sourceType === OmniOscType.Pulse) { + return this._oscillator.width; + } + } + }); + /** + * The number of detuned oscillators + * @memberOf Tone.OmniOscillator# + * @type {Number} + * @name count + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'count', { + get: function () { + if (this._sourceType === OmniOscType.Fat) { + return this._oscillator.count; + } + }, + set: function (count) { + if (this._sourceType === OmniOscType.Fat) { + this._oscillator.count = count; + } + } + }); + /** + * The detune spread between the oscillators. If "count" is + * set to 3 oscillators and the "spread" is set to 40, + * the three oscillators would be detuned like this: [-20, 0, 20] + * for a total detune spread of 40 cents. See Tone.FatOscillator + * for more info. + * @memberOf Tone.OmniOscillator# + * @type {Cents} + * @name spread + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'spread', { + get: function () { + if (this._sourceType === OmniOscType.Fat) { + return this._oscillator.spread; + } + }, + set: function (spread) { + if (this._sourceType === OmniOscType.Fat) { + this._oscillator.spread = spread; + } + } + }); + /** + * The type of the modulator oscillator. Only if the oscillator + * is set to "am" or "fm" types. see. Tone.AMOscillator or Tone.FMOscillator + * for more info. + * @memberOf Tone.OmniOscillator# + * @type {String} + * @name modulationType + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationType', { + get: function () { + if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { + return this._oscillator.modulationType; + } + }, + set: function (mType) { + if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { + this._oscillator.modulationType = mType; + } + } + }); + /** + * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the + * ratio of the frequency of the modulating signal (mf) to the amplitude of the + * modulating signal (ma) -- as in ma/mf. + * See Tone.FMOscillator for more info. + * @type {Positive} + * @signal + * @name modulationIndex + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationIndex', { + get: function () { + if (this._sourceType === OmniOscType.FM) { + return this._oscillator.modulationIndex; + } + } + }); + /** + * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. + * A harmonicity of 1 gives both oscillators the same frequency. + * Harmonicity = 2 means a change of an octave. See Tone.AMOscillator or Tone.FMOscillator + * for more info. + * @memberOf Tone.OmniOscillator# + * @signal + * @type {Positive} + * @name harmonicity + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'harmonicity', { + get: function () { + if (this._sourceType === OmniOscType.FM || this._sourceType === OmniOscType.AM) { + return this._oscillator.harmonicity; + } + } + }); + /** + * The modulationFrequency Signal of the oscillator + * (only if the oscillator type is set to pwm). See + * Tone.PWMOscillator for more info. + * @memberOf Tone.OmniOscillator# + * @type {Frequency} + * @signal + * @name modulationFrequency + * @example + * var omniOsc = new Tone.OmniOscillator(440, "pwm"); + * //can access the modulationFrequency attribute only if type === "pwm" + * omniOsc.modulationFrequency.value = 0.2; + */ + Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationFrequency', { + get: function () { + if (this._sourceType === OmniOscType.PWM) { + return this._oscillator.modulationFrequency; + } + } + }); + /** + * Clean up. + * @return {Tone.OmniOscillator} this + */ + Tone.OmniOscillator.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'detune' + ]); + this.detune.dispose(); + this.detune = null; + this.frequency.dispose(); + this.frequency = null; + this._oscillator.dispose(); + this._oscillator = null; + this._sourceType = null; + return this; + }; + return Tone.OmniOscillator; + }); + Module(function (Tone) { + + /** + * @class Base-class for all instruments + * + * @constructor + * @extends {Tone} + */ + Tone.Instrument = function (options) { + //get the defaults + options = this.defaultArg(options, Tone.Instrument.defaults); + /** + * The output and volume triming node + * @type {Tone.Volume} + * @private + */ + this._volume = this.output = new Tone.Volume(options.volume); + /** + * The volume of the output in decibels. + * @type {Decibels} + * @signal + * @example + * source.volume.value = -6; + */ + this.volume = this._volume.volume; + this._readOnly('volume'); + }; + Tone.extend(Tone.Instrument); + /** + * the default attributes + * @type {object} + */ + Tone.Instrument.defaults = { + /** the volume of the output in decibels */ + 'volume': 0 + }; + /** + * @abstract + * @param {string|number} note the note to trigger + * @param {Time} [time=now] the time to trigger the ntoe + * @param {number} [velocity=1] the velocity to trigger the note + */ + Tone.Instrument.prototype.triggerAttack = Tone.noOp; + /** + * @abstract + * @param {Time} [time=now] when to trigger the release + */ + Tone.Instrument.prototype.triggerRelease = Tone.noOp; + /** + * Trigger the attack and then the release after the duration. + * @param {Frequency} note The note to trigger. + * @param {Time} duration How long the note should be held for before + * triggering the release. This value must be greater than 0. + * @param {Time} [time=now] When the note should be triggered. + * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. + * @returns {Tone.Instrument} this + * @example + * //trigger "C4" for the duration of an 8th note + * synth.triggerAttackRelease("C4", "8n"); + */ + Tone.Instrument.prototype.triggerAttackRelease = function (note, duration, time, velocity) { + if (this.isUndef(time)) { + time = this.now() + this.blockTime; + } else { + time = this.toSeconds(time); + } + duration = this.toSeconds(duration); + this.triggerAttack(note, time, velocity); + this.triggerRelease(time + duration); + return this; + }; + /** + * clean up + * @returns {Tone.Instrument} this + */ + Tone.Instrument.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._volume.dispose(); + this._volume = null; + this._writable(['volume']); + this.volume = null; + return this; + }; + return Tone.Instrument; + }); + Module(function (Tone) { + + /** + * @class This is an abstract base class for other monophonic instruments to + * extend. IMPORTANT: It does not make any sound on its own and + * shouldn't be directly instantiated. + * + * @constructor + * @abstract + * @extends {Tone.Instrument} + */ + Tone.Monophonic = function (options) { + //get the defaults + options = this.defaultArg(options, Tone.Monophonic.defaults); + Tone.Instrument.call(this, options); + /** + * The glide time between notes. + * @type {Time} + */ + this.portamento = options.portamento; + }; + Tone.extend(Tone.Monophonic, Tone.Instrument); + /** + * @static + * @const + * @type {Object} + */ + Tone.Monophonic.defaults = { 'portamento': 0 }; + /** + * Trigger the attack of the note optionally with a given velocity. + * + * + * @param {Frequency} note The note to trigger. + * @param {Time} [time=now] When the note should start. + * @param {number} [velocity=1] velocity The velocity scaler + * determines how "loud" the note + * will be triggered. + * @returns {Tone.Monophonic} this + * @example + * synth.triggerAttack("C4"); + * @example + * //trigger the note a half second from now at half velocity + * synth.triggerAttack("C4", "+0.5", 0.5); + */ + Tone.Monophonic.prototype.triggerAttack = function (note, time, velocity) { + if (this.isUndef(time)) { + time = this.now() + this.blockTime; + } else { + time = this.toSeconds(time); + } + this._triggerEnvelopeAttack(time, velocity); + this.setNote(note, time); + return this; + }; + /** + * Trigger the release portion of the envelope + * @param {Time} [time=now] If no time is given, the release happens immediatly + * @returns {Tone.Monophonic} this + * @example + * synth.triggerRelease(); + */ + Tone.Monophonic.prototype.triggerRelease = function (time) { + if (this.isUndef(time)) { + time = this.now() + this.blockTime; + } else { + time = this.toSeconds(time); + } + this._triggerEnvelopeRelease(time); + return this; + }; + /** + * override this method with the actual method + * @abstract + * @private + */ + Tone.Monophonic.prototype._triggerEnvelopeAttack = function () { + }; + /** + * override this method with the actual method + * @abstract + * @private + */ + Tone.Monophonic.prototype._triggerEnvelopeRelease = function () { + }; + /** + * Set the note at the given time. If no time is given, the note + * will set immediately. + * @param {Frequency} note The note to change to. + * @param {Time} [time=now] The time when the note should be set. + * @returns {Tone.Monophonic} this + * @example + * //change to F#6 in one quarter note from now. + * synth.setNote("F#6", "+4n"); + * @example + * //change to Bb4 right now + * synth.setNote("Bb4"); + */ + Tone.Monophonic.prototype.setNote = function (note, time) { + time = this.toSeconds(time); + if (this.portamento > 0) { + var currentNote = this.frequency.value; + this.frequency.setValueAtTime(currentNote, time); + var portTime = this.toSeconds(this.portamento); + this.frequency.exponentialRampToValueAtTime(note, time + portTime); + } else { + this.frequency.setValueAtTime(note, time); + } + return this; + }; + return Tone.Monophonic; + }); + Module(function (Tone) { + + /** + * @class Tone.Synth is composed simply of a Tone.OmniOscillator + * routed through a Tone.AmplitudeEnvelope. + * + * + * @constructor + * @extends {Tone.Monophonic} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var synth = new Tone.Synth().toMaster(); + * synth.triggerAttackRelease("C4", "8n"); + */ + Tone.Synth = function (options) { + //get the defaults + options = this.defaultArg(options, Tone.Synth.defaults); + Tone.Monophonic.call(this, options); + /** + * The oscillator. + * @type {Tone.OmniOscillator} + */ + this.oscillator = new Tone.OmniOscillator(options.oscillator); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = this.oscillator.frequency; + /** + * The detune control. + * @type {Cents} + * @signal + */ + this.detune = this.oscillator.detune; + /** + * The amplitude envelope. + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = new Tone.AmplitudeEnvelope(options.envelope); + //connect the oscillators to the output + this.oscillator.chain(this.envelope, this.output); + //start the oscillators + this.oscillator.start(); + this._readOnly([ + 'oscillator', + 'frequency', + 'detune', + 'envelope' + ]); + }; + Tone.extend(Tone.Synth, Tone.Monophonic); + /** + * @const + * @static + * @type {Object} + */ + Tone.Synth.defaults = { + 'oscillator': { 'type': 'triangle' }, + 'envelope': { + 'attack': 0.005, + 'decay': 0.1, + 'sustain': 0.3, + 'release': 1 + } + }; + /** + * start the attack portion of the envelope + * @param {Time} [time=now] the time the attack should start + * @param {number} [velocity=1] the velocity of the note (0-1) + * @returns {Tone.Synth} this + * @private + */ + Tone.Synth.prototype._triggerEnvelopeAttack = function (time, velocity) { + //the envelopes + this.envelope.triggerAttack(time, velocity); + return this; + }; + /** + * start the release portion of the envelope + * @param {Time} [time=now] the time the release should start + * @returns {Tone.Synth} this + * @private + */ + Tone.Synth.prototype._triggerEnvelopeRelease = function (time) { + this.envelope.triggerRelease(time); + return this; + }; + /** + * clean up + * @returns {Tone.Synth} this + */ + Tone.Synth.prototype.dispose = function () { + Tone.Monophonic.prototype.dispose.call(this); + this._writable([ + 'oscillator', + 'frequency', + 'detune', + 'envelope' + ]); + this.oscillator.dispose(); + this.oscillator = null; + this.envelope.dispose(); + this.envelope = null; + this.frequency = null; + this.detune = null; + return this; + }; + return Tone.Synth; + }); + Module(function (Tone) { + + /** + * @class AMSynth uses the output of one Tone.Synth to modulate the + * amplitude of another Tone.Synth. The harmonicity (the ratio between + * the two signals) affects the timbre of the output signal greatly. + * Read more about Amplitude Modulation Synthesis on + * [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). + * + * + * @constructor + * @extends {Tone.Monophonic} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var synth = new Tone.AMSynth().toMaster(); + * synth.triggerAttackRelease("C4", "4n"); + */ + Tone.AMSynth = function (options) { + options = this.defaultArg(options, Tone.AMSynth.defaults); + Tone.Monophonic.call(this, options); + /** + * The carrier voice. + * @type {Tone.Synth} + * @private + */ + this._carrier = new Tone.Synth(); + this._carrier.volume.value = -10; + /** + * The carrier's oscillator + * @type {Tone.Oscillator} + */ + this.oscillator = this._carrier.oscillator; + /** + * The carrier's envelope + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = this._carrier.envelope.set(options.envelope); + /** + * The modulator voice. + * @type {Tone.Synth} + * @private + */ + this._modulator = new Tone.Synth(); + this._modulator.volume.value = -10; + /** + * The modulator's oscillator which is applied + * to the amplitude of the oscillator + * @type {Tone.Oscillator} + */ + this.modulation = this._modulator.oscillator.set(options.modulation); + /** + * The modulator's envelope + * @type {Tone.AmplitudeEnvelope} + */ + this.modulationEnvelope = this._modulator.envelope.set(options.modulationEnvelope); + /** + * The frequency. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(440, Tone.Type.Frequency); + /** + * The detune in cents + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + /** + * Harmonicity is the ratio between the two voices. A harmonicity of + * 1 is no change. Harmonicity = 2 means a change of an octave. + * @type {Positive} + * @signal + * @example + * //pitch voice1 an octave below voice0 + * synth.harmonicity.value = 0.5; + */ + this.harmonicity = new Tone.Multiply(options.harmonicity); + this.harmonicity.units = Tone.Type.Positive; + /** + * convert the -1,1 output to 0,1 + * @type {Tone.AudioToGain} + * @private + */ + this._modulationScale = new Tone.AudioToGain(); + /** + * the node where the modulation happens + * @type {Tone.Gain} + * @private + */ + this._modulationNode = new Tone.Gain(); + //control the two voices frequency + this.frequency.connect(this._carrier.frequency); + this.frequency.chain(this.harmonicity, this._modulator.frequency); + this.detune.fan(this._carrier.detune, this._modulator.detune); + this._modulator.chain(this._modulationScale, this._modulationNode.gain); + this._carrier.chain(this._modulationNode, this.output); + this._readOnly([ + 'frequency', + 'harmonicity', + 'oscillator', + 'envelope', + 'modulation', + 'modulationEnvelope', + 'detune' + ]); + }; + Tone.extend(Tone.AMSynth, Tone.Monophonic); + /** + * @static + * @type {Object} + */ + Tone.AMSynth.defaults = { + 'harmonicity': 3, + 'detune': 0, + 'oscillator': { 'type': 'sine' }, + 'envelope': { + 'attack': 0.01, + 'decay': 0.01, + 'sustain': 1, + 'release': 0.5 + }, + 'modulation': { 'type': 'square' }, + 'modulationEnvelope': { + 'attack': 0.5, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + } + }; + /** + * trigger the attack portion of the note + * + * @param {Time} [time=now] the time the note will occur + * @param {NormalRange} [velocity=1] the velocity of the note + * @private + * @returns {Tone.AMSynth} this + */ + Tone.AMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { + //the port glide + time = this.toSeconds(time); + //the envelopes + this.envelope.triggerAttack(time, velocity); + this.modulationEnvelope.triggerAttack(time, velocity); + return this; + }; + /** + * trigger the release portion of the note + * + * @param {Time} [time=now] the time the note will release + * @private + * @returns {Tone.AMSynth} this + */ + Tone.AMSynth.prototype._triggerEnvelopeRelease = function (time) { + this.envelope.triggerRelease(time); + this.modulationEnvelope.triggerRelease(time); + return this; + }; + /** + * clean up + * @returns {Tone.AMSynth} this + */ + Tone.AMSynth.prototype.dispose = function () { + Tone.Monophonic.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'harmonicity', + 'oscillator', + 'envelope', + 'modulation', + 'modulationEnvelope', + 'detune' + ]); + this._carrier.dispose(); + this._carrier = null; + this._modulator.dispose(); + this._modulator = null; + this.frequency.dispose(); + this.frequency = null; + this.detune.dispose(); + this.detune = null; + this.harmonicity.dispose(); + this.harmonicity = null; + this._modulationScale.dispose(); + this._modulationScale = null; + this._modulationNode.dispose(); + this._modulationNode = null; + this.oscillator = null; + this.envelope = null; + this.modulationEnvelope = null; + this.modulation = null; + return this; + }; + return Tone.AMSynth; + }); + Module(function (Tone) { + + /** + * @class Tone.MonoSynth is composed of one oscillator, one filter, and two envelopes. + * The amplitude of the Tone.Oscillator and the cutoff frequency of the + * Tone.Filter are controlled by Tone.Envelopes. + * + * + * @constructor + * @extends {Tone.Monophonic} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var synth = new Tone.MonoSynth({ + * "oscillator" : { + * "type" : "square" + * }, + * "envelope" : { + * "attack" : 0.1 + * } + * }).toMaster(); + * synth.triggerAttackRelease("C4", "8n"); + */ + Tone.MonoSynth = function (options) { + //get the defaults + options = this.defaultArg(options, Tone.MonoSynth.defaults); + Tone.Monophonic.call(this, options); + /** + * The oscillator. + * @type {Tone.OmniOscillator} + */ + this.oscillator = new Tone.OmniOscillator(options.oscillator); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = this.oscillator.frequency; + /** + * The detune control. + * @type {Cents} + * @signal + */ + this.detune = this.oscillator.detune; + /** + * The filter. + * @type {Tone.Filter} + */ + this.filter = new Tone.Filter(options.filter); + /** + * The filter envelope. + * @type {Tone.FrequencyEnvelope} + */ + this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); + /** + * The amplitude envelope. + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = new Tone.AmplitudeEnvelope(options.envelope); + //connect the oscillators to the output + this.oscillator.chain(this.filter, this.envelope, this.output); + //start the oscillators + this.oscillator.start(); + //connect the filter envelope + this.filterEnvelope.connect(this.filter.frequency); + this._readOnly([ + 'oscillator', + 'frequency', + 'detune', + 'filter', + 'filterEnvelope', + 'envelope' + ]); + }; + Tone.extend(Tone.MonoSynth, Tone.Monophonic); + /** + * @const + * @static + * @type {Object} + */ + Tone.MonoSynth.defaults = { + 'frequency': 'C4', + 'detune': 0, + 'oscillator': { 'type': 'square' }, + 'filter': { + 'Q': 6, + 'type': 'lowpass', + 'rolloff': -24 + }, + 'envelope': { + 'attack': 0.005, + 'decay': 0.1, + 'sustain': 0.9, + 'release': 1 + }, + 'filterEnvelope': { + 'attack': 0.06, + 'decay': 0.2, + 'sustain': 0.5, + 'release': 2, + 'baseFrequency': 200, + 'octaves': 7, + 'exponent': 2 + } + }; + /** + * start the attack portion of the envelope + * @param {Time} [time=now] the time the attack should start + * @param {NormalRange} [velocity=1] the velocity of the note (0-1) + * @returns {Tone.MonoSynth} this + * @private + */ + Tone.MonoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { + //the envelopes + this.envelope.triggerAttack(time, velocity); + this.filterEnvelope.triggerAttack(time); + return this; + }; + /** + * start the release portion of the envelope + * @param {Time} [time=now] the time the release should start + * @returns {Tone.MonoSynth} this + * @private + */ + Tone.MonoSynth.prototype._triggerEnvelopeRelease = function (time) { + this.envelope.triggerRelease(time); + this.filterEnvelope.triggerRelease(time); + return this; + }; + /** + * clean up + * @returns {Tone.MonoSynth} this + */ + Tone.MonoSynth.prototype.dispose = function () { + Tone.Monophonic.prototype.dispose.call(this); + this._writable([ + 'oscillator', + 'frequency', + 'detune', + 'filter', + 'filterEnvelope', + 'envelope' + ]); + this.oscillator.dispose(); + this.oscillator = null; + this.envelope.dispose(); + this.envelope = null; + this.filterEnvelope.dispose(); + this.filterEnvelope = null; + this.filter.dispose(); + this.filter = null; + this.frequency = null; + this.detune = null; + return this; + }; + return Tone.MonoSynth; + }); + Module(function (Tone) { + + /** + * @class Tone.DuoSynth is a monophonic synth composed of two + * MonoSynths run in parallel with control over the + * frequency ratio between the two voices and vibrato effect. + * + * + * @constructor + * @extends {Tone.Monophonic} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var duoSynth = new Tone.DuoSynth().toMaster(); + * duoSynth.triggerAttackRelease("C4", "2n"); + */ + Tone.DuoSynth = function (options) { + options = this.defaultArg(options, Tone.DuoSynth.defaults); + Tone.Monophonic.call(this, options); + /** + * the first voice + * @type {Tone.MonoSynth} + */ + this.voice0 = new Tone.MonoSynth(options.voice0); + this.voice0.volume.value = -10; + /** + * the second voice + * @type {Tone.MonoSynth} + */ + this.voice1 = new Tone.MonoSynth(options.voice1); + this.voice1.volume.value = -10; + /** + * The vibrato LFO. + * @type {Tone.LFO} + * @private + */ + this._vibrato = new Tone.LFO(options.vibratoRate, -50, 50); + this._vibrato.start(); + /** + * the vibrato frequency + * @type {Frequency} + * @signal + */ + this.vibratoRate = this._vibrato.frequency; + /** + * the vibrato gain + * @type {Tone.Gain} + * @private + */ + this._vibratoGain = new Tone.Gain(options.vibratoAmount, Tone.Type.Positive); + /** + * The amount of vibrato + * @type {Positive} + * @signal + */ + this.vibratoAmount = this._vibratoGain.gain; + /** + * the frequency control + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(440, Tone.Type.Frequency); + /** + * Harmonicity is the ratio between the two voices. A harmonicity of + * 1 is no change. Harmonicity = 2 means a change of an octave. + * @type {Positive} + * @signal + * @example + * //pitch voice1 an octave below voice0 + * duoSynth.harmonicity.value = 0.5; + */ + this.harmonicity = new Tone.Multiply(options.harmonicity); + this.harmonicity.units = Tone.Type.Positive; + //control the two voices frequency + this.frequency.connect(this.voice0.frequency); + this.frequency.chain(this.harmonicity, this.voice1.frequency); + this._vibrato.connect(this._vibratoGain); + this._vibratoGain.fan(this.voice0.detune, this.voice1.detune); + this.voice0.connect(this.output); + this.voice1.connect(this.output); + this._readOnly([ + 'voice0', + 'voice1', + 'frequency', + 'vibratoAmount', + 'vibratoRate' + ]); + }; + Tone.extend(Tone.DuoSynth, Tone.Monophonic); + /** + * @static + * @type {Object} + */ + Tone.DuoSynth.defaults = { + 'vibratoAmount': 0.5, + 'vibratoRate': 5, + 'harmonicity': 1.5, + 'voice0': { + 'volume': -10, + 'portamento': 0, + 'oscillator': { 'type': 'sine' }, + 'filterEnvelope': { + 'attack': 0.01, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + }, + 'envelope': { + 'attack': 0.01, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + } + }, + 'voice1': { + 'volume': -10, + 'portamento': 0, + 'oscillator': { 'type': 'sine' }, + 'filterEnvelope': { + 'attack': 0.01, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + }, + 'envelope': { + 'attack': 0.01, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + } + } + }; + /** + * start the attack portion of the envelopes + * + * @param {Time} [time=now] the time the attack should start + * @param {NormalRange} [velocity=1] the velocity of the note (0-1) + * @returns {Tone.DuoSynth} this + * @private + */ + Tone.DuoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { + time = this.toSeconds(time); + this.voice0.envelope.triggerAttack(time, velocity); + this.voice1.envelope.triggerAttack(time, velocity); + this.voice0.filterEnvelope.triggerAttack(time); + this.voice1.filterEnvelope.triggerAttack(time); + return this; + }; + /** + * start the release portion of the envelopes + * + * @param {Time} [time=now] the time the release should start + * @returns {Tone.DuoSynth} this + * @private + */ + Tone.DuoSynth.prototype._triggerEnvelopeRelease = function (time) { + this.voice0.triggerRelease(time); + this.voice1.triggerRelease(time); + return this; + }; + /** + * clean up + * @returns {Tone.DuoSynth} this + */ + Tone.DuoSynth.prototype.dispose = function () { + Tone.Monophonic.prototype.dispose.call(this); + this._writable([ + 'voice0', + 'voice1', + 'frequency', + 'vibratoAmount', + 'vibratoRate' + ]); + this.voice0.dispose(); + this.voice0 = null; + this.voice1.dispose(); + this.voice1 = null; + this.frequency.dispose(); + this.frequency = null; + this._vibratoGain.dispose(); + this._vibratoGain = null; + this._vibrato = null; + this.harmonicity.dispose(); + this.harmonicity = null; + this.vibratoAmount.dispose(); + this.vibratoAmount = null; + this.vibratoRate = null; + return this; + }; + return Tone.DuoSynth; + }); + Module(function (Tone) { + + /** + * @class FMSynth is composed of two Tone.Synths where one Tone.Synth modulates + * the frequency of a second Tone.Synth. A lot of spectral content + * can be explored using the modulationIndex parameter. Read more about + * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). + * + * + * @constructor + * @extends {Tone.Monophonic} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var fmSynth = new Tone.FMSynth().toMaster(); + * fmSynth.triggerAttackRelease("C5", "4n"); + */ + Tone.FMSynth = function (options) { + options = this.defaultArg(options, Tone.FMSynth.defaults); + Tone.Monophonic.call(this, options); + /** + * The carrier voice. + * @type {Tone.Synth} + * @private + */ + this._carrier = new Tone.Synth(options.carrier); + this._carrier.volume.value = -10; + /** + * The carrier's oscillator + * @type {Tone.Oscillator} + */ + this.oscillator = this._carrier.oscillator; + /** + * The carrier's envelope + * @type {Tone.Oscillator} + */ + this.envelope = this._carrier.envelope.set(options.envelope); + /** + * The modulator voice. + * @type {Tone.Synth} + * @private + */ + this._modulator = new Tone.Synth(options.modulator); + this._modulator.volume.value = -10; + /** + * The modulator's oscillator which is applied + * to the amplitude of the oscillator + * @type {Tone.Oscillator} + */ + this.modulation = this._modulator.oscillator.set(options.modulation); + /** + * The modulator's envelope + * @type {Tone.Oscillator} + */ + this.modulationEnvelope = this._modulator.envelope.set(options.modulationEnvelope); + /** + * The frequency control. + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(440, Tone.Type.Frequency); + /** + * The detune in cents + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + /** + * Harmonicity is the ratio between the two voices. A harmonicity of + * 1 is no change. Harmonicity = 2 means a change of an octave. + * @type {Positive} + * @signal + * @example + * //pitch voice1 an octave below voice0 + * synth.harmonicity.value = 0.5; + */ + this.harmonicity = new Tone.Multiply(options.harmonicity); + this.harmonicity.units = Tone.Type.Positive; + /** + * The modulation index which essentially the depth or amount of the modulation. It is the + * ratio of the frequency of the modulating signal (mf) to the amplitude of the + * modulating signal (ma) -- as in ma/mf. + * @type {Positive} + * @signal + */ + this.modulationIndex = new Tone.Multiply(options.modulationIndex); + this.modulationIndex.units = Tone.Type.Positive; + /** + * the node where the modulation happens + * @type {GainNode} + * @private + */ + this._modulationNode = new Tone.Gain(0); + //control the two voices frequency + this.frequency.connect(this._carrier.frequency); + this.frequency.chain(this.harmonicity, this._modulator.frequency); + this.frequency.chain(this.modulationIndex, this._modulationNode); + this.detune.fan(this._carrier.detune, this._modulator.detune); + this._modulator.connect(this._modulationNode.gain); + this._modulationNode.connect(this._carrier.frequency); + this._carrier.connect(this.output); + this._readOnly([ + 'frequency', + 'harmonicity', + 'modulationIndex', + 'oscillator', + 'envelope', + 'modulation', + 'modulationEnvelope', + 'detune' + ]); + }; + Tone.extend(Tone.FMSynth, Tone.Monophonic); + /** + * @static + * @type {Object} + */ + Tone.FMSynth.defaults = { + 'harmonicity': 3, + 'modulationIndex': 10, + 'detune': 0, + 'oscillator': { 'type': 'sine' }, + 'envelope': { + 'attack': 0.01, + 'decay': 0.01, + 'sustain': 1, + 'release': 0.5 + }, + 'modulation': { 'type': 'square' }, + 'modulationEnvelope': { + 'attack': 0.5, + 'decay': 0, + 'sustain': 1, + 'release': 0.5 + } + }; + /** + * trigger the attack portion of the note + * + * @param {Time} [time=now] the time the note will occur + * @param {number} [velocity=1] the velocity of the note + * @returns {Tone.FMSynth} this + * @private + */ + Tone.FMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { + time = this.toSeconds(time); + //the envelopes + this.envelope.triggerAttack(time, velocity); + this.modulationEnvelope.triggerAttack(time); + return this; + }; + /** + * trigger the release portion of the note + * + * @param {Time} [time=now] the time the note will release + * @returns {Tone.FMSynth} this + * @private + */ + Tone.FMSynth.prototype._triggerEnvelopeRelease = function (time) { + time = this.toSeconds(time); + this.envelope.triggerRelease(time); + this.modulationEnvelope.triggerRelease(time); + return this; + }; + /** + * clean up + * @returns {Tone.FMSynth} this + */ + Tone.FMSynth.prototype.dispose = function () { + Tone.Monophonic.prototype.dispose.call(this); + this._writable([ + 'frequency', + 'harmonicity', + 'modulationIndex', + 'oscillator', + 'envelope', + 'modulation', + 'modulationEnvelope', + 'detune' + ]); + this._carrier.dispose(); + this._carrier = null; + this._modulator.dispose(); + this._modulator = null; + this.frequency.dispose(); + this.frequency = null; + this.detune.dispose(); + this.detune = null; + this.modulationIndex.dispose(); + this.modulationIndex = null; + this.harmonicity.dispose(); + this.harmonicity = null; + this._modulationNode.dispose(); + this._modulationNode = null; + this.oscillator = null; + this.envelope = null; + this.modulationEnvelope = null; + this.modulation = null; + return this; + }; + return Tone.FMSynth; + }); + Module(function (Tone) { + + /** + * @class Tone.MembraneSynth makes kick and tom sounds using a single oscillator + * with an amplitude envelope and frequency ramp. A Tone.OmniOscillator + * is routed through a Tone.AmplitudeEnvelope to the output. The drum + * quality of the sound comes from the frequency envelope applied + * during during Tone.MembraneSynth.triggerAttack(note). The frequency + * envelope starts at note * .octaves and ramps to + * note over the duration of .pitchDecay. + * + * @constructor + * @extends {Tone.Instrument} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var synth = new Tone.MembraneSynth().toMaster(); + * synth.triggerAttackRelease("C2", "8n"); + */ + Tone.MembraneSynth = function (options) { + options = this.defaultArg(options, Tone.MembraneSynth.defaults); + Tone.Instrument.call(this, options); + /** + * The oscillator. + * @type {Tone.OmniOscillator} + */ + this.oscillator = new Tone.OmniOscillator(options.oscillator).start(); + /** + * The amplitude envelope. + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = new Tone.AmplitudeEnvelope(options.envelope); + /** + * The number of octaves the pitch envelope ramps. + * @type {Positive} + */ + this.octaves = options.octaves; + /** + * The amount of time the frequency envelope takes. + * @type {Time} + */ + this.pitchDecay = options.pitchDecay; + this.oscillator.chain(this.envelope, this.output); + this._readOnly([ + 'oscillator', + 'envelope' + ]); + }; + Tone.extend(Tone.MembraneSynth, Tone.Instrument); + /** + * @static + * @type {Object} + */ + Tone.MembraneSynth.defaults = { + 'pitchDecay': 0.05, + 'octaves': 10, + 'oscillator': { 'type': 'sine' }, + 'envelope': { + 'attack': 0.001, + 'decay': 0.4, + 'sustain': 0.01, + 'release': 1.4, + 'attackCurve': 'exponential' + } + }; + /** + * Trigger the note at the given time with the given velocity. + * + * @param {Frequency} note the note + * @param {Time} [time=now] the time, if not given is now + * @param {number} [velocity=1] velocity defaults to 1 + * @returns {Tone.MembraneSynth} this + * @example + * kick.triggerAttack(60); + */ + Tone.MembraneSynth.prototype.triggerAttack = function (note, time, velocity) { + time = this.toSeconds(time); + note = this.toFrequency(note); + var maxNote = note * this.octaves; + this.oscillator.frequency.setValueAtTime(maxNote, time); + this.oscillator.frequency.exponentialRampToValueAtTime(note, time + this.toSeconds(this.pitchDecay)); + this.envelope.triggerAttack(time, velocity); + return this; + }; + /** + * Trigger the release portion of the note. + * + * @param {Time} [time=now] the time the note will release + * @returns {Tone.MembraneSynth} this + */ + Tone.MembraneSynth.prototype.triggerRelease = function (time) { + this.envelope.triggerRelease(time); + return this; + }; + /** + * Clean up. + * @returns {Tone.MembraneSynth} this + */ + Tone.MembraneSynth.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + this._writable([ + 'oscillator', + 'envelope' + ]); + this.oscillator.dispose(); + this.oscillator = null; + this.envelope.dispose(); + this.envelope = null; + return this; + }; + return Tone.MembraneSynth; + }); + Module(function (Tone) { + /** + * Inharmonic ratio of frequencies based on the Roland TR-808 + * Taken from https://ccrma.stanford.edu/papers/tr-808-cymbal-physically-informed-circuit-bendable-digital-model + * @private + * @static + * @type {Array} + */ + var inharmRatios = [ + 1, + 1.483, + 1.932, + 2.546, + 2.63, + 3.897 + ]; + /** + * @class A highly inharmonic and spectrally complex source with a highpass filter + * and amplitude envelope which is good for making metalophone sounds. Based + * on CymbalSynth by [@polyrhythmatic](https://github.com/polyrhythmatic). + * Inspiration from [Sound on Sound](http://www.soundonsound.com/sos/jul02/articles/synthsecrets0702.asp). + * + * @constructor + * @extends {Tone.Instrument} + * @param {Object} [options] The options availble for the synth + * see defaults below + */ + Tone.MetalSynth = function (options) { + options = this.defaultArg(options, Tone.MetalSynth.defaults); + Tone.Instrument.call(this, options); + /** + * The frequency of the cymbal + * @type {Frequency} + * @signal + */ + this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); + /** + * The array of FMOscillators + * @type {Array} + * @private + */ + this._oscillators = []; + /** + * The frequency multipliers + * @type {Array} + * @private + */ + this._freqMultipliers = []; + /** + * The amplitude for the body + * @type {Tone.Gain} + * @private + */ + this._amplitue = new Tone.Gain(0).connect(this.output); + /** + * highpass the output + * @type {Tone.Filter} + * @private + */ + this._highpass = new Tone.Filter({ + 'type': 'highpass', + 'Q': -3.0102999566398125 + }).connect(this._amplitue); + /** + * The number of octaves the highpass + * filter frequency ramps + * @type {Number} + * @private + */ + this._octaves = options.octaves; + /** + * Scale the body envelope + * for the bandpass + * @type {Tone.Scale} + * @private + */ + this._filterFreqScaler = new Tone.Scale(options.resonance, 7000); + /** + * The envelope which is connected both to the + * amplitude and highpass filter's cutoff frequency + * @type {Tone.Envelope} + */ + this.envelope = new Tone.Envelope({ + 'attack': options.envelope.attack, + 'attackCurve': 'linear', + 'decay': options.envelope.decay, + 'sustain': 0, + 'release': options.envelope.release + }).chain(this._filterFreqScaler, this._highpass.frequency); + this.envelope.connect(this._amplitue.gain); + for (var i = 0; i < inharmRatios.length; i++) { + var osc = new Tone.FMOscillator({ + 'type': 'square', + 'modulationType': 'square', + 'harmonicity': options.harmonicity, + 'modulationIndex': options.modulationIndex + }); + osc.connect(this._highpass).start(0); + this._oscillators[i] = osc; + var mult = new Tone.Multiply(inharmRatios[i]); + this._freqMultipliers[i] = mult; + this.frequency.chain(mult, osc.frequency); + } + //set the octaves + this.octaves = options.octaves; + }; + Tone.extend(Tone.MetalSynth, Tone.Instrument); + /** + * default values + * @static + * @const + * @type {Object} + */ + Tone.MetalSynth.defaults = { + 'frequency': 200, + 'envelope': { + 'attack': 0.001, + 'decay': 1.4, + 'release': 0.2 + }, + 'harmonicity': 5.1, + 'modulationIndex': 32, + 'resonance': 4000, + 'octaves': 1.5 + }; + /** + * Trigger the attack. + * @param {Time} time When the attack should be triggered. + * @param {NormalRange=1} velocity The velocity that the envelope should be triggered at. + * @return {Tone.MetalSynth} this + */ + Tone.MetalSynth.prototype.triggerAttack = function (time, vel) { + time = this.toSeconds(time); + vel = this.defaultArg(vel, 1); + this.envelope.triggerAttack(time, vel); + return this; + }; + /** + * Trigger the release of the envelope. + * @param {Time} time When the release should be triggered. + * @return {Tone.MetalSynth} this + */ + Tone.MetalSynth.prototype.triggerRelease = function (time) { + time = this.toSeconds(time); + this.envelope.triggerRelease(time); + return this; + }; + /** + * Trigger the attack and release of the envelope after the given + * duration. + * @param {Time} duration The duration before triggering the release + * @param {Time} time When the attack should be triggered. + * @param {NormalRange=1} velocity The velocity that the envelope should be triggered at. + * @return {Tone.MetalSynth} this + */ + Tone.MetalSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { + time = this.toSeconds(time); + duration = this.toSeconds(duration); + this.triggerAttack(time, velocity); + this.triggerRelease(time + duration); + return this; + }; + /** + * The modulationIndex of the oscillators which make up the source. + * see Tone.FMOscillator.modulationIndex + * @memberOf Tone.MetalSynth# + * @type {Positive} + * @name modulationIndex + */ + Object.defineProperty(Tone.MetalSynth.prototype, 'modulationIndex', { + get: function () { + return this._oscillators[0].modulationIndex.value; + }, + set: function (val) { + for (var i = 0; i < this._oscillators.length; i++) { + this._oscillators[i].modulationIndex.value = val; + } + } + }); + /** + * The harmonicity of the oscillators which make up the source. + * see Tone.FMOscillator.harmonicity + * @memberOf Tone.MetalSynth# + * @type {Positive} + * @name harmonicity + */ + Object.defineProperty(Tone.MetalSynth.prototype, 'harmonicity', { + get: function () { + return this._oscillators[0].harmonicity.value; + }, + set: function (val) { + for (var i = 0; i < this._oscillators.length; i++) { + this._oscillators[i].harmonicity.value = val; + } + } + }); + /** + * The frequency of the highpass filter attached to the envelope + * @memberOf Tone.MetalSynth# + * @type {Frequency} + * @name resonance + */ + Object.defineProperty(Tone.MetalSynth.prototype, 'resonance', { + get: function () { + return this._filterFreqScaler.min; + }, + set: function (val) { + this._filterFreqScaler.min = val; + this.octaves = this._octaves; + } + }); + /** + * The number of octaves above the "resonance" frequency + * that the filter ramps during the attack/decay envelope + * @memberOf Tone.MetalSynth# + * @type {Number} + * @name octaves + */ + Object.defineProperty(Tone.MetalSynth.prototype, 'octaves', { + get: function () { + return this._octaves; + }, + set: function (octs) { + this._octaves = octs; + this._filterFreqScaler.max = this._filterFreqScaler.min * Math.pow(2, octs); + } + }); + /** + * Clean up + * @returns {Tone.MetalSynth} this + */ + Tone.MetalSynth.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + for (var i = 0; i < this._oscillators.length; i++) { + this._oscillators[i].dispose(); + this._freqMultipliers[i].dispose(); + } + this._oscillators = null; + this._freqMultipliers = null; + this.frequency.dispose(); + this.frequency = null; + this._filterFreqScaler.dispose(); + this._filterFreqScaler = null; + this._amplitue.dispose(); + this._amplitue = null; + this.envelope.dispose(); + this.envelope = null; + this._highpass.dispose(); + this._highpass = null; + }; + return Tone.MetalSynth; + }); + Module(function (Tone) { + /** + * BufferSource polyfill + */ + if (window.AudioBufferSourceNode && !AudioBufferSourceNode.prototype.start) { + AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; + AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; + } + /** + * @class Wrapper around the native BufferSourceNode. + * @param {AudioBuffer|Tone.Buffer} buffer The buffer to play + * @param {Function} onended The callback to invoke when the + * buffer is done playing. + */ + Tone.BufferSource = function () { + var options = this.optionsObject(arguments, [ + 'buffer', + 'onended' + ], Tone.BufferSource.defaults); + /** + * The callback to invoke after the + * buffer source is done playing. + * @type {Function} + */ + this.onended = options.onended; + /** + * The time that the buffer was started. + * @type {Number} + * @private + */ + this._startTime = -1; + /** + * The time that the buffer is scheduled to stop. + * @type {Number} + * @private + */ + this._stopTime = -1; + /** + * The gain node which envelopes the BufferSource + * @type {Tone.Gain} + * @private + */ + this._gainNode = this.output = new Tone.Gain(); + /** + * The buffer source + * @type {AudioBufferSourceNode} + * @private + */ + this._source = this.context.createBufferSource(); + this._source.connect(this._gainNode); + /** + * The playbackRate of the buffer + * @type {Positive} + * @signal + */ + this.playbackRate = new Tone.Param(this._source.playbackRate, Tone.Type.Positive); + /** + * The fadeIn time of the amplitude envelope. + * @type {Time} + */ + this.fadeIn = options.fadeIn; + /** + * The fadeOut time of the amplitude envelope. + * @type {Time} + */ + this.fadeOut = options.fadeOut; + /** + * The value that the buffer ramps to + * @type {Gain} + * @private + */ + this._gain = 1; + /** + * The onended timeout + * @type {Number} + * @private + */ + this._onendedTimeout = -1; + //set the buffer initially + if (!this.isUndef(options.buffer)) { + this.buffer = options.buffer; + } + this.loop = options.loop; + }; + Tone.extend(Tone.BufferSource); + /** + * The defaults + * @const + * @type {Object} + */ + Tone.BufferSource.defaults = { + 'onended': Tone.noOp, + 'fadeIn': 0, + 'fadeOut': 0 + }; + /** + * Returns the playback state of the source, either "started" or "stopped". + * @type {Tone.State} + * @readOnly + * @memberOf Tone.BufferSource# + * @name state + */ + Object.defineProperty(Tone.BufferSource.prototype, 'state', { + get: function () { + var now = this.now(); + if (this._startTime !== -1 && now >= this._startTime && now < this._stopTime) { + return Tone.State.Started; + } else { + return Tone.State.Stopped; + } + } + }); + /** + * Start the buffer + * @param {Time} [startTime=now] When the player should start. + * @param {Time} [offset=0] The offset from the beginning of the sample + * to start at. + * @param {Time=} duration How long the sample should play. If no duration + * is given, it will default to the full length + * of the sample (minus any offset) + * @param {Gain} [gain=1] The gain to play the buffer back at. + * @param {Time=} fadeInTime The optional fadeIn ramp time. + * @return {Tone.BufferSource} this + */ + Tone.BufferSource.prototype.start = function (time, offset, duration, gain, fadeInTime) { + if (this._startTime !== -1) { + throw new Error('Tone.BufferSource: can only be started once.'); + } + if (this.buffer) { + time = this.toSeconds(time); + //if it's a loop the default offset is the loopstart point + if (this.loop) { + offset = this.defaultArg(offset, this.loopStart); + } else { + //otherwise the default offset is 0 + offset = this.defaultArg(offset, 0); + } + offset = this.toSeconds(offset); + //the values in seconds + time = this.toSeconds(time); + this._source.start(time, offset); + gain = this.defaultArg(gain, 1); + this._gain = gain; + //the fadeIn time + if (this.isUndef(fadeInTime)) { + fadeInTime = this.toSeconds(this.fadeIn); + } else { + fadeInTime = this.toSeconds(fadeInTime); + } + if (fadeInTime > 0) { + this._gainNode.gain.setValueAtTime(0, time); + this._gainNode.gain.linearRampToValueAtTime(this._gain, time + fadeInTime); + } else { + this._gainNode.gain.setValueAtTime(gain, time); + } + this._startTime = time + fadeInTime; + if (!this.isUndef(duration)) { + duration = this.defaultArg(duration, this.buffer.duration - offset); + duration = this.toSeconds(duration); + this.stop(time + duration + fadeInTime, fadeInTime); + } + } + return this; + }; + /** + * Stop the buffer. Optionally add a ramp time to fade the + * buffer out. + * @param {Time=} time The time the buffer should stop. + * @param {Time=} fadeOutTime How long the gain should fade out for + * @return {Tone.BufferSource} this + */ + Tone.BufferSource.prototype.stop = function (time, fadeOutTime) { + if (this.buffer) { + time = this.toSeconds(time); + //the fadeOut time + if (this.isUndef(fadeOutTime)) { + fadeOutTime = this.toSeconds(this.fadeOut); + } else { + fadeOutTime = this.toSeconds(fadeOutTime); + } + this._stopTime = time + fadeOutTime; + //cancel the end curve + this._gainNode.gain.cancelScheduledValues(this._startTime + this.sampleTime); + //set a new one + if (fadeOutTime > 0) { + this._gainNode.gain.setValueAtTime(this._gain, time); + this._gainNode.gain.linearRampToValueAtTime(0, time + fadeOutTime); + time += fadeOutTime; + } else { + this._gainNode.gain.setValueAtTime(0, time); + } + // fix for safari bug and old FF + if (!this.isNumber(this._source.playbackState) || this._source.playbackState === 2) { + this._source.stop(time); + } + clearTimeout(this._onendedTimeout); + this._onendedTimeout = setTimeout(this._onended.bind(this), (this._stopTime - this.now()) * 1000); + } + return this; + }; + /** + * Internal callback when the buffer is ended. + * Invokes `onended` and disposes the node. + * @private + */ + Tone.BufferSource.prototype._onended = function () { + this.onended(this); + this.dispose(); + }; + /** + * If loop is true, the loop will start at this position. + * @memberOf Tone.BufferSource# + * @type {Time} + * @name loopStart + */ + Object.defineProperty(Tone.BufferSource.prototype, 'loopStart', { + get: function () { + return this._source.loopStart; + }, + set: function (loopStart) { + this._source.loopStart = this.toSeconds(loopStart); + } + }); + /** + * If loop is true, the loop will end at this position. + * @memberOf Tone.BufferSource# + * @type {Time} + * @name loopEnd + */ + Object.defineProperty(Tone.BufferSource.prototype, 'loopEnd', { + get: function () { + return this._source.loopEnd; + }, + set: function (loopEnd) { + this._source.loopEnd = this.toSeconds(loopEnd); + } + }); + /** + * The audio buffer belonging to the player. + * @memberOf Tone.BufferSource# + * @type {AudioBuffer} + * @name buffer + */ + Object.defineProperty(Tone.BufferSource.prototype, 'buffer', { + get: function () { + if (this._source) { + return this._source.buffer; + } else { + return null; + } + }, + set: function (buffer) { + if (buffer instanceof Tone.Buffer) { + this._source.buffer = buffer.get(); + } else { + this._source.buffer = buffer; + } + } + }); + /** + * If the buffer should loop once it's over. + * @memberOf Tone.BufferSource# + * @type {boolean} + * @name loop + */ + Object.defineProperty(Tone.BufferSource.prototype, 'loop', { + get: function () { + return this._source.loop; + }, + set: function (loop) { + this._source.loop = loop; + } + }); + /** + * Clean up. + * @return {Tone.BufferSource} this + */ + Tone.BufferSource.prototype.dispose = function () { + this.onended = null; + if (this._source) { + this._source.disconnect(); + this._source = null; + } + if (this._gainNode) { + this._gainNode.dispose(); + this._gainNode = null; + } + this._startTime = -1; + this.playbackRate = null; + this.output = null; + clearTimeout(this._onendedTimeout); + return this; + }; + return Tone.BufferSource; + }); + Module(function (Tone) { + + /** + * @class Tone.Noise is a noise generator. It uses looped noise buffers to save on performance. + * Tone.Noise supports the noise types: "pink", "white", and "brown". Read more about + * colors of noise on [Wikipedia](https://en.wikipedia.org/wiki/Colors_of_noise). + * + * @constructor + * @extends {Tone.Source} + * @param {string} type the noise type (white|pink|brown) + * @example + * //initialize the noise and start + * var noise = new Tone.Noise("pink").start(); + * + * //make an autofilter to shape the noise + * var autoFilter = new Tone.AutoFilter({ + * "frequency" : "8m", + * "min" : 800, + * "max" : 15000 + * }).connect(Tone.Master); + * + * //connect the noise + * noise.connect(autoFilter); + * //start the autofilter LFO + * autoFilter.start() + */ + Tone.Noise = function () { + var options = this.optionsObject(arguments, ['type'], Tone.Noise.defaults); + Tone.Source.call(this, options); + /** + * @private + * @type {AudioBufferSourceNode} + */ + this._source = null; + /** + * the buffer + * @private + * @type {AudioBuffer} + */ + this._type = options.type; + /** + * The playback rate of the noise. Affects + * the "frequency" of the noise. + * @type {Positive} + * @signal + */ + this._playbackRate = options.playbackRate; + }; + Tone.extend(Tone.Noise, Tone.Source); + /** + * the default parameters + * + * @static + * @const + * @type {Object} + */ + Tone.Noise.defaults = { + 'type': 'white', + 'playbackRate': 1 + }; + /** + * The type of the noise. Can be "white", "brown", or "pink". + * @memberOf Tone.Noise# + * @type {string} + * @name type + * @example + * noise.type = "white"; + */ + Object.defineProperty(Tone.Noise.prototype, 'type', { + get: function () { + return this._type; + }, + set: function (type) { + if (this._type !== type) { + if (type in _noiseBuffers) { + this._type = type; + //if it's playing, stop and restart it + if (this.state === Tone.State.Started) { + var now = this.now() + this.blockTime; + this._stop(now); + this._start(now); + } + } else { + throw new TypeError('Tone.Noise: invalid type: ' + type); + } + } + } + }); + /** + * The playback rate of the noise. Affects + * the "frequency" of the noise. + * @type {Positive} + * @signal + */ + Object.defineProperty(Tone.Noise.prototype, 'playbackRate', { + get: function () { + return this._playbackRate; + }, + set: function (rate) { + this._playbackRate = rate; + if (this._source) { + this._source.playbackRate.value = rate; + } + } + }); + /** + * internal start method + * + * @param {Time} time + * @private + */ + Tone.Noise.prototype._start = function (time) { + var buffer = _noiseBuffers[this._type]; + this._source = new Tone.BufferSource(buffer).connect(this.output); + this._source.loop = true; + this._source.playbackRate.value = this._playbackRate; + this._source.start(this.toSeconds(time), Math.random() * (buffer.duration - 0.001)); + }; + /** + * internal stop method + * + * @param {Time} time + * @private + */ + Tone.Noise.prototype._stop = function (time) { + if (this._source) { + this._source.stop(this.toSeconds(time)); + this._source = null; + } + }; + /** + * Clean up. + * @returns {Tone.Noise} this + */ + Tone.Noise.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + if (this._source !== null) { + this._source.disconnect(); + this._source = null; + } + this._buffer = null; + return this; + }; + /////////////////////////////////////////////////////////////////////////// + // THE BUFFERS + /////////////////////////////////////////////////////////////////////////// + //Noise buffer stats + var bufferLength = 44100 * 5; + var channels = 2; + /** + * the noise arrays. only generated once on init + * @static + * @private + * @type {Array} + * borrowed heavily from https://github.com/zacharydenton/noise.js + * (c) 2013 Zach Denton (MIT) + */ + var _noiseArrays = { + 'pink': function () { + var buffer = []; + for (var channelNum = 0; channelNum < channels; channelNum++) { + var channel = new Float32Array(bufferLength); + buffer[channelNum] = channel; + var b0, b1, b2, b3, b4, b5, b6; + b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; + for (var i = 0; i < bufferLength; i++) { + var white = Math.random() * 2 - 1; + b0 = 0.99886 * b0 + white * 0.0555179; + b1 = 0.99332 * b1 + white * 0.0750759; + b2 = 0.969 * b2 + white * 0.153852; + b3 = 0.8665 * b3 + white * 0.3104856; + b4 = 0.55 * b4 + white * 0.5329522; + b5 = -0.7616 * b5 - white * 0.016898; + channel[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; + channel[i] *= 0.11; + // (roughly) compensate for gain + b6 = white * 0.115926; + } + } + return buffer; + }(), + 'brown': function () { + var buffer = []; + for (var channelNum = 0; channelNum < channels; channelNum++) { + var channel = new Float32Array(bufferLength); + buffer[channelNum] = channel; + var lastOut = 0; + for (var i = 0; i < bufferLength; i++) { + var white = Math.random() * 2 - 1; + channel[i] = (lastOut + 0.02 * white) / 1.02; + lastOut = channel[i]; + channel[i] *= 3.5; // (roughly) compensate for gain + } + } + return buffer; + }(), + 'white': function () { + var buffer = []; + for (var channelNum = 0; channelNum < channels; channelNum++) { + var channel = new Float32Array(bufferLength); + buffer[channelNum] = channel; + for (var i = 0; i < bufferLength; i++) { + channel[i] = Math.random() * 2 - 1; + } + } + return buffer; + }() + }; + /** + * static noise buffers + * @static + * @private + * @type {Tone.Buffer} + */ + var _noiseBuffers = {}; + //create the Tone.Buffers + function createBuffers() { + for (var type in _noiseArrays) { + _noiseBuffers[type] = new Tone.Buffer().fromArray(_noiseArrays[type]); + } + } + createBuffers(); + Tone.Context.on('init', createBuffers); + return Tone.Noise; + }); + Module(function (Tone) { + + /** + * @class Tone.NoiseSynth is composed of a noise generator (Tone.Noise), one filter (Tone.Filter), + * and two envelopes (Tone.Envelop). One envelope controls the amplitude + * of the noise and the other is controls the cutoff frequency of the filter. + * + * + * @constructor + * @extends {Tone.Instrument} + * @param {Object} [options] the options available for the synth + * see defaults below + * @example + * var noiseSynth = new Tone.NoiseSynth().toMaster(); + * noiseSynth.triggerAttackRelease("8n"); + */ + Tone.NoiseSynth = function (options) { + //get the defaults + options = this.defaultArg(options, Tone.NoiseSynth.defaults); + Tone.Instrument.call(this, options); + /** + * The noise source. + * @type {Tone.Noise} + * @example + * noiseSynth.set("noise.type", "brown"); + */ + this.noise = new Tone.Noise(); + /** + * The amplitude envelope. + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = new Tone.AmplitudeEnvelope(options.envelope); + //connect the noise to the output + this.noise.chain(this.envelope, this.output); + //start the noise + this.noise.start(); + this._readOnly([ + 'noise', + 'envelope' + ]); + }; + Tone.extend(Tone.NoiseSynth, Tone.Instrument); + /** + * @const + * @static + * @type {Object} + */ + Tone.NoiseSynth.defaults = { + 'noise': { 'type': 'white' }, + 'envelope': { + 'attack': 0.005, + 'decay': 0.1, + 'sustain': 0 + } + }; + /** + * Start the attack portion of the envelopes. Unlike other + * instruments, Tone.NoiseSynth doesn't have a note. + * @param {Time} [time=now] the time the attack should start + * @param {number} [velocity=1] the velocity of the note (0-1) + * @returns {Tone.NoiseSynth} this + * @example + * noiseSynth.triggerAttack(); + */ + Tone.NoiseSynth.prototype.triggerAttack = function (time, velocity) { + //the envelopes + this.envelope.triggerAttack(time, velocity); + return this; + }; + /** + * Start the release portion of the envelopes. + * @param {Time} [time=now] the time the release should start + * @returns {Tone.NoiseSynth} this + */ + Tone.NoiseSynth.prototype.triggerRelease = function (time) { + this.envelope.triggerRelease(time); + return this; + }; + /** + * Trigger the attack and then the release. + * @param {Time} duration the duration of the note + * @param {Time} [time=now] the time of the attack + * @param {number} [velocity=1] the velocity + * @returns {Tone.NoiseSynth} this + */ + Tone.NoiseSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { + time = this.toSeconds(time); + duration = this.toSeconds(duration); + this.triggerAttack(time, velocity); + this.triggerRelease(time + duration); + return this; + }; + /** + * Clean up. + * @returns {Tone.NoiseSynth} this + */ + Tone.NoiseSynth.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + this._writable([ + 'noise', + 'envelope' + ]); + this.noise.dispose(); + this.noise = null; + this.envelope.dispose(); + this.envelope = null; + return this; + }; + return Tone.NoiseSynth; + }); + Module(function (Tone) { + + /** + * @class Karplus-String string synthesis. Often out of tune. + * Will change when the AudioWorkerNode is available across + * browsers. + * + * @constructor + * @extends {Tone.Instrument} + * @param {Object} [options] see the defaults + * @example + * var plucky = new Tone.PluckSynth().toMaster(); + * plucky.triggerAttack("C4"); + */ + Tone.PluckSynth = function (options) { + options = this.defaultArg(options, Tone.PluckSynth.defaults); + Tone.Instrument.call(this, options); + /** + * @type {Tone.Noise} + * @private + */ + this._noise = new Tone.Noise('pink'); + /** + * The amount of noise at the attack. + * Nominal range of [0.1, 20] + * @type {number} + */ + this.attackNoise = options.attackNoise; + /** + * the LFCF + * @type {Tone.LowpassCombFilter} + * @private + */ + this._lfcf = new Tone.LowpassCombFilter({ + 'resonance': options.resonance, + 'dampening': options.dampening + }); + /** + * The resonance control. + * @type {NormalRange} + * @signal + */ + this.resonance = this._lfcf.resonance; + /** + * The dampening control. i.e. the lowpass filter frequency of the comb filter + * @type {Frequency} + * @signal + */ + this.dampening = this._lfcf.dampening; + //connections + this._noise.connect(this._lfcf); + this._lfcf.connect(this.output); + this._readOnly([ + 'resonance', + 'dampening' + ]); + }; + Tone.extend(Tone.PluckSynth, Tone.Instrument); + /** + * @static + * @const + * @type {Object} + */ + Tone.PluckSynth.defaults = { + 'attackNoise': 1, + 'dampening': 4000, + 'resonance': 0.9 + }; + /** + * Trigger the note. + * @param {Frequency} note The note to trigger. + * @param {Time} [time=now] When the note should be triggered. + * @returns {Tone.PluckSynth} this + */ + Tone.PluckSynth.prototype.triggerAttack = function (note, time) { + note = this.toFrequency(note); + time = this.toSeconds(time); + var delayAmount = 1 / note; + this._lfcf.delayTime.setValueAtTime(delayAmount, time); + this._noise.start(time); + this._noise.stop(time + delayAmount * this.attackNoise); + return this; + }; + /** + * Clean up. + * @returns {Tone.PluckSynth} this + */ + Tone.PluckSynth.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + this._noise.dispose(); + this._lfcf.dispose(); + this._noise = null; + this._lfcf = null; + this._writable([ + 'resonance', + 'dampening' + ]); + this.dampening = null; + this.resonance = null; + return this; + }; + return Tone.PluckSynth; + }); + Module(function (Tone) { + + /** + * @class Tone.PolySynth handles voice creation and allocation for any + * instruments passed in as the second paramter. PolySynth is + * not a synthesizer by itself, it merely manages voices of + * one of the other types of synths, allowing any of the + * monophonic synthesizers to be polyphonic. + * + * @constructor + * @extends {Tone.Instrument} + * @param {number|Object} [polyphony=4] The number of voices to create + * @param {function} [voice=Tone.Synth] The constructor of the voices + * uses Tone.Synth by default. + * @example + * //a polysynth composed of 6 Voices of Synth + * var synth = new Tone.PolySynth(6, Tone.Synth).toMaster(); + * //set the attributes using the set interface + * synth.set("detune", -1200); + * //play a chord + * synth.triggerAttackRelease(["C4", "E4", "A4"], "4n"); + */ + Tone.PolySynth = function () { + Tone.Instrument.call(this); + var options = this.optionsObject(arguments, [ + 'polyphony', + 'voice' + ], Tone.PolySynth.defaults); + options = this.defaultArg(options, Tone.Instrument.defaults); + //max polyphony + options.polyphony = Math.min(Tone.PolySynth.MAX_POLYPHONY, options.polyphony); + /** + * the array of voices + * @type {Array} + */ + this.voices = new Array(options.polyphony); + /** + * The queue of voices with data about last trigger + * and the triggered note + * @private + * @type {Array} + */ + this._triggers = new Array(options.polyphony); + /** + * The detune in cents + * @type {Cents} + * @signal + */ + this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); + this._readOnly('detune'); + //create the voices + for (var i = 0; i < options.polyphony; i++) { + var v = new options.voice(arguments[2], arguments[3]); + this.voices[i] = v; + v.connect(this.output); + if (v.hasOwnProperty('detune')) { + this.detune.connect(v.detune); + } + this._triggers[i] = { + release: -1, + note: null, + voice: v + }; + } + //set the volume initially + this.volume.value = options.volume; + }; + Tone.extend(Tone.PolySynth, Tone.Instrument); + /** + * the defaults + * @const + * @static + * @type {Object} + */ + Tone.PolySynth.defaults = { + 'polyphony': 4, + 'volume': 0, + 'detune': 0, + 'voice': Tone.Synth + }; + /** + * Trigger the attack portion of the note + * @param {Frequency|Array} notes The notes to play. Accepts a single + * Frequency or an array of frequencies. + * @param {Time} [time=now] The start time of the note. + * @param {number} [velocity=1] The velocity of the note. + * @returns {Tone.PolySynth} this + * @example + * //trigger a chord immediately with a velocity of 0.2 + * poly.triggerAttack(["Ab3", "C4", "F5"], undefined, 0.2); + */ + Tone.PolySynth.prototype.triggerAttack = function (notes, time, velocity) { + if (!Array.isArray(notes)) { + notes = [notes]; + } + time = this.toSeconds(time); + for (var i = 0; i < notes.length; i++) { + var val = notes[i]; + //trigger the oldest voice + var oldest = this._triggers[0]; + var oldestIndex = 0; + for (var j = 1; j < this._triggers.length; j++) { + if (this._triggers[j].release < oldest.release) { + oldest = this._triggers[j]; + oldestIndex = j; + } + } + oldest.release = Infinity; + oldest.note = JSON.stringify(val); + oldest.voice.triggerAttack(val, time, velocity); + } + return this; + }; + /** + * Trigger the attack and release after the specified duration + * + * @param {Frequency|Array} notes The notes to play. Accepts a single + * Frequency or an array of frequencies. + * @param {Time} duration the duration of the note + * @param {Time} [time=now] if no time is given, defaults to now + * @param {number} [velocity=1] the velocity of the attack (0-1) + * @returns {Tone.PolySynth} this + * @example + * //trigger a chord for a duration of a half note + * poly.triggerAttackRelease(["Eb3", "G4", "C5"], "2n"); + * @example + * //can pass in an array of durations as well + * poly.triggerAttackRelease(["Eb3", "G4", "C5"], ["2n", "4n", "4n"]); + */ + Tone.PolySynth.prototype.triggerAttackRelease = function (notes, duration, time, velocity) { + time = this.toSeconds(time); + this.triggerAttack(notes, time, velocity); + if (this.isArray(duration) && this.isArray(notes)) { + for (var i = 0; i < notes.length; i++) { + var d = duration[Math.min(i, duration.length - 1)]; + this.triggerRelease(notes[i], time + this.toSeconds(d)); + } + } else { + this.triggerRelease(notes, time + this.toSeconds(duration)); + } + return this; + }; + /** + * Trigger the release of the note. Unlike monophonic instruments, + * a note (or array of notes) needs to be passed in as the first argument. + * @param {Frequency|Array} notes The notes to play. Accepts a single + * Frequency or an array of frequencies. + * @param {Time} [time=now] When the release will be triggered. + * @returns {Tone.PolySynth} this + * @example + * poly.triggerRelease(["Ab3", "C4", "F5"], "+2n"); + */ + Tone.PolySynth.prototype.triggerRelease = function (notes, time) { + if (!Array.isArray(notes)) { + notes = [notes]; + } + time = this.toSeconds(time); + for (var i = 0; i < notes.length; i++) { + //get the voice + var stringified = JSON.stringify(notes[i]); + for (var v = 0; v < this._triggers.length; v++) { + var desc = this._triggers[v]; + if (desc.note === stringified && desc.release > time) { + desc.voice.triggerRelease(time); + desc.release = time; + } + } + } + return this; + }; + /** + * Set a member/attribute of the voices. + * @param {Object|string} params + * @param {number=} value + * @param {Time=} rampTime + * @returns {Tone.PolySynth} this + * @example + * poly.set({ + * "filter" : { + * "type" : "highpass" + * }, + * "envelope" : { + * "attack" : 0.25 + * } + * }); + */ + Tone.PolySynth.prototype.set = function (params, value, rampTime) { + for (var i = 0; i < this.voices.length; i++) { + this.voices[i].set(params, value, rampTime); + } + return this; + }; + /** + * Get the synth's attributes. Given no arguments get + * will return all available object properties and their corresponding + * values. Pass in a single attribute to retrieve or an array + * of attributes. The attribute strings can also include a "." + * to access deeper properties. + * @param {Array=} params the parameters to get, otherwise will return + * all available. + */ + Tone.PolySynth.prototype.get = function (params) { + return this.voices[0].get(params); + }; + /** + * Trigger the release portion of all the currently active voices. + * @param {Time} [time=now] When the notes should be released. + * @return {Tone.PolySynth} this + */ + Tone.PolySynth.prototype.releaseAll = function (time) { + time = this.toSeconds(time); + for (var i = 0; i < this._triggers.length; i++) { + var desc = this._triggers[i]; + if (desc.release > time) { + desc.release = time; + desc.voice.triggerRelease(time); + } + } + return this; + }; + /** + * Clean up. + * @returns {Tone.PolySynth} this + */ + Tone.PolySynth.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + for (var i = 0; i < this.voices.length; i++) { + this.voices[i].dispose(); + this.voices[i] = null; + } + this._writable('detune'); + this.detune.dispose(); + this.detune = null; + this.voices = null; + this._triggers = null; + return this; + }; + /** + * The maximum number of notes that can be allocated + * to a polysynth. + * @type {Number} + * @static + */ + Tone.PolySynth.MAX_POLYPHONY = 20; + return Tone.PolySynth; + }); + Module(function (Tone) { + + /** + * @class Tone.Player is an audio file player with start, loop, and stop functions. + * + * @constructor + * @extends {Tone.Source} + * @param {string|AudioBuffer} url Either the AudioBuffer or the url from + * which to load the AudioBuffer + * @param {function=} onload The function to invoke when the buffer is loaded. + * Recommended to use Tone.Buffer.on('load') instead. + * @example + * var player = new Tone.Player("./path/to/sample.mp3").toMaster(); + * //play as soon as the buffer is loaded + * player.autostart = true; + */ + Tone.Player = function (url) { + var options; + if (url instanceof Tone.Buffer) { + url = url.get(); + options = Tone.Player.defaults; + } else { + options = this.optionsObject(arguments, [ + 'url', + 'onload' + ], Tone.Player.defaults); + } + Tone.Source.call(this, options); + /** + * @private + * @type {AudioBufferSourceNode} + */ + this._source = null; + /** + * If the file should play as soon + * as the buffer is loaded. + * @type {boolean} + * @example + * //will play as soon as it's loaded + * var player = new Tone.Player({ + * "url" : "./path/to/sample.mp3", + * "autostart" : true, + * }).toMaster(); + */ + this.autostart = options.autostart; + /** + * the buffer + * @private + * @type {Tone.Buffer} + */ + this._buffer = new Tone.Buffer({ + 'url': options.url, + 'onload': this._onload.bind(this, options.onload), + 'reverse': options.reverse + }); + if (url instanceof AudioBuffer) { + this._buffer.set(url); + } + /** + * if the buffer should loop once it's over + * @type {boolean} + * @private + */ + this._loop = options.loop; + /** + * if 'loop' is true, the loop will start at this position + * @type {Time} + * @private + */ + this._loopStart = options.loopStart; + /** + * if 'loop' is true, the loop will end at this position + * @type {Time} + * @private + */ + this._loopEnd = options.loopEnd; + /** + * the playback rate + * @private + * @type {number} + */ + this._playbackRate = options.playbackRate; + /** + * Enabling retrigger will allow a player to be restarted + * before the the previous 'start' is done playing. Otherwise, + * successive calls to Tone.Player.start will only start + * the sample if it had played all the way through. + * @type {boolean} + */ + this.retrigger = options.retrigger; + }; + Tone.extend(Tone.Player, Tone.Source); + /** + * the default parameters + * @static + * @const + * @type {Object} + */ + Tone.Player.defaults = { + 'onload': Tone.noOp, + 'playbackRate': 1, + 'loop': false, + 'autostart': false, + 'loopStart': 0, + 'loopEnd': 0, + 'retrigger': false, + 'reverse': false + }; + /** + * Load the audio file as an audio buffer. + * Decodes the audio asynchronously and invokes + * the callback once the audio buffer loads. + * Note: this does not need to be called if a url + * was passed in to the constructor. Only use this + * if you want to manually load a new url. + * @param {string} url The url of the buffer to load. + * Filetype support depends on the + * browser. + * @param {function=} callback The function to invoke once + * the sample is loaded. + * @returns {Promise} + */ + Tone.Player.prototype.load = function (url, callback) { + return this._buffer.load(url, this._onload.bind(this, callback)); + }; + /** + * Internal callback when the buffer is loaded. + * @private + */ + Tone.Player.prototype._onload = function (callback) { + callback = this.defaultArg(callback, Tone.noOp); + callback(this); + if (this.autostart) { + this.start(); + } + }; + /** + * Play the buffer at the given startTime. Optionally add an offset + * and/or duration which will play the buffer from a position + * within the buffer for the given duration. + * + * @param {Time} [startTime=now] When the player should start. + * @param {Time} [offset=0] The offset from the beginning of the sample + * to start at. + * @param {Time=} duration How long the sample should play. If no duration + * is given, it will default to the full length + * of the sample (minus any offset) + * @returns {Tone.Player} this + * @memberOf Tone.Player# + * @method start + * @name start + */ + /** + * Internal start method + * @private + */ + Tone.Player.prototype._start = function (startTime, offset, duration) { + if (this._buffer.loaded) { + //if it's a loop the default offset is the loopstart point + if (this._loop) { + offset = this.defaultArg(offset, this._loopStart); + } else { + //otherwise the default offset is 0 + offset = this.defaultArg(offset, 0); + } + offset = this.toSeconds(offset); + //make sure it has a positive duration + duration = this.defaultArg(duration, Math.max(this._buffer.duration - offset, 0)); + duration = this.toSeconds(duration); + //the values in seconds + startTime = this.toSeconds(startTime); + //make the source + this._source = this.context.createBufferSource(); + this._source.buffer = this._buffer.get(); + //set the looping properties + if (this._loop) { + this._source.loop = this._loop; + this._source.loopStart = this.toSeconds(this._loopStart); + this._source.loopEnd = this.toSeconds(this._loopEnd); + } else if (!this._synced) { + //if it's not looping, set the state change at the end of the sample + this._state.setStateAtTime(Tone.State.Stopped, startTime + duration); + } + //and other properties + this._source.playbackRate.value = this._playbackRate; + this._source.connect(this.output); + //start it + if (this._loop) { + //modify the offset if it's greater than the loop time + var loopEnd = this._source.loopEnd || this._buffer.duration; + var loopStart = this._source.loopStart; + var loopDuration = loopEnd - loopStart; + if (offset > loopEnd) { + //move the offset back + while (offset > loopEnd) { + offset -= loopDuration; + } + } + this._source.start(startTime, offset); + } else { + this._source.start(startTime, offset, duration); + } + } else { + throw Error('Tone.Player: tried to start Player before the buffer was loaded'); + } + return this; + }; + /** + * Stop playback. + * @private + * @param {Time} [time=now] + * @returns {Tone.Player} this + */ + Tone.Player.prototype._stop = function (time) { + if (this._source) { + this._source.stop(this.toSeconds(time)); + this._source = null; + } + return this; + }; + /** + * Seek to a specific time in the player's buffer. If the + * source is no longer playing at that time, it will stop. + * If you seek to a time that + * @param {Time} offset The time to seek to. + * @param {Time=} time The time for the seek event to occur. + * @return {Tone.Player} this + * @example + * source.start(0.2); + * source.stop(0.4); + */ + Tone.Player.prototype.seek = function (offset, time) { + time = this.toSeconds(time); + if (this._state.getValueAtTime(time) === Tone.State.Started) { + offset = this.toSeconds(offset); + // if it's currently playing, stop it + this._stop(time); + //restart it at the given time + this._start(time, offset); + } + return this; + }; + /** + * Set the loop start and end. Will only loop if loop is + * set to true. + * @param {Time} loopStart The loop end time + * @param {Time} loopEnd The loop end time + * @returns {Tone.Player} this + * @example + * //loop 0.1 seconds of the file. + * player.setLoopPoints(0.2, 0.3); + * player.loop = true; + */ + Tone.Player.prototype.setLoopPoints = function (loopStart, loopEnd) { + this.loopStart = loopStart; + this.loopEnd = loopEnd; + return this; + }; + /** + * If loop is true, the loop will start at this position. + * @memberOf Tone.Player# + * @type {Time} + * @name loopStart + */ + Object.defineProperty(Tone.Player.prototype, 'loopStart', { + get: function () { + return this._loopStart; + }, + set: function (loopStart) { + this._loopStart = loopStart; + if (this._source) { + this._source.loopStart = this.toSeconds(loopStart); + } + } + }); + /** + * If loop is true, the loop will end at this position. + * @memberOf Tone.Player# + * @type {Time} + * @name loopEnd + */ + Object.defineProperty(Tone.Player.prototype, 'loopEnd', { + get: function () { + return this._loopEnd; + }, + set: function (loopEnd) { + this._loopEnd = loopEnd; + if (this._source) { + this._source.loopEnd = this.toSeconds(loopEnd); + } + } + }); + /** + * The audio buffer belonging to the player. + * @memberOf Tone.Player# + * @type {Tone.Buffer} + * @name buffer + */ + Object.defineProperty(Tone.Player.prototype, 'buffer', { + get: function () { + return this._buffer; + }, + set: function (buffer) { + this._buffer.set(buffer); + } + }); + /** + * If the buffer should loop once it's over. + * @memberOf Tone.Player# + * @type {boolean} + * @name loop + */ + Object.defineProperty(Tone.Player.prototype, 'loop', { + get: function () { + return this._loop; + }, + set: function (loop) { + this._loop = loop; + if (this._source) { + this._source.loop = loop; + } + } + }); + /** + * The playback speed. 1 is normal speed. This is not a signal because + * Safari and iOS currently don't support playbackRate as a signal. + * @memberOf Tone.Player# + * @type {number} + * @name playbackRate + */ + Object.defineProperty(Tone.Player.prototype, 'playbackRate', { + get: function () { + return this._playbackRate; + }, + set: function (rate) { + this._playbackRate = rate; + if (this._source) { + this._source.playbackRate.value = rate; + } + } + }); + /** + * The direction the buffer should play in + * @memberOf Tone.Player# + * @type {boolean} + * @name reverse + */ + Object.defineProperty(Tone.Player.prototype, 'reverse', { + get: function () { + return this._buffer.reverse; + }, + set: function (rev) { + this._buffer.reverse = rev; + } + }); + /** + * Dispose and disconnect. + * @return {Tone.Player} this + */ + Tone.Player.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + if (this._source !== null) { + this._source.disconnect(); + this._source = null; + } + this._buffer.dispose(); + this._buffer = null; + return this; + }; + return Tone.Player; + }); + Module(function (Tone) { + + /** + * @class Sampler wraps Tone.Player in an AmplitudeEnvelope. + * + * @constructor + * @extends {Tone.Instrument} + * @param {String} url the url of the audio file + * @param {Function=} onload The callback to invoke when the sample is loaded. + * @example + * var sampler = new Sampler("./audio/casio/A1.mp3", function(){ + * //repitch the sample down a half step + * sampler.triggerAttack(-1); + * }).toMaster(); + */ + Tone.Sampler = function () { + var options = this.optionsObject(arguments, [ + 'url', + 'onload' + ], Tone.Sampler.defaults); + Tone.Instrument.call(this, options); + /** + * The sample player. + * @type {Tone.Player} + */ + this.player = new Tone.Player(options.url, options.onload); + this.player.retrigger = true; + /** + * The amplitude envelope. + * @type {Tone.AmplitudeEnvelope} + */ + this.envelope = new Tone.AmplitudeEnvelope(options.envelope); + this.player.chain(this.envelope, this.output); + this._readOnly([ + 'player', + 'envelope' + ]); + this.loop = options.loop; + this.reverse = options.reverse; + }; + Tone.extend(Tone.Sampler, Tone.Instrument); + /** + * the default parameters + * @static + */ + Tone.Sampler.defaults = { + 'onload': Tone.noOp, + 'loop': false, + 'reverse': false, + 'envelope': { + 'attack': 0.001, + 'decay': 0, + 'sustain': 1, + 'release': 0.1 + } + }; + /** + * Trigger the start of the sample. + * @param {Interval} [pitch=0] The amount the sample should + * be repitched. + * @param {Time} [time=now] The time when the sample should start + * @param {NormalRange} [velocity=1] The velocity of the note + * @returns {Tone.Sampler} this + * @example + * sampler.triggerAttack(0, "+0.1", 0.5); + */ + Tone.Sampler.prototype.triggerAttack = function (pitch, time, velocity) { + time = this.toSeconds(time); + pitch = this.defaultArg(pitch, 0); + this.player.playbackRate = this.intervalToFrequencyRatio(pitch); + this.player.start(time); + this.envelope.triggerAttack(time, velocity); + return this; + }; + /** + * Start the release portion of the sample. Will stop the sample once the + * envelope has fully released. + * + * @param {Time} [time=now] The time when the note should release + * @returns {Tone.Sampler} this + * @example + * sampler.triggerRelease(); + */ + Tone.Sampler.prototype.triggerRelease = function (time) { + time = this.toSeconds(time); + this.envelope.triggerRelease(time); + this.player.stop(this.toSeconds(this.envelope.release) + time); + return this; + }; + /** + * Trigger the attack and then the release after the duration. + * @param {Interval} interval The interval in half-steps that the + * sample should be pitch shifted. + * @param {Time} duration How long the note should be held for before + * triggering the release. + * @param {Time} [time=now] When the note should be triggered. + * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. + * @returns {Tone.Sampler} this + * @example + * //trigger the unpitched note for the duration of an 8th note + * synth.triggerAttackRelease(0, "8n"); + * @memberOf Tone.Sampler# + * @name triggerAttackRelease + * @method triggerAttackRelease + */ + /** + * If the output sample should loop or not. + * @memberOf Tone.Sampler# + * @type {number|string} + * @name loop + */ + Object.defineProperty(Tone.Sampler.prototype, 'loop', { + get: function () { + return this.player.loop; + }, + set: function (loop) { + this.player.loop = loop; + } + }); + /** + * The direction the buffer should play in + * @memberOf Tone.Sampler# + * @type {boolean} + * @name reverse + */ + Object.defineProperty(Tone.Sampler.prototype, 'reverse', { + get: function () { + return this.player.reverse; + }, + set: function (rev) { + this.player.reverse = rev; + } + }); + /** + * The buffer to play. + * @memberOf Tone.Sampler# + * @type {Tone.Buffer} + * @name buffer + */ + Object.defineProperty(Tone.Sampler.prototype, 'buffer', { + get: function () { + return this.player.buffer; + }, + set: function (buff) { + this.player.buffer = buff; + } + }); + /** + * Clean up. + * @returns {Tone.Sampler} this + */ + Tone.Sampler.prototype.dispose = function () { + Tone.Instrument.prototype.dispose.call(this); + this._writable([ + 'player', + 'envelope' + ]); + this.player.dispose(); + this.player = null; + this.envelope.dispose(); + this.envelope = null; + return this; + }; + return Tone.Sampler; + }); + Module(function (Tone) { + + /** + * @class Maps a NormalRange [0, 1] to an AudioRange [-1, 1]. + * See also Tone.AudioToGain. + * + * @extends {Tone.SignalBase} + * @constructor + * @example + * var g2a = new Tone.GainToAudio(); + */ + Tone.GainToAudio = function () { + /** + * @type {WaveShaperNode} + * @private + */ + this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { + return Math.abs(x) * 2 - 1; + }); + }; + Tone.extend(Tone.GainToAudio, Tone.SignalBase); + /** + * clean up + * @returns {Tone.GainToAudio} this + */ + Tone.GainToAudio.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._norm.dispose(); + this._norm = null; + return this; + }; + return Tone.GainToAudio; + }); + Module(function (Tone) { + + /** + * @class Normalize takes an input min and max and maps it linearly to NormalRange [0,1] + * + * @extends {Tone.SignalBase} + * @constructor + * @param {number} inputMin the min input value + * @param {number} inputMax the max input value + * @example + * var norm = new Tone.Normalize(2, 4); + * var sig = new Tone.Signal(3).connect(norm); + * //output of norm is 0.5. + */ + Tone.Normalize = function (inputMin, inputMax) { + /** + * the min input value + * @type {number} + * @private + */ + this._inputMin = this.defaultArg(inputMin, 0); + /** + * the max input value + * @type {number} + * @private + */ + this._inputMax = this.defaultArg(inputMax, 1); + /** + * subtract the min from the input + * @type {Tone.Add} + * @private + */ + this._sub = this.input = new Tone.Add(0); + /** + * divide by the difference between the input and output + * @type {Tone.Multiply} + * @private + */ + this._div = this.output = new Tone.Multiply(1); + this._sub.connect(this._div); + this._setRange(); + }; + Tone.extend(Tone.Normalize, Tone.SignalBase); + /** + * The minimum value the input signal will reach. + * @memberOf Tone.Normalize# + * @type {number} + * @name min + */ + Object.defineProperty(Tone.Normalize.prototype, 'min', { + get: function () { + return this._inputMin; + }, + set: function (min) { + this._inputMin = min; + this._setRange(); + } + }); + /** + * The maximum value the input signal will reach. + * @memberOf Tone.Normalize# + * @type {number} + * @name max + */ + Object.defineProperty(Tone.Normalize.prototype, 'max', { + get: function () { + return this._inputMax; + }, + set: function (max) { + this._inputMax = max; + this._setRange(); + } + }); + /** + * set the values + * @private + */ + Tone.Normalize.prototype._setRange = function () { + this._sub.value = -this._inputMin; + this._div.value = 1 / (this._inputMax - this._inputMin); + }; + /** + * clean up + * @returns {Tone.Normalize} this + */ + Tone.Normalize.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._sub.dispose(); + this._sub = null; + this._div.dispose(); + this._div = null; + return this; + }; + return Tone.Normalize; + }); + Module(function (Tone) { + /** + * @class Tone.MultiPlayer is well suited for one-shots, multi-sampled instruments + * or any time you need to play a bunch of audio buffers. + * @param {Object|Array|Tone.Buffers} buffers The buffers which are available + * to the MultiPlayer + * @param {Function} onload The callback to invoke when all of the buffers are loaded. + * @extends {Tone} + * @example + * var multiPlayer = new MultiPlayer({ + * "kick" : "path/to/kick.mp3", + * "snare" : "path/to/snare.mp3", + * }, function(){ + * multiPlayer.start("kick"); + * }); + * @example + * //can also store the values in an array + * var multiPlayer = new MultiPlayer(["path/to/kick.mp3", "path/to/snare.mp3"], + * function(){ + * //if an array is passed in, the samples are referenced to by index + * multiPlayer.start(1); + * }); + */ + Tone.MultiPlayer = function () { + var options = this.optionsObject(arguments, [ + 'urls', + 'onload' + ], Tone.MultiPlayer.defaults); + if (options.urls instanceof Tone.Buffers) { + /** + * All the buffers belonging to the player. + * @type {Tone.Buffers} + */ + this.buffers = options.urls; + } else { + this.buffers = new Tone.Buffers(options.urls, options.onload); + } + /** + * Keeps track of the currently playing sources. + * @type {Object} + * @private + */ + this._activeSources = {}; + /** + * The fade in envelope which is applied + * to the beginning of the BufferSource + * @type {Time} + */ + this.fadeIn = options.fadeIn; + /** + * The fade out envelope which is applied + * to the end of the BufferSource + * @type {Time} + */ + this.fadeOut = options.fadeOut; + /** + * The output volume node + * @type {Tone.Volume} + * @private + */ + this._volume = this.output = new Tone.Volume(options.volume); + /** + * The volume of the output in decibels. + * @type {Decibels} + * @signal + * @example + * source.volume.value = -6; + */ + this.volume = this._volume.volume; + this._readOnly('volume'); + //make the output explicitly stereo + this._volume.output.output.channelCount = 2; + this._volume.output.output.channelCountMode = 'explicit'; + //mute initially + this.mute = options.mute; + }; + Tone.extend(Tone.MultiPlayer, Tone.Source); + /** + * The defaults + * @type {Object} + */ + Tone.MultiPlayer.defaults = { + 'onload': Tone.noOp, + 'fadeIn': 0, + 'fadeOut': 0 + }; + /** + * Make the source from the buffername + * @param {String} bufferName + * @return {Tone.BufferSource} + * @private + */ + Tone.MultiPlayer.prototype._makeSource = function (bufferName) { + var buffer; + if (this.isString(bufferName) || this.isNumber(bufferName)) { + buffer = this.buffers.get(bufferName).get(); + } else if (bufferName instanceof Tone.Buffer) { + buffer = bufferName.get(); + } else if (bufferName instanceof AudioBuffer) { + buffer = bufferName; + } + var source = new Tone.BufferSource(buffer).connect(this.output); + if (!this._activeSources.hasOwnProperty(bufferName)) { + this._activeSources[bufferName] = []; + } + this._activeSources[bufferName].push(source); + return source; + }; + /** + * Start a buffer by name. The `start` method allows a number of options + * to be passed in such as offset, interval, and gain. This is good for multi-sampled + * instruments and sound sprites where samples are repitched played back at different velocities. + * @param {String} bufferName The name of the buffer to start. + * @param {Time} time When to start the buffer. + * @param {Time} [offset=0] The offset into the buffer to play from. + * @param {Time=} duration How long to play the buffer for. + * @param {Interval} [pitch=0] The interval to repitch the buffer. + * @param {Gain} [gain=1] The gain to play the sample at. + * @return {Tone.MultiPlayer} this + */ + Tone.MultiPlayer.prototype.start = function (bufferName, time, offset, duration, pitch, gain) { + time = this.toSeconds(time); + var source = this._makeSource(bufferName); + source.start(time, offset, duration, this.defaultArg(gain, 1), this.fadeIn); + if (duration) { + source.stop(time + this.toSeconds(duration), this.fadeOut); + } + pitch = this.defaultArg(pitch, 0); + source.playbackRate.value = this.intervalToFrequencyRatio(pitch); + return this; + }; + /** + * Start a looping buffer by name. Similar to `start`, but the buffer + * is looped instead of played straight through. Can still be stopped with `stop`. + * @param {String} bufferName The name of the buffer to start. + * @param {Time} time When to start the buffer. + * @param {Time} [offset=0] The offset into the buffer to play from. + * @param {Time=} loopStart The start of the loop. + * @param {Time=} loopEnd The end of the loop. + * @param {Interval} [pitch=0] The interval to repitch the buffer. + * @param {Gain} [gain=1] The gain to play the sample at. + * @return {Tone.MultiPlayer} this + */ + Tone.MultiPlayer.prototype.startLoop = function (bufferName, time, offset, loopStart, loopEnd, pitch, gain) { + time = this.toSeconds(time); + var source = this._makeSource(bufferName); + source.loop = true; + source.loopStart = this.toSeconds(this.defaultArg(loopStart, 0)); + source.loopEnd = this.toSeconds(this.defaultArg(loopEnd, 0)); + source.start(time, offset, undefined, this.defaultArg(gain, 1), this.fadeIn); + pitch = this.defaultArg(pitch, 0); + source.playbackRate.value = this.intervalToFrequencyRatio(pitch); + return this; + }; + /** + * Stop the first played instance of the buffer name. + * @param {String} bufferName The buffer to stop. + * @param {Time=} time When to stop the buffer + * @return {Tone.MultiPlayer} this + */ + Tone.MultiPlayer.prototype.stop = function (bufferName, time) { + if (this._activeSources[bufferName] && this._activeSources[bufferName].length) { + time = this.toSeconds(time); + this._activeSources[bufferName].shift().stop(time, this.fadeOut); + } else { + throw new Error('Tone.MultiPlayer: cannot stop a buffer that hasn\'t been started or is already stopped'); + } + return this; + }; + /** + * Stop all currently playing buffers at the given time. + * @param {Time=} time When to stop the buffers. + * @return {Tone.MultiPlayer} this + */ + Tone.MultiPlayer.prototype.stopAll = function (time) { + time = this.toSeconds(time); + for (var bufferName in this._activeSources) { + var sources = this._activeSources[bufferName]; + for (var i = 0; i < sources.length; i++) { + sources[i].stop(time); + } + } + return this; + }; + /** + * Add another buffer to the available buffers. + * @param {String} name The name to that the buffer is refered + * to in start/stop methods. + * @param {String|Tone.Buffer} url The url of the buffer to load + * or the buffer. + * @param {Function} callback The function to invoke after the buffer is loaded. + */ + Tone.MultiPlayer.prototype.add = function (name, url, callback) { + this.buffers.add(name, url, callback); + return this; + }; + /** + * Returns the playback state of the source. "started" + * if there are any buffers playing. "stopped" otherwise. + * @type {Tone.State} + * @readOnly + * @memberOf Tone.MultiPlayer# + * @name state + */ + Object.defineProperty(Tone.MultiPlayer.prototype, 'state', { + get: function () { + return this._activeSources.length > 0 ? Tone.State.Started : Tone.State.Stopped; + } + }); + /** + * Mute the output. + * @memberOf Tone.MultiPlayer# + * @type {boolean} + * @name mute + * @example + * //mute the output + * source.mute = true; + */ + Object.defineProperty(Tone.MultiPlayer.prototype, 'mute', { + get: function () { + return this._volume.mute; + }, + set: function (mute) { + this._volume.mute = mute; + } + }); + /** + * Clean up. + * @return {Tone.MultiPlayer} this + */ + Tone.MultiPlayer.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._volume.dispose(); + this._volume = null; + this._writable('volume'); + this.volume = null; + for (var bufferName in this._activeSources) { + this._activeSources[bufferName].forEach(function (source) { + source.dispose(); + }); + } + this.buffers.dispose(); + this.buffers = null; + this._activeSources = null; + return this; + }; + return Tone.MultiPlayer; + }); + Module(function (Tone) { + /** + * @class Tone.GrainPlayer implements [granular synthesis](https://en.wikipedia.org/wiki/Granular_synthesis). + * Granular Synthesis enables you to adjust pitch and playback rate independently. The grainSize is the + * amount of time each small chunk of audio is played for and the overlap is the + * amount of crossfading transition time between successive grains. + * @extends {Tone} + * @param {String|Tone.Buffer} url The url to load, or the Tone.Buffer to play. + * @param {Function=} callback The callback to invoke after the url is loaded. + */ + Tone.GrainPlayer = function () { + var options = this.optionsObject(arguments, [ + 'url', + 'onload' + ], Tone.GrainPlayer.defaults); + Tone.Source.call(this); + /** + * The audio buffer belonging to the player. + * @type {Tone.Buffer} + */ + this.buffer = new Tone.Buffer(options.url, options.onload); + /** + * Plays the buffer with a small envelope + * @type {Tone.MultiPlayer} + * @private + */ + this._player = new Tone.MultiPlayer().connect(this.output); + /** + * Create a repeating tick to schedule + * the grains. + * @type {Tone.Clock} + * @private + */ + this._clock = new Tone.Clock(this._tick.bind(this), 1); + /** + * @type {Number} + * @private + */ + this._loopStart = 0; + /** + * @type {Number} + * @private + */ + this._loopEnd = 0; + /** + * @type {Number} + * @private + */ + this._playbackRate = options.playbackRate; + /** + * @type {Number} + * @private + */ + this._grainSize = options.grainSize; + /** + * @private + * @type {Number} + */ + this._overlap = options.overlap; + /** + * Adjust the pitch independently of the playbackRate. + * @type {Cents} + */ + this.detune = options.detune; + /** + * The amount of time randomly added + * or subtracted from the grain's offset + * @type {Time} + */ + this.drift = options.drift; + //setup + this.overlap = options.overlap; + this.loop = options.loop; + this.playbackRate = options.playbackRate; + this.grainSize = options.grainSize; + this.loopStart = options.loopStart; + this.loopEnd = options.loopEnd; + this.reverse = options.reverse; + }; + Tone.extend(Tone.GrainPlayer, Tone.Source); + /** + * the default parameters + * @static + * @const + * @type {Object} + */ + Tone.GrainPlayer.defaults = { + 'onload': Tone.noOp, + 'overlap': 0.1, + 'grainSize': 0.2, + 'drift': 0, + 'playbackRate': 1, + 'detune': 0, + 'loop': false, + 'loopStart': 0, + 'loopEnd': 0, + 'reverse': false + }; + /** + * Play the buffer at the given startTime. Optionally add an offset + * and/or duration which will play the buffer from a position + * within the buffer for the given duration. + * + * @param {Time} [startTime=now] When the player should start. + * @param {Time} [offset=0] The offset from the beginning of the sample + * to start at. + * @param {Time=} duration How long the sample should play. If no duration + * is given, it will default to the full length + * of the sample (minus any offset) + * @returns {Tone.GrainPlayer} this + * @memberOf Tone.GrainPlayer# + * @method start + * @name start + */ + /** + * Internal start method + * @param {Time} time + * @param {Time} offset + * @private + */ + Tone.GrainPlayer.prototype._start = function (time, offset, duration) { + offset = this.defaultArg(offset, 0); + offset = this.toSeconds(offset); + time = this.toSeconds(time); + this._offset = offset; + this._clock.start(time); + //unmute the player + this._player.volume.setValueAtTime(0, time); + if (duration) { + this._stop(time + this.toSeconds(duration)); + } + }; + /** + * Internal start method + * @param {Time} time + * @private + */ + Tone.GrainPlayer.prototype._stop = function (time) { + this._clock.stop(time); + //mute the player + this._player.volume.cancelScheduledValues(time); + this._player.volume.setValueAtTime(-Infinity, time); + }; + /** + * Invoked on each clock tick. scheduled a new + * grain at this time. + * @param {Time} time + * @private + */ + Tone.GrainPlayer.prototype._tick = function (time) { + var bufferDuration = this.buffer.duration; + if (this.loop && this._loopEnd > 0) { + bufferDuration = this._loopEnd; + } + var drift = (Math.random() * 2 - 1) * this.drift; + var offset = this._offset - this._overlap + drift; + var detune = this.detune / 100; + //keep the offset within the limits of the buffer + offset = Math.max(offset, 0); + offset = Math.min(offset, bufferDuration); + var originalFadeIn = this._player.fadeIn; + if (this.loop && this._offset > bufferDuration) { + //play the end + var endSegmentDuration = this._offset - bufferDuration; + this._player.start(this.buffer, time, offset, endSegmentDuration + this._overlap, detune); + //and play the beginning + offset = this._offset % bufferDuration; + this._offset = this._loopStart; + this._player.fadeIn = 0; + this._player.start(this.buffer, time + endSegmentDuration, this._offset, offset + this._overlap, detune); + } else if (this._offset > bufferDuration) { + //set the state to stopped. + this.stop(time); + } else { + if (offset === 0) { + this._player.fadeIn = 0; + } + this._player.start(this.buffer, time, offset, this.grainSize + this._overlap, detune); + } + this._player.fadeIn = originalFadeIn; + //increment the offset + var duration = this._clock._nextTick - time; + this._offset += duration * this._playbackRate; + }; + /** + * Jump to a specific time and play it. + * @param {Time} offset The offset to jump to. + * @param {Time=} time When to make the jump. + * @return {[type]} [description] + */ + Tone.GrainPlayer.prototype.scrub = function (offset, time) { + this._offset = this.toSeconds(offset); + this._tick(this.toSeconds(time)); + return this; + }; + /** + * The playback rate of the sample + * @memberOf Tone.GrainPlayer# + * @type {Positive} + * @name playbackRate + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'playbackRate', { + get: function () { + return this._playbackRate; + }, + set: function (rate) { + this._playbackRate = rate; + this.grainSize = this._grainSize; + } + }); + /** + * The loop start time. + * @memberOf Tone.GrainPlayer# + * @type {Time} + * @name loopStart + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'loopStart', { + get: function () { + return this._loopStart; + }, + set: function (time) { + this._loopStart = this.toSeconds(time); + } + }); + /** + * The loop end time. + * @memberOf Tone.GrainPlayer# + * @type {Time} + * @name loopEnd + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'loopEnd', { + get: function () { + return this._loopEnd; + }, + set: function (time) { + this._loopEnd = this.toSeconds(time); + } + }); + /** + * The direction the buffer should play in + * @memberOf Tone.GrainPlayer# + * @type {boolean} + * @name reverse + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'reverse', { + get: function () { + return this.buffer.reverse; + }, + set: function (rev) { + this.buffer.reverse = rev; + } + }); + /** + * The size of each chunk of audio that the + * buffer is chopped into and played back at. + * @memberOf Tone.GrainPlayer# + * @type {Time} + * @name grainSize + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'grainSize', { + get: function () { + return this._grainSize; + }, + set: function (size) { + this._grainSize = this.toSeconds(size); + this._clock.frequency.value = this._playbackRate / this._grainSize; + } + }); + /** + * This is the duration of the cross-fade between + * sucessive grains. + * @memberOf Tone.GrainPlayer# + * @type {Time} + * @name overlap + */ + Object.defineProperty(Tone.GrainPlayer.prototype, 'overlap', { + get: function () { + return this._overlap; + }, + set: function (time) { + time = this.toSeconds(time); + this._overlap = time; + if (this._overlap < 0) { + this._player.fadeIn = 0.01; + this._player.fadeOut = 0.01; + } else { + this._player.fadeIn = time; + this._player.fadeOut = time; + } + } + }); + /** + * Clean up + * @return {Tone.GrainPlayer} this + */ + Tone.GrainPlayer.prototype.dispose = function () { + Tone.Source.prototype.dispose.call(this); + this.buffer.dispose(); + this.buffer = null; + this._player.dispose(); + this._player = null; + this._clock.dispose(); + this._clock = null; + return this; + }; + return Tone.GrainPlayer; + }); + Module(function (Tone) { + + /** + * @class Tone.UserMedia uses MediaDevices.getUserMedia to open up + * and external microphone or audio input. Check + * [MediaDevices API Support](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) + * to see which browsers are supported. Access to an external input + * is limited to secure (HTTPS) connections. + * + * @constructor + * @extends {Tone} + * @param {Decibels=} volume The level of the input + * @example + * //list the inputs and open the third one + * var motu = new Tone.UserMedia(); + * + * //opening the input asks the user to activate their mic + * motu.open().then(function(){ + * //opening is activates the microphone + * //starting lets audio through + * motu.start(10); + * }); + */ + Tone.UserMedia = function () { + var options = this.optionsObject(arguments, ['volume'], Tone.UserMedia.defaults); + /** + * The MediaStreamNode + * @type {MediaStreamAudioSourceNode} + * @private + */ + this._mediaStream = null; + /** + * The media stream created by getUserMedia. + * @type {LocalMediaStream} + * @private + */ + this._stream = null; + /** + * The open device + * @type {MediaDeviceInfo} + * @private + */ + this._device = null; + /** + * The output volume node + * @type {Tone.Volume} + * @private + */ + this._volume = this.output = new Tone.Volume(options.volume); + /** + * The volume of the output in decibels. + * @type {Decibels} + * @signal + * @example + * input.volume.value = -6; + */ + this.volume = this._volume.volume; + this._readOnly('volume'); + this.mute = options.mute; + }; + Tone.extend(Tone.UserMedia); + /** + * the default parameters + * @type {Object} + */ + Tone.UserMedia.defaults = { + 'volume': 0, + 'mute': false + }; + /** + * Open the media stream. If a string is passed in, it is assumed + * to be the label or id of the stream, if a number is passed in, + * it is the input number of the stream. + * @param {String|Number} [labelOrId="default"] The label or id of the audio input media device. + * With no argument, the default stream is opened. + * @return {Promise} The promise is resolved when the stream is open. + */ + Tone.UserMedia.prototype.open = function (labelOrId) { + labelOrId = this.defaultArg(labelOrId, 'default'); + return this.enumerateDevices().then(function (devices) { + var device; + if (this.isNumber(labelOrId)) { + device = devices[labelOrId]; + } else { + device = devices.find(function (device) { + return device.label === labelOrId || device.deviceId === labelOrId; + }); + if (!device) { + //otherwise just take the first one + device = devices[0]; + } + } + //didn't find a matching device + if (!device) { + throw new Error('Tone.UserMedia: no matching audio inputs.'); + } + this._device = device; + //do getUserMedia + var constraints = { + audio: { + 'deviceId': device.deviceId, + 'echoCancellation': false, + 'sampleRate': this.context.sampleRate + } + }; + return navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { + //start a new source only if the previous one is closed + if (!this._stream) { + this._stream = stream; + //Wrap a MediaStreamSourceNode around the live input stream. + this._mediaStream = this.context.createMediaStreamSource(stream); + //Connect the MediaStreamSourceNode to a gate gain node + this._mediaStream.connect(this.output); + } + return this; + }.bind(this)); + }.bind(this)); + }; + /** + * Close the media stream + * @return {Tone.UserMedia} this + */ + Tone.UserMedia.prototype.close = function () { + if (this._stream) { + this._stream.getAudioTracks().forEach(function (track) { + track.stop(); + }); + this._stream = null; + //remove the old media stream + this._mediaStream.disconnect(); + this._mediaStream = null; + } + this._device = null; + return this; + }; + /** + * Returns a promise which resolves with the list of audio input devices available. + * @return {Promise} The promise that is resolved with the devices + * @example + * extInput.enumerateDevices().then(function(devices){ + * console.log(devices) + * }) + */ + Tone.UserMedia.prototype.enumerateDevices = function () { + return navigator.mediaDevices.enumerateDevices().then(function (devices) { + return devices.filter(function (device) { + return device.kind === 'audioinput'; + }); + }); + }; + /** + * Returns the playback state of the source, "started" when the microphone is open + * and "stopped" when the mic is closed. + * @type {Tone.State} + * @readOnly + * @memberOf Tone.UserMedia# + * @name state + */ + Object.defineProperty(Tone.UserMedia.prototype, 'state', { + get: function () { + return this._stream && this._stream.active ? Tone.State.Started : Tone.State.Stopped; + } + }); + /** + * Returns an identifier for the represented device that is + * persisted across sessions. It is un-guessable by other applications and + * unique to the origin of the calling application. It is reset when the + * user clears cookies (for Private Browsing, a different identifier is + * used that is not persisted across sessions). Returns undefined when the + * device is not open. + * @type {String} + * @readOnly + * @memberOf Tone.UserMedia# + * @name deviceId + */ + Object.defineProperty(Tone.UserMedia.prototype, 'deviceId', { + get: function () { + if (this._device) { + return this._device.deviceId; + } + } + }); + /** + * Returns a group identifier. Two devices have the + * same group identifier if they belong to the same physical device. + * Returns undefined when the device is not open. + * @type {String} + * @readOnly + * @memberOf Tone.UserMedia# + * @name groupId + */ + Object.defineProperty(Tone.UserMedia.prototype, 'groupId', { + get: function () { + if (this._device) { + return this._device.groupId; + } + } + }); + /** + * Returns a label describing this device (for example "Built-in Microphone"). + * Returns undefined when the device is not open or label is not available + * because of permissions. + * @type {String} + * @readOnly + * @memberOf Tone.UserMedia# + * @name groupId + */ + Object.defineProperty(Tone.UserMedia.prototype, 'label', { + get: function () { + if (this._device) { + return this._device.label; + } + } + }); + /** + * Mute the output. + * @memberOf Tone.UserMedia# + * @type {boolean} + * @name mute + * @example + * //mute the output + * userMedia.mute = true; + */ + Object.defineProperty(Tone.UserMedia.prototype, 'mute', { + get: function () { + return this._volume.mute; + }, + set: function (mute) { + this._volume.mute = mute; + } + }); + /** + * Clean up. + * @return {Tone.UserMedia} this + */ + Tone.UserMedia.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this.close(); + this._writable('volume'); + this._volume.dispose(); + this._volume = null; + this.volume = null; + return this; + }; + /** + * If getUserMedia is supported by the browser. + * @type {Boolean} + * @memberOf Tone.UserMedia# + * @name supported + * @static + * @readOnly + */ + Object.defineProperty(Tone.UserMedia, 'supported', { + get: function () { + return !Tone.prototype.isUndef(navigator.mediaDevices) && Tone.prototype.isFunction(navigator.mediaDevices.getUserMedia); + } + }); + return Tone.UserMedia; + }); + + return Tone; +})); /***/ }), -/* 90 */ +/* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aCallable = __webpack_require__(42); - -var $TypeError = TypeError; - -var PromiseCapability = function (C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aCallable(resolve); - this.reject = aCallable(reject); -}; +var charAt = __webpack_require__(134).charAt; -// `NewPromiseCapability` abstract operation -// https://tc39.es/ecma262/#sec-newpromisecapability -module.exports.f = function (C) { - return new PromiseCapability(C); +// `AdvanceStringIndex` abstract operation +// https://tc39.es/ecma262/#sec-advancestringindex +module.exports = function (S, index, unicode) { + return index + (unicode ? charAt(S, index).length : 1); }; /***/ }), -/* 91 */ +/* 110 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIntegerOrInfinity = __webpack_require__(54); - -var max = Math.max; -var min = Math.min; - -// Helper for a popular repeating case of the spec: -// Let integer be ? ToInteger(index). -// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). -module.exports = function (index, length) { - var integer = toIntegerOrInfinity(index); - return integer < 0 ? max(integer + length, 0) : min(integer, length); -}; +// eslint-disable-next-line es/no-typed-arrays -- safe +module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined'; /***/ }), -/* 92 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var call = __webpack_require__(36); -var DESCRIPTORS = __webpack_require__(38); -var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(208); -var ArrayBufferViewCore = __webpack_require__(44); -var ArrayBufferModule = __webpack_require__(141); -var anInstance = __webpack_require__(71); -var createPropertyDescriptor = __webpack_require__(73); -var createNonEnumerableProperty = __webpack_require__(59); -var isIntegralNumber = __webpack_require__(188); -var toLength = __webpack_require__(77); -var toIndex = __webpack_require__(169); -var toOffset = __webpack_require__(276); -var toUint8Clamped = __webpack_require__(313); -var toPropertyKey = __webpack_require__(94); -var hasOwn = __webpack_require__(45); -var classof = __webpack_require__(79); -var isObject = __webpack_require__(40); -var isSymbol = __webpack_require__(104); -var create = __webpack_require__(62); -var isPrototypeOf = __webpack_require__(68); -var setPrototypeOf = __webpack_require__(81); -var getOwnPropertyNames = __webpack_require__(106).f; -var typedArrayFrom = __webpack_require__(277); -var forEach = __webpack_require__(58).forEach; -var setSpecies = __webpack_require__(122); -var defineBuiltInAccessor = __webpack_require__(55); -var definePropertyModule = __webpack_require__(51); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var arrayFromConstructorAndList = __webpack_require__(142); -var InternalStateModule = __webpack_require__(53); -var inheritIfRequired = __webpack_require__(101); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var DESCRIPTORS = __webpack_require__(6); +var NATIVE_ARRAY_BUFFER = __webpack_require__(110); +var FunctionName = __webpack_require__(82); +var createNonEnumerableProperty = __webpack_require__(27); +var defineBuiltInAccessor = __webpack_require__(23); +var defineBuiltIns = __webpack_require__(56); +var fails = __webpack_require__(1); +var anInstance = __webpack_require__(39); +var toIntegerOrInfinity = __webpack_require__(22); +var toLength = __webpack_require__(45); +var toIndex = __webpack_require__(139); +var fround = __webpack_require__(220); +var IEEE754 = __webpack_require__(296); +var getPrototypeOf = __webpack_require__(35); +var setPrototypeOf = __webpack_require__(49); +var arrayFill = __webpack_require__(146); +var arraySlice = __webpack_require__(46); +var inheritIfRequired = __webpack_require__(70); +var copyConstructorProperties = __webpack_require__(79); +var setToStringTag = __webpack_require__(38); +var InternalStateModule = __webpack_require__(21); -var getInternalState = InternalStateModule.get; +var PROPER_FUNCTION_NAME = FunctionName.PROPER; +var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE; +var ARRAY_BUFFER = 'ArrayBuffer'; +var DATA_VIEW = 'DataView'; +var PROTOTYPE = 'prototype'; +var WRONG_LENGTH = 'Wrong length'; +var WRONG_INDEX = 'Wrong index'; +var getInternalArrayBufferState = InternalStateModule.getterFor(ARRAY_BUFFER); +var getInternalDataViewState = InternalStateModule.getterFor(DATA_VIEW); var setInternalState = InternalStateModule.set; -var enforceInternalState = InternalStateModule.enforce; -var nativeDefineProperty = definePropertyModule.f; -var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; +var NativeArrayBuffer = globalThis[ARRAY_BUFFER]; +var $ArrayBuffer = NativeArrayBuffer; +var ArrayBufferPrototype = $ArrayBuffer && $ArrayBuffer[PROTOTYPE]; +var $DataView = globalThis[DATA_VIEW]; +var DataViewPrototype = $DataView && $DataView[PROTOTYPE]; +var ObjectPrototype = Object.prototype; +var Array = globalThis.Array; var RangeError = globalThis.RangeError; -var ArrayBuffer = ArrayBufferModule.ArrayBuffer; -var ArrayBufferPrototype = ArrayBuffer.prototype; -var DataView = ArrayBufferModule.DataView; -var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; -var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG; -var TypedArray = ArrayBufferViewCore.TypedArray; -var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype; -var isTypedArray = ArrayBufferViewCore.isTypedArray; -var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; -var WRONG_LENGTH = 'Wrong length'; - -var addGetter = function (it, key) { - defineBuiltInAccessor(it, key, { - configurable: true, - get: function () { - return getInternalState(this)[key]; - } - }); -}; - -var isArrayBuffer = function (it) { - var klass; - return isPrototypeOf(ArrayBufferPrototype, it) || (klass = classof(it)) === 'ArrayBuffer' || klass === 'SharedArrayBuffer'; -}; - -var isTypedArrayIndex = function (target, key) { - return isTypedArray(target) - && !isSymbol(key) - && key in target - && isIntegralNumber(+key) - && key >= 0; -}; - -var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { - key = toPropertyKey(key); - return isTypedArrayIndex(target, key) - ? createPropertyDescriptor(2, target[key]) - : nativeGetOwnPropertyDescriptor(target, key); -}; - -var wrappedDefineProperty = function defineProperty(target, key, descriptor) { - key = toPropertyKey(key); - if (isTypedArrayIndex(target, key) - && isObject(descriptor) - && hasOwn(descriptor, 'value') - && !hasOwn(descriptor, 'get') - && !hasOwn(descriptor, 'set') - // TODO: add validation descriptor w/o calling accessors - && !descriptor.configurable - && (!hasOwn(descriptor, 'writable') || descriptor.writable) - && (!hasOwn(descriptor, 'enumerable') || descriptor.enumerable) - ) { - target[key] = descriptor.value; - return target; - } return nativeDefineProperty(target, key, descriptor); -}; - -if (DESCRIPTORS) { - if (!NATIVE_ARRAY_BUFFER_VIEWS) { - getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor; - definePropertyModule.f = wrappedDefineProperty; - addGetter(TypedArrayPrototype, 'buffer'); - addGetter(TypedArrayPrototype, 'byteOffset'); - addGetter(TypedArrayPrototype, 'byteLength'); - addGetter(TypedArrayPrototype, 'length'); - } - - $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { - getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, - defineProperty: wrappedDefineProperty - }); - - module.exports = function (TYPE, wrapper, CLAMPED) { - var BYTES = TYPE.match(/\d+/)[0] / 8; - var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + TYPE; - var SETTER = 'set' + TYPE; - var NativeTypedArrayConstructor = globalThis[CONSTRUCTOR_NAME]; - var TypedArrayConstructor = NativeTypedArrayConstructor; - var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; - var exported = {}; - - var getter = function (that, index) { - var data = getInternalState(that); - return data.view[GETTER](index * BYTES + data.byteOffset, true); - }; - - var setter = function (that, index, value) { - var data = getInternalState(that); - data.view[SETTER](index * BYTES + data.byteOffset, CLAMPED ? toUint8Clamped(value) : value, true); - }; - - var addElement = function (that, index) { - nativeDefineProperty(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - - if (!NATIVE_ARRAY_BUFFER_VIEWS) { - TypedArrayConstructor = wrapper(function (that, data, offset, $length) { - anInstance(that, TypedArrayConstructorPrototype); - var index = 0; - var byteOffset = 0; - var buffer, byteLength, length; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new ArrayBuffer(byteLength); - } else if (isArrayBuffer(data)) { - buffer = data; - byteOffset = toOffset(offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw new RangeError(WRONG_LENGTH); - byteLength = $len - byteOffset; - if (byteLength < 0) throw new RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + byteOffset > $len) throw new RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (isTypedArray(data)) { - return arrayFromConstructorAndList(TypedArrayConstructor, data); - } else { - return call(typedArrayFrom, TypedArrayConstructor, data); - } - setInternalState(that, { - buffer: buffer, - byteOffset: byteOffset, - byteLength: byteLength, - length: length, - view: new DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - - if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); - TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype); - } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) { - TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { - anInstance(dummy, TypedArrayConstructorPrototype); - return inheritIfRequired(function () { - if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); - if (isArrayBuffer(data)) return $length !== undefined - ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) - : typedArrayOffset !== undefined - ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) - : new NativeTypedArrayConstructor(data); - if (isTypedArray(data)) return arrayFromConstructorAndList(TypedArrayConstructor, data); - return call(typedArrayFrom, TypedArrayConstructor, data); - }(), dummy, TypedArrayConstructor); - }); - - if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); - forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { - if (!(key in TypedArrayConstructor)) { - createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); - } - }); - TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; - } - - if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); - } - - enforceInternalState(TypedArrayConstructorPrototype).TypedArrayConstructor = TypedArrayConstructor; - - if (TYPED_ARRAY_TAG) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); - } - - var FORCED = TypedArrayConstructor !== NativeTypedArrayConstructor; - - exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; - - $({ global: true, constructor: true, forced: FORCED, sham: !NATIVE_ARRAY_BUFFER_VIEWS }, exported); - - if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { - createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); - } - - if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); - } - - setSpecies(CONSTRUCTOR_NAME); - }; -} else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var classof = __webpack_require__(64); - -// `IsArray` abstract operation -// https://tc39.es/ecma262/#sec-isarray -// eslint-disable-next-line es/no-array-isarray -- safe -module.exports = Array.isArray || function isArray(argument) { - return classof(argument) === 'Array'; -}; - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var toPrimitive = __webpack_require__(170); -var isSymbol = __webpack_require__(104); - -// `ToPropertyKey` abstract operation -// https://tc39.es/ecma262/#sec-topropertykey -module.exports = function (argument) { - var key = toPrimitive(argument, 'string'); - return isSymbol(key) ? key : key + ''; -}; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var has = __webpack_require__(82).has; - -// Perform ? RequireInternalSlot(M, [[SetData]]) -module.exports = function (it) { - has(it); - return it; -}; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// `CreateIterResultObject` abstract operation -// https://tc39.es/ecma262/#sec-createiterresultobject -module.exports = function (value, done) { - return { value: value, done: done }; -}; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var $TypeError = TypeError; -var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991 - -module.exports = function (it) { - if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded'); - return it; -}; - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var classofRaw = __webpack_require__(64); -var uncurryThis = __webpack_require__(34); - -module.exports = function (fn) { - // Nashorn bug: - // https://github.com/zloirock/core-js/issues/1128 - // https://github.com/zloirock/core-js/issues/1130 - if (classofRaw(fn) === 'Function') return uncurryThis(fn); -}; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var classof = __webpack_require__(79); -var getMethod = __webpack_require__(60); -var isNullOrUndefined = __webpack_require__(89); -var Iterators = __webpack_require__(133); -var wellKnownSymbol = __webpack_require__(39); - -var ITERATOR = wellKnownSymbol('iterator'); - -module.exports = function (it) { - if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR) - || getMethod(it, '@@iterator') - || Iterators[classof(it)]; -}; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var call = __webpack_require__(36); -var toIntegerOrInfinity = __webpack_require__(54); -var getIteratorDirect = __webpack_require__(65); - -var INVALID_SIZE = 'Invalid size'; -var $RangeError = RangeError; -var $TypeError = TypeError; -var max = Math.max; - -var SetRecord = function (set, intSize) { - this.set = set; - this.size = max(intSize, 0); - this.has = aCallable(set.has); - this.keys = aCallable(set.keys); -}; - -SetRecord.prototype = { - getIterator: function () { - return getIteratorDirect(anObject(call(this.keys, this.set))); - }, - includes: function (it) { - return call(this.has, this.set, it); - } -}; - -// `GetSetRecord` abstract operation -// https://tc39.es/proposal-set-methods/#sec-getsetrecord -module.exports = function (obj) { - anObject(obj); - var numSize = +obj.size; - // NOTE: If size is undefined, then numSize will be NaN - // eslint-disable-next-line no-self-compare -- NaN check - if (numSize !== numSize) throw new $TypeError(INVALID_SIZE); - var intSize = toIntegerOrInfinity(numSize); - if (intSize < 0) throw new $RangeError(INVALID_SIZE); - return new SetRecord(obj, intSize); -}; - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var setPrototypeOf = __webpack_require__(81); - -// makes subclassing work correct for wrapped built-ins -module.exports = function ($this, dummy, Wrapper) { - var NewTarget, NewTargetPrototype; - if ( - // it can work only with native `setPrototypeOf` - setPrototypeOf && - // we haven't completely correct pre-ES6 way for getting `new.target`, so use this - isCallable(NewTarget = dummy.constructor) && - NewTarget !== Wrapper && - isObject(NewTargetPrototype = NewTarget.prototype) && - NewTargetPrototype !== Wrapper.prototype - ) setPrototypeOf($this, NewTargetPrototype); - return $this; -}; - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var hiddenKeys = __webpack_require__(131); -var isObject = __webpack_require__(40); -var hasOwn = __webpack_require__(45); -var defineProperty = __webpack_require__(51).f; -var getOwnPropertyNamesModule = __webpack_require__(106); -var getOwnPropertyNamesExternalModule = __webpack_require__(195); -var isExtensible = __webpack_require__(196); -var uid = __webpack_require__(126); -var FREEZING = __webpack_require__(112); +var fill = uncurryThis(arrayFill); +var reverse = uncurryThis([].reverse); -var REQUIRED = false; -var METADATA = uid('meta'); -var id = 0; +var packIEEE754 = IEEE754.pack; +var unpackIEEE754 = IEEE754.unpack; -var setMetadata = function (it) { - defineProperty(it, METADATA, { value: { - objectID: 'O' + id++, // object ID - weakData: {} // weak collections IDs - } }); +var packInt8 = function (number) { + return [number & 0xFF]; }; -var fastKey = function (it, create) { - // return a primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!hasOwn(it, METADATA)) { - // 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 - setMetadata(it); - // return object ID - } return it[METADATA].objectID; +var packInt16 = function (number) { + return [number & 0xFF, number >> 8 & 0xFF]; }; -var getWeakData = function (it, create) { - if (!hasOwn(it, METADATA)) { - // 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 - setMetadata(it); - // return the store of weak collections IDs - } return it[METADATA].weakData; +var packInt32 = function (number) { + return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; }; -// add metadata on freeze-family methods calling -var onFreeze = function (it) { - if (FREEZING && REQUIRED && isExtensible(it) && !hasOwn(it, METADATA)) setMetadata(it); - return it; +var unpackInt32 = function (buffer) { + return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; }; -var enable = function () { - meta.enable = function () { /* empty */ }; - REQUIRED = true; - var getOwnPropertyNames = getOwnPropertyNamesModule.f; - var splice = uncurryThis([].splice); - var test = {}; - test[METADATA] = 1; - - // prevent exposing of metadata key - if (getOwnPropertyNames(test).length) { - getOwnPropertyNamesModule.f = function (it) { - var result = getOwnPropertyNames(it); - for (var i = 0, length = result.length; i < length; i++) { - if (result[i] === METADATA) { - splice(result, i, 1); - break; - } - } return result; - }; - - $({ target: 'Object', stat: true, forced: true }, { - getOwnPropertyNames: getOwnPropertyNamesExternalModule.f - }); - } +var packFloat32 = function (number) { + return packIEEE754(fround(number), 23, 4); }; -var meta = module.exports = { - enable: enable, - fastKey: fastKey, - getWeakData: getWeakData, - onFreeze: onFreeze +var packFloat64 = function (number) { + return packIEEE754(number, 52, 8); }; -hiddenKeys[METADATA] = true; +var addGetter = function (Constructor, key, getInternalState) { + defineBuiltInAccessor(Constructor[PROTOTYPE], key, { + configurable: true, + get: function () { + return getInternalState(this)[key]; + } + }); +}; +var get = function (view, count, index, isLittleEndian) { + var store = getInternalDataViewState(view); + var intIndex = toIndex(index); + var boolIsLittleEndian = !!isLittleEndian; + if (intIndex + count > store.byteLength) throw new RangeError(WRONG_INDEX); + var bytes = store.bytes; + var start = intIndex + store.byteOffset; + var pack = arraySlice(bytes, start, start + count); + return boolIsLittleEndian ? pack : reverse(pack); +}; -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { +var set = function (view, count, index, conversion, value, isLittleEndian) { + var store = getInternalDataViewState(view); + var intIndex = toIndex(index); + var pack = conversion(+value); + var boolIsLittleEndian = !!isLittleEndian; + if (intIndex + count > store.byteLength) throw new RangeError(WRONG_INDEX); + var bytes = store.bytes; + var start = intIndex + store.byteOffset; + for (var i = 0; i < count; i++) bytes[start + i] = pack[boolIsLittleEndian ? i : count - i - 1]; +}; -"use strict"; +if (!NATIVE_ARRAY_BUFFER) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, ArrayBufferPrototype); + var byteLength = toIndex(length); + setInternalState(this, { + type: ARRAY_BUFFER, + bytes: fill(Array(byteLength), 0), + byteLength: byteLength + }); + if (!DESCRIPTORS) { + this.byteLength = byteLength; + this.detached = false; + } + }; -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var isCallable = __webpack_require__(46); -var classof = __webpack_require__(79); -var getBuiltIn = __webpack_require__(43); -var inspectSource = __webpack_require__(186); + ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE]; -var noop = function () { /* empty */ }; -var construct = getBuiltIn('Reflect', 'construct'); -var constructorRegExp = /^\s*(?:class|function)\b/; -var exec = uncurryThis(constructorRegExp.exec); -var INCORRECT_TO_STRING = !constructorRegExp.test(noop); + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, DataViewPrototype); + anInstance(buffer, ArrayBufferPrototype); + var bufferState = getInternalArrayBufferState(buffer); + var bufferLength = bufferState.byteLength; + var offset = toIntegerOrInfinity(byteOffset); + if (offset < 0 || offset > bufferLength) throw new RangeError('Wrong offset'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw new RangeError(WRONG_LENGTH); + setInternalState(this, { + type: DATA_VIEW, + buffer: buffer, + byteLength: byteLength, + byteOffset: offset, + bytes: bufferState.bytes + }); + if (!DESCRIPTORS) { + this.buffer = buffer; + this.byteLength = byteLength; + this.byteOffset = offset; + } + }; -var isConstructorModern = function isConstructor(argument) { - if (!isCallable(argument)) return false; - try { - construct(noop, [], argument); - return true; - } catch (error) { - return false; - } -}; + DataViewPrototype = $DataView[PROTOTYPE]; -var isConstructorLegacy = function isConstructor(argument) { - if (!isCallable(argument)) return false; - switch (classof(argument)) { - case 'AsyncFunction': - case 'GeneratorFunction': - case 'AsyncGeneratorFunction': return false; - } - try { - // we can't check .prototype since constructors produced by .bind haven't it - // `Function#toString` throws on some built-it function in some legacy engines - // (for example, `DOMQuad` and similar in FF41-) - return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument)); - } catch (error) { - return true; + if (DESCRIPTORS) { + addGetter($ArrayBuffer, 'byteLength', getInternalArrayBufferState); + addGetter($DataView, 'buffer', getInternalDataViewState); + addGetter($DataView, 'byteLength', getInternalDataViewState); + addGetter($DataView, 'byteOffset', getInternalDataViewState); } -}; -isConstructorLegacy.sham = true; + defineBuiltIns(DataViewPrototype, { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false)); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false)) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false), 23); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : false), 52); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : false); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : false); + } + }); +} else { + var INCORRECT_ARRAY_BUFFER_NAME = PROPER_FUNCTION_NAME && NativeArrayBuffer.name !== ARRAY_BUFFER; + /* eslint-disable no-new, sonarjs/inconsistent-function-call -- required for testing */ + if (!fails(function () { + NativeArrayBuffer(1); + }) || !fails(function () { + new NativeArrayBuffer(-1); + }) || fails(function () { + new NativeArrayBuffer(); + new NativeArrayBuffer(1.5); + new NativeArrayBuffer(NaN); + return NativeArrayBuffer.length !== 1 || INCORRECT_ARRAY_BUFFER_NAME && !CONFIGURABLE_FUNCTION_NAME; + })) { + /* eslint-enable no-new, sonarjs/inconsistent-function-call -- required for testing */ + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, ArrayBufferPrototype); + return inheritIfRequired(new NativeArrayBuffer(toIndex(length)), this, $ArrayBuffer); + }; -// `IsConstructor` abstract operation -// https://tc39.es/ecma262/#sec-isconstructor -module.exports = !construct || fails(function () { - var called; - return isConstructorModern(isConstructorModern.call) - || !isConstructorModern(Object) - || !isConstructorModern(function () { called = true; }) - || called; -}) ? isConstructorLegacy : isConstructorModern; + $ArrayBuffer[PROTOTYPE] = ArrayBufferPrototype; + ArrayBufferPrototype.constructor = $ArrayBuffer; -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { + copyConstructorProperties($ArrayBuffer, NativeArrayBuffer); + } else if (INCORRECT_ARRAY_BUFFER_NAME && CONFIGURABLE_FUNCTION_NAME) { + createNonEnumerableProperty(NativeArrayBuffer, 'name', ARRAY_BUFFER); + } -"use strict"; + // WebKit bug - the same parent prototype for typed arrays and data view + if (setPrototypeOf && getPrototypeOf(DataViewPrototype) !== ObjectPrototype) { + setPrototypeOf(DataViewPrototype, ObjectPrototype); + } -var getBuiltIn = __webpack_require__(43); -var isCallable = __webpack_require__(46); -var isPrototypeOf = __webpack_require__(68); -var USE_SYMBOL_AS_UID = __webpack_require__(278); + // iOS Safari 7.x bug + var testView = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = uncurryThis(DataViewPrototype.setInt8); + testView.setInt8(0, 2147483648); + testView.setInt8(1, 2147483649); + if (testView.getInt8(0) || !testView.getInt8(1)) defineBuiltIns(DataViewPrototype, { + setInt8: function setInt8(byteOffset, value) { + $setInt8(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8(this, byteOffset, value << 24 >> 24); + } + }, { unsafe: true }); +} -var $Object = Object; +setToStringTag($ArrayBuffer, ARRAY_BUFFER); +setToStringTag($DataView, DATA_VIEW); -module.exports = USE_SYMBOL_AS_UID ? function (it) { - return typeof it == 'symbol'; -} : function (it) { - var $Symbol = getBuiltIn('Symbol'); - return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); +module.exports = { + ArrayBuffer: $ArrayBuffer, + DataView: $DataView }; /***/ }), -/* 105 */ +/* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); +var lengthOfArrayLike = __webpack_require__(18); -module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) { - var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator; - var next = record.next; - var step, result; - while (!(step = call(next, iterator)).done) { - result = fn(step.value); - if (result !== undefined) return result; - } +module.exports = function (Constructor, list, $length) { + var index = 0; + var length = arguments.length > 2 ? $length : lengthOfArrayLike(list); + var result = new Constructor(length); + while (length > index) result[index] = list[index++]; + return result; }; /***/ }), -/* 106 */ +/* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var internalObjectKeys = __webpack_require__(260); -var enumBugKeys = __webpack_require__(182); +var bind = __webpack_require__(43); +var IndexedObject = __webpack_require__(84); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); -var hiddenKeys = enumBugKeys.concat('length', 'prototype'); +// `Array.prototype.{ findLast, findLastIndex }` methods implementation +var createMethod = function (TYPE) { + var IS_FIND_LAST_INDEX = TYPE === 1; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IndexedObject(O); + var index = lengthOfArrayLike(self); + var boundFunction = bind(callbackfn, that); + var value, result; + while (index-- > 0) { + value = self[index]; + result = boundFunction(value, index, O); + if (result) switch (TYPE) { + case 0: return value; // findLast + case 1: return index; // findLastIndex + } + } + return IS_FIND_LAST_INDEX ? -1 : undefined; + }; +}; -// `Object.getOwnPropertyNames` method -// https://tc39.es/ecma262/#sec-object.getownpropertynames -// eslint-disable-next-line es/no-object-getownpropertynames -- safe -exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return internalObjectKeys(O, hiddenKeys); +module.exports = { + // `Array.prototype.findLast` method + // https://github.com/tc39/proposal-array-find-from-last + findLast: createMethod(0), + // `Array.prototype.findLastIndex` method + // https://github.com/tc39/proposal-array-find-from-last + findLastIndex: createMethod(1) }; /***/ }), -/* 107 */ +/* 114 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var hasOwn = __webpack_require__(45); -var isPrototypeOf = __webpack_require__(68); -var regExpFlagsDetection = __webpack_require__(266); -var regExpFlagsGetterImplementation = __webpack_require__(199); +var aCallable = __webpack_require__(10); +var toObject = __webpack_require__(15); +var IndexedObject = __webpack_require__(84); +var lengthOfArrayLike = __webpack_require__(18); -var RegExpPrototype = RegExp.prototype; +var $TypeError = TypeError; -module.exports = regExpFlagsDetection.correct ? function (it) { - return it.flags; -} : function (it) { - return (!regExpFlagsDetection.correct && isPrototypeOf(RegExpPrototype, it) && !hasOwn(it, 'flags')) - ? call(regExpFlagsGetterImplementation, it) - : it.flags; +var REDUCE_EMPTY = 'Reduce of empty array with no initial value'; + +// `Array.prototype.{ reduce, reduceRight }` methods implementation +var createMethod = function (IS_RIGHT) { + return function (that, callbackfn, argumentsLength, memo) { + var O = toObject(that); + var self = IndexedObject(O); + var length = lengthOfArrayLike(O); + aCallable(callbackfn); + if (length === 0 && argumentsLength < 2) throw new $TypeError(REDUCE_EMPTY); + var index = IS_RIGHT ? length - 1 : 0; + var i = IS_RIGHT ? -1 : 1; + if (argumentsLength < 2) while (true) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (IS_RIGHT ? index < 0 : length <= index) { + throw new $TypeError(REDUCE_EMPTY); + } + } + for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; +}; + +module.exports = { + // `Array.prototype.reduce` method + // https://tc39.es/ecma262/#sec-array.prototype.reduce + left: createMethod(false), + // `Array.prototype.reduceRight` method + // https://tc39.es/ecma262/#sec-array.prototype.reduceright + right: createMethod(true) }; /***/ }), -/* 108 */ +/* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); +var wellKnownSymbol = __webpack_require__(7); -var createSetLike = function (size) { - return { - size: size, - has: function () { - return false; - }, - keys: function () { - return { - next: function () { - return { done: true }; - } - }; - } - }; -}; +var ITERATOR = wellKnownSymbol('iterator'); +var SAFE_CLOSING = false; -var createSetLikeWithInfinitySize = function (size) { - return { - size: size, - has: function () { - return true; +try { + var called = 0; + var iteratorWithReturn = { + next: function () { + return { done: !!called++ }; }, - keys: function () { - throw new Error('e'); + 'return': function () { + SAFE_CLOSING = true; } }; -}; + iteratorWithReturn[ITERATOR] = function () { + return this; + }; + // eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing + Array.from(iteratorWithReturn, function () { throw 2; }); +} catch (error) { /* empty */ } -module.exports = function (name, callback) { - var Set = getBuiltIn('Set'); +module.exports = function (exec, SKIP_CLOSING) { try { - new Set()[name](createSetLike(0)); - try { - // late spec change, early WebKit ~ Safari 17 implementation does not pass it - // https://github.com/tc39/proposal-set-methods/pull/88 - // also covered engines with - // https://bugs.webkit.org/show_bug.cgi?id=272679 - new Set()[name](createSetLike(-1)); - return false; - } catch (error2) { - if (!callback) return true; - // early V8 implementation bug - // https://issues.chromium.org/issues/351332634 - try { - new Set()[name](createSetLikeWithInfinitySize(-Infinity)); - return false; - } catch (error) { - var set = new Set(); - set.add(1); - set.add(2); - return callback(set[name](createSetLikeWithInfinitySize(Infinity))); - } - } - } catch (error) { - return false; - } + if (!SKIP_CLOSING && !SAFE_CLOSING) return false; + } catch (error) { return false; } // workaround of old WebKit + `eval` bug + var ITERATION_SUPPORT = false; + try { + var object = {}; + object[ITERATOR] = function () { + return { + next: function () { + return { done: ITERATION_SUPPORT = true }; + } + }; + }; + exec(object); + } catch (error) { /* empty */ } + return ITERATION_SUPPORT; }; /***/ }), -/* 109 */ +/* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $String = String; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var isForced = __webpack_require__(101); +var defineBuiltIn = __webpack_require__(17); +var InternalMetadataModule = __webpack_require__(71); +var iterate = __webpack_require__(24); +var anInstance = __webpack_require__(39); +var isCallable = __webpack_require__(14); +var isNullOrUndefined = __webpack_require__(57); +var isObject = __webpack_require__(8); +var fails = __webpack_require__(1); +var checkCorrectnessOfIteration = __webpack_require__(115); +var setToStringTag = __webpack_require__(38); +var inheritIfRequired = __webpack_require__(70); -module.exports = function (argument) { - try { - return $String(argument); - } catch (error) { - return 'Object'; - } -}; +module.exports = function (CONSTRUCTOR_NAME, wrapper, common) { + var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; + var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; + var ADDER = IS_MAP ? 'set' : 'add'; + var NativeConstructor = globalThis[CONSTRUCTOR_NAME]; + var NativePrototype = NativeConstructor && NativeConstructor.prototype; + var Constructor = NativeConstructor; + var exported = {}; + var fixMethod = function (KEY) { + var uncurriedNativeMethod = uncurryThis(NativePrototype[KEY]); + defineBuiltIn(NativePrototype, KEY, + KEY === 'add' ? function add(value) { + uncurriedNativeMethod(this, value === 0 ? 0 : value); + return this; + } : KEY === 'delete' ? function (key) { + return IS_WEAK && !isObject(key) ? false : uncurriedNativeMethod(this, key === 0 ? 0 : key); + } : KEY === 'get' ? function get(key) { + return IS_WEAK && !isObject(key) ? undefined : uncurriedNativeMethod(this, key === 0 ? 0 : key); + } : KEY === 'has' ? function has(key) { + return IS_WEAK && !isObject(key) ? false : uncurriedNativeMethod(this, key === 0 ? 0 : key); + } : function set(key, value) { + uncurriedNativeMethod(this, key === 0 ? 0 : key, value); + return this; + } + ); + }; -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { + var REPLACE = isForced( + CONSTRUCTOR_NAME, + !isCallable(NativeConstructor) || !(IS_WEAK || NativePrototype.forEach && !fails(function () { + new NativeConstructor().entries().next(); + })) + ); -"use strict"; + if (REPLACE) { + // create collection constructor + Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); + InternalMetadataModule.enable(); + } else if (isForced(CONSTRUCTOR_NAME, true)) { + var instance = new Constructor(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) !== instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + // eslint-disable-next-line no-new -- required for testing + var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new NativeConstructor(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); -var hasOwn = __webpack_require__(45); -var ownKeys = __webpack_require__(197); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var definePropertyModule = __webpack_require__(51); + if (!ACCEPT_ITERABLES) { + Constructor = wrapper(function (dummy, iterable) { + anInstance(dummy, NativePrototype); + var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); + if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); + return that; + }); + Constructor.prototype = NativePrototype; + NativePrototype.constructor = Constructor; + } -module.exports = function (target, source, exceptions) { - var keys = ownKeys(source); - var defineProperty = definePropertyModule.f; - var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) { - defineProperty(target, key, getOwnPropertyDescriptor(source, key)); + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); } + + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + + // weak collections should not contains .clear method + if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; } + + exported[CONSTRUCTOR_NAME] = Constructor; + $({ global: true, constructor: true, forced: Constructor !== NativeConstructor }, exported); + + setToStringTag(Constructor, CONSTRUCTOR_NAME); + + if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); + + return Constructor; }; /***/ }), -/* 111 */ +/* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ENVIRONMENT = __webpack_require__(149); +var tryToString = __webpack_require__(78); -module.exports = ENVIRONMENT === 'NODE'; +var $TypeError = TypeError; + +module.exports = function (O, P) { + if (!delete O[P]) throw new $TypeError('Cannot delete property ' + tryToString(P) + ' of ' + tryToString(O)); +}; /***/ }), -/* 112 */ +/* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); +var globalThis = __webpack_require__(3); +var isObject = __webpack_require__(8); -module.exports = !fails(function () { - // eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing - return Object.isExtensible(Object.preventExtensions({})); -}); +var document = globalThis.document; +// typeof document.createElement is 'object' in old IE +var EXISTS = isObject(document) && isObject(document.createElement); + +module.exports = function (it) { + return EXISTS ? document.createElement(it) : {}; +}; /***/ }), -/* 113 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var hasOwn = __webpack_require__(45); - -var FunctionPrototype = Function.prototype; -// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; - -var EXISTS = hasOwn(FunctionPrototype, 'name'); -// additional protection from minified / mangled / dropped function names -var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something'; -var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable)); +/* global Bun, Deno -- detection */ +var globalThis = __webpack_require__(3); +var userAgent = __webpack_require__(51); +var classof = __webpack_require__(32); -module.exports = { - EXISTS: EXISTS, - PROPER: PROPER, - CONFIGURABLE: CONFIGURABLE +var userAgentStartsWith = function (string) { + return userAgent.slice(0, string.length) === string; }; +module.exports = (function () { + if (userAgentStartsWith('Bun/')) return 'BUN'; + if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE'; + if (userAgentStartsWith('Deno/')) return 'DENO'; + if (userAgentStartsWith('Node.js/')) return 'NODE'; + if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN'; + if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO'; + if (classof(globalThis.process) === 'process') return 'NODE'; + if (globalThis.window && globalThis.document) return 'BROWSER'; + return 'REST'; +})(); + /***/ }), -/* 114 */ +/* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var tryToString = __webpack_require__(109); -var getIteratorMethod = __webpack_require__(99); +// TODO: Remove from `core-js@4` since it's moved to entry points +__webpack_require__(180); +var call = __webpack_require__(4); +var defineBuiltIn = __webpack_require__(17); +var regexpExec = __webpack_require__(169); +var fails = __webpack_require__(1); +var wellKnownSymbol = __webpack_require__(7); +var createNonEnumerableProperty = __webpack_require__(27); -var $TypeError = TypeError; +var SPECIES = wellKnownSymbol('species'); +var RegExpPrototype = RegExp.prototype; -module.exports = function (argument, usingIterator) { - var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator; - if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument)); - throw new $TypeError(tryToString(argument) + ' is not iterable'); +module.exports = function (KEY, exec, FORCED, SHAM) { + var SYMBOL = wellKnownSymbol(KEY); + + var DELEGATES_TO_SYMBOL = !fails(function () { + // String methods call symbol-named RegExp methods + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) !== 7; + }); + + var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { + // Symbol-named RegExp methods call .exec + var execCalled = false; + var re = /a/; + + if (KEY === 'split') { + // We can't use real regex here since it causes deoptimization + // and serious performance degradation in V8 + // https://github.com/zloirock/core-js/issues/306 + re = {}; + // RegExp[@@split] doesn't call the regex's exec method, but first creates + // a new one. We need to return the patched regex when creating the new one. + re.constructor = {}; + re.constructor[SPECIES] = function () { return re; }; + re.flags = ''; + re[SYMBOL] = /./[SYMBOL]; + } + + re.exec = function () { + execCalled = true; + return null; + }; + + re[SYMBOL](''); + return !execCalled; + }); + + if ( + !DELEGATES_TO_SYMBOL || + !DELEGATES_TO_EXEC || + FORCED + ) { + var nativeRegExpMethod = /./[SYMBOL]; + var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { + var $exec = regexp.exec; + if ($exec === regexpExec || $exec === RegExpPrototype.exec) { + if (DELEGATES_TO_SYMBOL && !forceStringMethod) { + // The native String method already delegates to @@method (this + // polyfilled function), leasing to infinite recursion. + // We avoid it by directly calling the native @@method method. + return { done: true, value: call(nativeRegExpMethod, regexp, str, arg2) }; + } + return { done: true, value: call(nativeMethod, str, regexp, arg2) }; + } + return { done: false }; + }); + + defineBuiltIn(String.prototype, KEY, methods[0]); + defineBuiltIn(RegExpPrototype, SYMBOL, methods[1]); + } + + if (SHAM) createNonEnumerableProperty(RegExpPrototype[SYMBOL], 'sham', true); }; /***/ }), -/* 115 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var classof = __webpack_require__(64); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); -var $Object = Object; -var split = uncurryThis(''.split); - -// fallback for non-array-like ES3 and non-enumerable old V8 strings -module.exports = fails(function () { - // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 - // eslint-disable-next-line no-prototype-builtins -- safe - return !$Object('z').propertyIsEnumerable(0); -}) ? function (it) { - return classof(it) === 'String' ? split(it, '') : $Object(it); -} : $Object; +module.exports = function (object, key, method) { + try { + // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe + return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); + } catch (error) { /* empty */ } +}; /***/ }), -/* 116 */ +/* 122 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var create = __webpack_require__(62); -var createNonEnumerableProperty = __webpack_require__(59); -var defineBuiltIns = __webpack_require__(88); -var wellKnownSymbol = __webpack_require__(39); -var InternalStateModule = __webpack_require__(53); -var getMethod = __webpack_require__(60); -var IteratorPrototype = __webpack_require__(117).IteratorPrototype; -var createIterResultObject = __webpack_require__(96); -var iteratorClose = __webpack_require__(61); -var iteratorCloseAll = __webpack_require__(302); - -var TO_STRING_TAG = wellKnownSymbol('toStringTag'); -var ITERATOR_HELPER = 'IteratorHelper'; -var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator'; -var NORMAL = 'normal'; -var THROW = 'throw'; -var setInternalState = InternalStateModule.set; +var isObject = __webpack_require__(8); +var classof = __webpack_require__(32); +var wellKnownSymbol = __webpack_require__(7); -var createIteratorProxyPrototype = function (IS_ITERATOR) { - var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER); +var MATCH = wellKnownSymbol('match'); - return defineBuiltIns(create(IteratorPrototype), { - next: function next() { - var state = getInternalState(this); - // for simplification: - // for `%WrapForValidIteratorPrototype%.next` or with `state.returnHandlerResult` our `nextHandler` returns `IterResultObject` - // for `%IteratorHelperPrototype%.next` - just a value - if (IS_ITERATOR) return state.nextHandler(); - if (state.done) return createIterResultObject(undefined, true); - try { - var result = state.nextHandler(); - return state.returnHandlerResult ? result : createIterResultObject(result, state.done); - } catch (error) { - state.done = true; - throw error; - } - }, - 'return': function () { - var state = getInternalState(this); - var iterator = state.iterator; - state.done = true; - if (IS_ITERATOR) { - var returnMethod = getMethod(iterator, 'return'); - return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true); - } - if (state.inner) try { - iteratorClose(state.inner.iterator, NORMAL); - } catch (error) { - return iteratorClose(iterator, THROW, error); - } - if (state.openIters) try { - iteratorCloseAll(state.openIters, NORMAL); - } catch (error) { - return iteratorClose(iterator, THROW, error); - } - if (iterator) iteratorClose(iterator, NORMAL); - return createIterResultObject(undefined, true); - } - }); +// `IsRegExp` abstract operation +// https://tc39.es/ecma262/#sec-isregexp +module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) === 'RegExp'); }; -var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true); -var IteratorHelperPrototype = createIteratorProxyPrototype(false); - -createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper'); -module.exports = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) { - var IteratorProxy = function Iterator(record, state) { - if (state) { - state.iterator = record.iterator; - state.next = record.next; - } else state = record; - state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER; - state.returnHandlerResult = !!RETURN_HANDLER_RESULT; - state.nextHandler = nextHandler; - state.counter = 0; - state.done = false; - setInternalState(this, state); - }; +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { - IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype; +"use strict"; - return IteratorProxy; +// Should throw an error on invalid iterator +// https://issues.chromium.org/issues/336839115 +module.exports = function (methodName, argument) { + // eslint-disable-next-line es/no-iterator -- required for testing + var method = typeof Iterator == 'function' && Iterator.prototype[methodName]; + if (method) try { + method.call({ next: null }, argument).next(); + } catch (error) { + return true; + } }; /***/ }), -/* 117 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var create = __webpack_require__(62); -var getPrototypeOf = __webpack_require__(67); -var defineBuiltIn = __webpack_require__(49); -var wellKnownSymbol = __webpack_require__(39); -var IS_PURE = __webpack_require__(48); - -var ITERATOR = wellKnownSymbol('iterator'); -var BUGGY_SAFARI_ITERATORS = false; - -// `%IteratorPrototype%` object -// https://tc39.es/ecma262/#sec-%iteratorprototype%-object -var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; +// eslint-disable-next-line es/no-math-expm1 -- safe +var $expm1 = Math.expm1; +var exp = Math.exp; -/* eslint-disable es/no-array-prototype-keys -- safe */ -if ([].keys) { - arrayIterator = [].keys(); - // Safari 8 has buggy iterators w/o `next` - if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; - else { - PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); - if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; - } -} +// `Math.expm1` method implementation +// https://tc39.es/ecma262/#sec-math.expm1 +module.exports = (!$expm1 + // Old FF bug + // eslint-disable-next-line no-loss-of-precision -- required for old engines + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) !== -2e-17 +) ? function expm1(x) { + var n = +x; + return n === 0 ? n : n > -1e-6 && n < 1e-6 ? n + n * n / 2 : exp(n) - 1; +} : $expm1; -var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () { - var test = {}; - // FF44- legacy iterators case - return IteratorPrototype[ITERATOR].call(test) !== test; -}); -if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {}; -else if (IS_PURE) IteratorPrototype = create(IteratorPrototype); +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { -// `%IteratorPrototype%[@@iterator]()` method -// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator -if (!isCallable(IteratorPrototype[ITERATOR])) { - defineBuiltIn(IteratorPrototype, ITERATOR, function () { - return this; - }); -} +"use strict"; -module.exports = { - IteratorPrototype: IteratorPrototype, - BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS -}; +// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe +exports.f = Object.getOwnPropertySymbols; /***/ }), -/* 118 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toString = __webpack_require__(41); +var $propertyIsEnumerable = {}.propertyIsEnumerable; +// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +// Nashorn ~ JDK8 bug +var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1); -module.exports = function (argument, $default) { - return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument); -}; +// `Object.prototype.propertyIsEnumerable` method implementation +// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable +exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { + var descriptor = getOwnPropertyDescriptor(this, V); + return !!descriptor && descriptor.enumerable; +} : $propertyIsEnumerable; /***/ }), -/* 119 */ +/* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = function (exec) { - try { - return { error: false, value: exec() }; - } catch (error) { - return { error: true, value: error }; - } -}; +/* eslint-disable no-undef, no-useless-call, sonarjs/no-reference-error -- required for testing */ +/* eslint-disable es/no-legacy-object-prototype-accessor-methods -- required for testing */ +var IS_PURE = __webpack_require__(16); +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var WEBKIT = __webpack_require__(154); + +// Forced replacement object prototype accessors methods +module.exports = IS_PURE || !fails(function () { + // This feature detection crashes old WebKit + // https://github.com/zloirock/core-js/issues/232 + if (WEBKIT && WEBKIT < 535) return; + var key = Math.random(); + // In FF throws only define methods + __defineSetter__.call(null, key, function () { /* empty */ }); + delete globalThis[key]; +}); /***/ }), -/* 120 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +var globalThis = __webpack_require__(3); -module.exports = globalThis.Promise; +module.exports = globalThis; /***/ }), -/* 121 */ +/* 129 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var iterateSimple = __webpack_require__(105); -var SetHelpers = __webpack_require__(82); +var NativePromiseConstructor = __webpack_require__(89); +var checkCorrectnessOfIteration = __webpack_require__(115); +var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(104).CONSTRUCTOR; -var Set = SetHelpers.Set; -var SetPrototype = SetHelpers.proto; -var forEach = uncurryThis(SetPrototype.forEach); -var keys = uncurryThis(SetPrototype.keys); -var next = keys(new Set()).next; - -module.exports = function (set, fn, interruptible) { - return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn); -}; +module.exports = FORCED_PROMISE_CONSTRUCTOR || !checkCorrectnessOfIteration(function (iterable) { + NativePromiseConstructor.all(iterable).then(undefined, function () { /* empty */ }); +}); /***/ }), -/* 122 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); -var defineBuiltInAccessor = __webpack_require__(55); -var wellKnownSymbol = __webpack_require__(39); -var DESCRIPTORS = __webpack_require__(38); +var fails = __webpack_require__(1); +var globalThis = __webpack_require__(3); -var SPECIES = wellKnownSymbol('species'); +// babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError +var $RegExp = globalThis.RegExp; -module.exports = function (CONSTRUCTOR_NAME) { - var Constructor = getBuiltIn(CONSTRUCTOR_NAME); +var UNSUPPORTED_Y = fails(function () { + var re = $RegExp('a', 'y'); + re.lastIndex = 2; + return re.exec('abcd') !== null; +}); - if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) { - defineBuiltInAccessor(Constructor, SPECIES, { - configurable: true, - get: function () { return this; } - }); - } +// UC Browser bug +// https://github.com/zloirock/core-js/issues/1008 +var MISSED_STICKY = UNSUPPORTED_Y || fails(function () { + return !$RegExp('a', 'y').sticky; +}); + +var BROKEN_CARET = UNSUPPORTED_Y || fails(function () { + // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 + var re = $RegExp('^r', 'gy'); + re.lastIndex = 2; + return re.exec('str') !== null; +}); + +module.exports = { + BROKEN_CARET: BROKEN_CARET, + MISSED_STICKY: MISSED_STICKY, + UNSUPPORTED_Y: UNSUPPORTED_Y }; /***/ }), -/* 123 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var store = __webpack_require__(162); +var shared = __webpack_require__(92); +var uid = __webpack_require__(95); -module.exports = function (key, value) { - return store[key] || (store[key] = value || {}); +var keys = shared('keys'); + +module.exports = function (key) { + return keys[key] || (keys[key] = uid(key)); }; /***/ }), -/* 124 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toString = __webpack_require__(41); -var whitespaces = __webpack_require__(138); - -var replace = uncurryThis(''.replace); -var ltrim = RegExp('^[' + whitespaces + ']+'); -var rtrim = RegExp('(^|[^' + whitespaces + '])[' + whitespaces + ']+$'); +var IS_PURE = __webpack_require__(16); +var globalThis = __webpack_require__(3); +var defineGlobalProperty = __webpack_require__(152); -// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation -var createMethod = function (TYPE) { - return function ($this) { - var string = toString(requireObjectCoercible($this)); - if (TYPE & 1) string = replace(string, ltrim, ''); - if (TYPE & 2) string = replace(string, rtrim, '$1'); - return string; - }; -}; +var SHARED = '__core-js_shared__'; +var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {}); -module.exports = { - // `String.prototype.{ trimLeft, trimStart }` methods - // https://tc39.es/ecma262/#sec-string.prototype.trimstart - start: createMethod(1), - // `String.prototype.{ trimRight, trimEnd }` methods - // https://tc39.es/ecma262/#sec-string.prototype.trimend - end: createMethod(2), - // `String.prototype.trim` method - // https://tc39.es/ecma262/#sec-string.prototype.trim - trim: createMethod(3) -}; +(store.versions || (store.versions = [])).push({ + version: '3.43.0', + mode: IS_PURE ? 'pure' : 'global', + copyright: '© 2014-2025 Denis Pushkarev (zloirock.ru)', + license: 'https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE', + source: 'https://github.com/zloirock/core-js' +}); /***/ }), -/* 125 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable es/no-symbol -- required for testing */ -var V8_VERSION = __webpack_require__(84); -var fails = __webpack_require__(33); -var globalThis = __webpack_require__(35); +var anObject = __webpack_require__(5); +var aConstructor = __webpack_require__(144); +var isNullOrUndefined = __webpack_require__(57); +var wellKnownSymbol = __webpack_require__(7); -var $String = globalThis.String; +var SPECIES = wellKnownSymbol('species'); -// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing -module.exports = !!Object.getOwnPropertySymbols && !fails(function () { - var symbol = Symbol('symbol detection'); - // Chrome 38 Symbol has incorrect toString conversion - // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances - // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will, - // of course, fail. - return !$String(symbol) || !(Object(symbol) instanceof Symbol) || - // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances - !Symbol.sham && V8_VERSION && V8_VERSION < 41; -}); +// `SpeciesConstructor` abstract operation +// https://tc39.es/ecma262/#sec-speciesconstructor +module.exports = function (O, defaultConstructor) { + var C = anObject(O).constructor; + var S; + return C === undefined || isNullOrUndefined(S = anObject(C)[SPECIES]) ? defaultConstructor : aConstructor(S); +}; /***/ }), -/* 126 */ +/* 134 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); +var uncurryThis = __webpack_require__(2); +var toIntegerOrInfinity = __webpack_require__(22); +var toString = __webpack_require__(9); +var requireObjectCoercible = __webpack_require__(20); -var id = 0; -var postfix = Math.random(); -var toString = uncurryThis(1.1.toString); +var charAt = uncurryThis(''.charAt); +var charCodeAt = uncurryThis(''.charCodeAt); +var stringSlice = uncurryThis(''.slice); -module.exports = function (key) { - return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36); +var createMethod = function (CONVERT_TO_STRING) { + return function ($this, pos) { + var S = toString(requireObjectCoercible($this)); + var position = toIntegerOrInfinity(pos); + var size = S.length; + var first, second; + if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; + first = charCodeAt(S, position); + return first < 0xD800 || first > 0xDBFF || position + 1 === size + || (second = charCodeAt(S, position + 1)) < 0xDC00 || second > 0xDFFF + ? CONVERT_TO_STRING + ? charAt(S, position) + : first + : CONVERT_TO_STRING + ? stringSlice(S, position, position + 2) + : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; + }; +}; + +module.exports = { + // `String.prototype.codePointAt` method + // https://tc39.es/ecma262/#sec-string.prototype.codepointat + codeAt: createMethod(false), + // `String.prototype.at` method + // https://github.com/mathiasbynens/String.prototype.at + charAt: createMethod(true) }; /***/ }), -/* 127 */ +/* 135 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIndexedObject = __webpack_require__(57); -var toAbsoluteIndex = __webpack_require__(91); -var lengthOfArrayLike = __webpack_require__(50); +// https://github.com/tc39/proposal-string-pad-start-end +var uncurryThis = __webpack_require__(2); +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var $repeat = __webpack_require__(136); +var requireObjectCoercible = __webpack_require__(20); -// `Array.prototype.{ indexOf, includes }` methods implementation -var createMethod = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIndexedObject($this); - var length = lengthOfArrayLike(O); - if (length === 0) return !IS_INCLUDES && -1; - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare -- NaN check - if (IS_INCLUDES && el !== el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare -- NaN check - if (value !== value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) { - if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; +var repeat = uncurryThis($repeat); +var stringSlice = uncurryThis(''.slice); +var ceil = Math.ceil; + +// `String.prototype.{ padStart, padEnd }` methods implementation +var createMethod = function (IS_END) { + return function ($this, maxLength, fillString) { + var S = toString(requireObjectCoercible($this)); + var intMaxLength = toLength(maxLength); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : toString(fillString); + var fillLen, stringFiller; + if (intMaxLength <= stringLength || fillStr === '') return S; + fillLen = intMaxLength - stringLength; + stringFiller = repeat(fillStr, ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringSlice(stringFiller, 0, fillLen); + return IS_END ? S + stringFiller : stringFiller + S; }; }; module.exports = { - // `Array.prototype.includes` method - // https://tc39.es/ecma262/#sec-array.prototype.includes - includes: createMethod(true), - // `Array.prototype.indexOf` method - // https://tc39.es/ecma262/#sec-array.prototype.indexof - indexOf: createMethod(false) + // `String.prototype.padStart` method + // https://tc39.es/ecma262/#sec-string.prototype.padstart + start: createMethod(false), + // `String.prototype.padEnd` method + // https://tc39.es/ecma262/#sec-string.prototype.padend + end: createMethod(true) }; /***/ }), -/* 128 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var wellKnownSymbol = __webpack_require__(39); -var V8_VERSION = __webpack_require__(84); +var toIntegerOrInfinity = __webpack_require__(22); +var toString = __webpack_require__(9); +var requireObjectCoercible = __webpack_require__(20); -var SPECIES = wellKnownSymbol('species'); +var $RangeError = RangeError; -module.exports = function (METHOD_NAME) { - // We can't use this feature detection in V8 since it causes - // deoptimization and serious performance degradation - // https://github.com/zloirock/core-js/issues/677 - return V8_VERSION >= 51 || !fails(function () { - var array = []; - var constructor = array.constructor = {}; - constructor[SPECIES] = function () { - return { foo: 1 }; - }; - return array[METHOD_NAME](Boolean).foo !== 1; - }); +// `String.prototype.repeat` method implementation +// https://tc39.es/ecma262/#sec-string.prototype.repeat +module.exports = function repeat(count) { + var str = toString(requireObjectCoercible(this)); + var result = ''; + var n = toIntegerOrInfinity(count); + if (n < 0 || n === Infinity) throw new $RangeError('Wrong number of repetitions'); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str; + return result; }; /***/ }), -/* 129 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arraySpeciesConstructor = __webpack_require__(291); +var globalThis = __webpack_require__(3); +var apply = __webpack_require__(42); +var bind = __webpack_require__(43); +var isCallable = __webpack_require__(14); +var hasOwn = __webpack_require__(13); +var fails = __webpack_require__(1); +var html = __webpack_require__(212); +var arraySlice = __webpack_require__(46); +var createElement = __webpack_require__(118); +var validateArgumentsLength = __webpack_require__(48); +var IS_IOS = __webpack_require__(203); +var IS_NODE = __webpack_require__(80); -// `ArraySpeciesCreate` abstract operation -// https://tc39.es/ecma262/#sec-arrayspeciescreate -module.exports = function (originalArray, length) { - return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length); +var set = globalThis.setImmediate; +var clear = globalThis.clearImmediate; +var process = globalThis.process; +var Dispatch = globalThis.Dispatch; +var Function = globalThis.Function; +var MessageChannel = globalThis.MessageChannel; +var String = globalThis.String; +var counter = 0; +var queue = {}; +var ONREADYSTATECHANGE = 'onreadystatechange'; +var $location, defer, channel, port; + +fails(function () { + // Deno throws a ReferenceError on `location` access without `--location` flag + $location = globalThis.location; +}); + +var run = function (id) { + if (hasOwn(queue, id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } }; +var runner = function (id) { + return function () { + run(id); + }; +}; -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { +var eventListener = function (event) { + run(event.data); +}; -"use strict"; +var globalPostMessageDefer = function (id) { + // old engines have not location.origin + globalThis.postMessage(String(id), $location.protocol + '//' + $location.host); +}; -var fails = __webpack_require__(33); +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if (!set || !clear) { + set = function setImmediate(handler) { + validateArgumentsLength(arguments.length, 1); + var fn = isCallable(handler) ? handler : Function(handler); + var args = arraySlice(arguments, 1); + queue[++counter] = function () { + apply(fn, undefined, args); + }; + defer(counter); + return counter; + }; + clear = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (IS_NODE) { + defer = function (id) { + process.nextTick(runner(id)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(runner(id)); + }; + // Browsers with MessageChannel, includes WebWorkers + // except iOS - https://github.com/zloirock/core-js/issues/624 + } else if (MessageChannel && !IS_IOS) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = eventListener; + defer = bind(port.postMessage, port); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if ( + globalThis.addEventListener && + isCallable(globalThis.postMessage) && + !globalThis.importScripts && + $location && $location.protocol !== 'file:' && + !fails(globalPostMessageDefer) + ) { + defer = globalPostMessageDefer; + globalThis.addEventListener('message', eventListener, false); + // IE8- + } else if (ONREADYSTATECHANGE in createElement('script')) { + defer = function (id) { + html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(runner(id), 0); + }; + } +} -module.exports = !fails(function () { - // eslint-disable-next-line es/no-function-prototype-bind -- safe - var test = (function () { /* empty */ }).bind(); - // eslint-disable-next-line no-prototype-builtins -- safe - return typeof test != 'function' || test.hasOwnProperty('prototype'); -}); +module.exports = { + set: set, + clear: clear +}; /***/ }), -/* 131 */ +/* 138 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = {}; +var uncurryThis = __webpack_require__(2); + +// `thisNumberValue` abstract operation +// https://tc39.es/ecma262/#sec-thisnumbervalue +module.exports = uncurryThis(1.1.valueOf); /***/ }), -/* 132 */ +/* 139 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var isCallable = __webpack_require__(46); - -var replacement = /#|\.prototype\./; +var toIntegerOrInfinity = __webpack_require__(22); +var toLength = __webpack_require__(45); -var isForced = function (feature, detection) { - var value = data[normalize(feature)]; - return value === POLYFILL ? true - : value === NATIVE ? false - : isCallable(detection) ? fails(detection) - : !!detection; -}; +var $RangeError = RangeError; -var normalize = isForced.normalize = function (string) { - return String(string).replace(replacement, '.').toLowerCase(); +// `ToIndex` abstract operation +// https://tc39.es/ecma262/#sec-toindex +module.exports = function (it) { + if (it === undefined) return 0; + var number = toIntegerOrInfinity(it); + var length = toLength(number); + if (number !== length) throw new $RangeError('Wrong length or index'); + return length; }; -var data = isForced.data = {}; -var NATIVE = isForced.NATIVE = 'N'; -var POLYFILL = isForced.POLYFILL = 'P'; - -module.exports = isForced; - /***/ }), -/* 133 */ +/* 140 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = {}; - +var call = __webpack_require__(4); +var isObject = __webpack_require__(8); +var isSymbol = __webpack_require__(73); +var getMethod = __webpack_require__(28); +var ordinaryToPrimitive = __webpack_require__(233); +var wellKnownSymbol = __webpack_require__(7); -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var internalObjectKeys = __webpack_require__(260); -var enumBugKeys = __webpack_require__(182); +var $TypeError = TypeError; +var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); -// `Object.keys` method -// https://tc39.es/ecma262/#sec-object.keys -// eslint-disable-next-line es/no-object-keys -- safe -module.exports = Object.keys || function keys(O) { - return internalObjectKeys(O, enumBugKeys); +// `ToPrimitive` abstract operation +// https://tc39.es/ecma262/#sec-toprimitive +module.exports = function (input, pref) { + if (!isObject(input) || isSymbol(input)) return input; + var exoticToPrim = getMethod(input, TO_PRIMITIVE); + var result; + if (exoticToPrim) { + if (pref === undefined) pref = 'default'; + result = call(exoticToPrim, input, pref); + if (!isObject(result) || isSymbol(result)) return result; + throw new $TypeError("Can't convert object to primitive value"); + } + if (pref === undefined) pref = 'number'; + return ordinaryToPrimitive(input, pref); }; /***/ }), -/* 135 */ +/* 141 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var NativePromiseConstructor = __webpack_require__(120); -var isCallable = __webpack_require__(46); -var isForced = __webpack_require__(132); -var inspectSource = __webpack_require__(186); -var wellKnownSymbol = __webpack_require__(39); -var ENVIRONMENT = __webpack_require__(149); -var IS_PURE = __webpack_require__(48); -var V8_VERSION = __webpack_require__(84); +var fails = __webpack_require__(1); +var wellKnownSymbol = __webpack_require__(7); +var DESCRIPTORS = __webpack_require__(6); +var IS_PURE = __webpack_require__(16); -var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype; -var SPECIES = wellKnownSymbol('species'); -var SUBCLASSING = false; -var NATIVE_PROMISE_REJECTION_EVENT = isCallable(globalThis.PromiseRejectionEvent); +var ITERATOR = wellKnownSymbol('iterator'); -var FORCED_PROMISE_CONSTRUCTOR = isForced('Promise', function () { - var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor); - var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor); - // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // We can't detect it synchronously, so just check versions - if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true; - // We need Promise#{ catch, finally } in the pure version for preventing prototype pollution - if (IS_PURE && !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true; - // We can't use @@species feature detection in V8 since it causes - // deoptimization and performance degradation - // https://github.com/zloirock/core-js/issues/679 - if (!V8_VERSION || V8_VERSION < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) { - // Detect correctness of subclassing with @@species support - var promise = new NativePromiseConstructor(function (resolve) { resolve(1); }); - var FakePromise = function (exec) { - exec(function () { /* empty */ }, function () { /* empty */ }); - }; - var constructor = promise.constructor = {}; - constructor[SPECIES] = FakePromise; - SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise; - if (!SUBCLASSING) return true; - // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test - } return !GLOBAL_CORE_JS_PROMISE && (ENVIRONMENT === 'BROWSER' || ENVIRONMENT === 'DENO') && !NATIVE_PROMISE_REJECTION_EVENT; +module.exports = !fails(function () { + // eslint-disable-next-line unicorn/relative-url-style -- required for testing + var url = new URL('b?a=1&b=2&c=3', 'https://a'); + var params = url.searchParams; + var params2 = new URLSearchParams('a=1&a=2&b=3'); + var result = ''; + url.pathname = 'c%20d'; + params.forEach(function (value, key) { + params['delete']('b'); + result += key + value; + }); + params2['delete']('a', 2); + // `undefined` case is a Chromium 117 bug + // https://bugs.chromium.org/p/v8/issues/detail?id=14222 + params2['delete']('b', undefined); + return (IS_PURE && (!url.toJSON || !params2.has('a', 1) || params2.has('a', 2) || !params2.has('a', undefined) || params2.has('b'))) + || (!params.size && (IS_PURE || !DESCRIPTORS)) + || !params.sort + || url.href !== 'https://a/c%20d?a=1&c=3' + || params.get('c') !== '3' + || String(new URLSearchParams('?a=1')) !== 'a=1' + || !params[ITERATOR] + // throws in Edge + || new URL('https://a@b').username !== 'a' + || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' + // not punycoded in Edge + || new URL('https://тест').host !== 'xn--e1aybc' + // not escaped in Chrome 62- + || new URL('https://a#б').hash !== '#%D0%B1' + // fails in Chrome 66- + || result !== 'a1c3' + // throws in Safari + || new URL('https://x', undefined).host !== 'x'; }); -module.exports = { - CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR, - REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT, - SUBCLASSING: SUBCLASSING -}; - /***/ }), -/* 136 */ +/* 142 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var isCallable = __webpack_require__(46); -var classof = __webpack_require__(64); -var regexpExec = __webpack_require__(198); +var toIndexedObject = __webpack_require__(25); +var addToUnscopables = __webpack_require__(37); +var Iterators = __webpack_require__(102); +var InternalStateModule = __webpack_require__(21); +var defineProperty = __webpack_require__(19).f; +var defineIterator = __webpack_require__(161); +var createIterResultObject = __webpack_require__(65); +var IS_PURE = __webpack_require__(16); +var DESCRIPTORS = __webpack_require__(6); -var $TypeError = TypeError; +var ARRAY_ITERATOR = 'Array Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); -// `RegExpExec` abstract operation -// https://tc39.es/ecma262/#sec-regexpexec -module.exports = function (R, S) { - var exec = R.exec; - if (isCallable(exec)) { - var result = call(exec, R, S); - if (result !== null) anObject(result); - return result; +// `Array.prototype.entries` method +// https://tc39.es/ecma262/#sec-array.prototype.entries +// `Array.prototype.keys` method +// https://tc39.es/ecma262/#sec-array.prototype.keys +// `Array.prototype.values` method +// https://tc39.es/ecma262/#sec-array.prototype.values +// `Array.prototype[@@iterator]` method +// https://tc39.es/ecma262/#sec-array.prototype-@@iterator +// `CreateArrayIterator` internal method +// https://tc39.es/ecma262/#sec-createarrayiterator +module.exports = defineIterator(Array, 'Array', function (iterated, kind) { + setInternalState(this, { + type: ARRAY_ITERATOR, + target: toIndexedObject(iterated), // target + index: 0, // next index + kind: kind // kind + }); +// `%ArrayIteratorPrototype%.next` method +// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next +}, function () { + var state = getInternalState(this); + var target = state.target; + var index = state.index++; + if (!target || index >= target.length) { + state.target = null; + return createIterResultObject(undefined, true); } - if (classof(R) === 'RegExp') return call(regexpExec, R, S); - throw new $TypeError('RegExp#exec called on incompatible receiver'); -}; + switch (state.kind) { + case 'keys': return createIterResultObject(index, false); + case 'values': return createIterResultObject(target[index], false); + } return createIterResultObject([index, target[index]], false); +}, 'values'); + +// argumentsList[@@iterator] is %ArrayProto_values% +// https://tc39.es/ecma262/#sec-createunmappedargumentsobject +// https://tc39.es/ecma262/#sec-createmappedargumentsobject +var values = Iterators.Arguments = Iterators.Array; + +// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); + +// V8 ~ Chrome 45- bug +if (!IS_PURE && DESCRIPTORS && values.name !== 'values') try { + defineProperty(values, 'name', { value: 'values' }); +} catch (error) { /* empty */ } /***/ }), -/* 137 */ +/* 143 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThisAccessor = __webpack_require__(151); -var SetHelpers = __webpack_require__(82); -module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) { - return set.size; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.requestAudioContext = exports.intervalInRange = exports.roundInterval = exports.clamp = exports.lerp = exports.browser = exports.mod = exports.choice = undefined; +var _tone = __webpack_require__(108); -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { +var _tone2 = _interopRequireDefault(_tone); -"use strict"; +var _startAudioContext = __webpack_require__(271); -// a string of all valid unicode whitespaces -module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' + - '\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; +var _startAudioContext2 = _interopRequireDefault(_startAudioContext); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Utilities + * @module lib/util.js; + */ -"use strict"; +var isIphone = navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i); +var isIpad = navigator.userAgent.match(/iPad/i); +var isAndroid = navigator.userAgent.match(/Android/i); +var isMobile = isIphone || isIpad || isAndroid; +var isDesktop = !isMobile; -var charAt = __webpack_require__(164).charAt; +document.body.classList.add(isMobile ? "mobile" : "desktop"); -// `AdvanceStringIndex` abstract operation -// https://tc39.es/ecma262/#sec-advancestringindex -module.exports = function (S, index, unicode) { - return index + (unicode ? charAt(S, index).length : 1); +var browser = { isIphone: isIphone, isIpad: isIpad, isMobile: isMobile, isDesktop: isDesktop }; + +function choice(a) { + return a[Math.floor(Math.random() * a.length)]; +} +function mod(n, m) { + return n - m * Math.floor(n / m); +} +function roundInterval(interval) { + return Math.round(interval * 10000000); +} +var intervalInRange = function intervalInRange(interval, root) { + return 20 < interval * root && interval * root < 15000; +}; +var lerp = function lerp(n, a, b) { + return (b - a) * n + a; +}; +var clamp = function clamp(n) { + var a = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var b = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + return n < a ? a : n < b ? n : b; }; +function requestAudioContext(fn) { + if (window.location.protocol !== "https:") { + var container = document.createElement("div"); + var button = document.createElement("div"); + button.innerHTML = "Tap to start - please unmute your phone"; + Object.assign(container.style, { + display: "block", + position: "absolute", + width: "100%", + height: "100%", + zIndex: "10000", + top: "0px", + left: "0px", + backgroundColor: "rgba(0, 0, 0, 0.8)" + }); + Object.assign(button.style, { + display: "block", + position: "absolute", + left: "50%", + top: "50%", + padding: "20px", + backgroundColor: "#7F33ED", + color: "white", + fontFamily: "monospace", + borderRadius: "3px", + transform: "translate3D(-50%,-50%,0)", + textAlign: "center", + lineHeight: "1.5", + width: "150px" + }); + container.appendChild(button); + document.body.appendChild(container); + _startAudioContext2.default.setContext(_tone2.default.context); + _startAudioContext2.default.on(button); + _startAudioContext2.default.onStarted(function (_) { + container.remove(); + fn(); + }); + } else { + fn(); + } +} + +exports.choice = choice; +exports.mod = mod; +exports.browser = browser; +exports.lerp = lerp; +exports.clamp = clamp; +exports.roundInterval = roundInterval; +exports.intervalInRange = intervalInRange; +exports.requestAudioContext = requestAudioContext; /***/ }), -/* 140 */ +/* 144 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// eslint-disable-next-line es/no-typed-arrays -- safe -module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined'; +var isConstructor = __webpack_require__(72); +var tryToString = __webpack_require__(78); + +var $TypeError = TypeError; + +// `Assert: IsConstructor(argument) is true` +module.exports = function (argument) { + if (isConstructor(argument)) return argument; + throw new $TypeError(tryToString(argument) + ' is not a constructor'); +}; /***/ }), -/* 141 */ +/* 145 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var DESCRIPTORS = __webpack_require__(38); -var NATIVE_ARRAY_BUFFER = __webpack_require__(140); -var FunctionName = __webpack_require__(113); -var createNonEnumerableProperty = __webpack_require__(59); -var defineBuiltInAccessor = __webpack_require__(55); -var defineBuiltIns = __webpack_require__(88); -var fails = __webpack_require__(33); -var anInstance = __webpack_require__(71); -var toIntegerOrInfinity = __webpack_require__(54); -var toLength = __webpack_require__(77); -var toIndex = __webpack_require__(169); -var fround = __webpack_require__(249); -var IEEE754 = __webpack_require__(301); -var getPrototypeOf = __webpack_require__(67); -var setPrototypeOf = __webpack_require__(81); -var arrayFill = __webpack_require__(175); -var arraySlice = __webpack_require__(78); -var inheritIfRequired = __webpack_require__(101); -var copyConstructorProperties = __webpack_require__(110); -var setToStringTag = __webpack_require__(70); -var InternalStateModule = __webpack_require__(53); - -var PROPER_FUNCTION_NAME = FunctionName.PROPER; -var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE; -var ARRAY_BUFFER = 'ArrayBuffer'; -var DATA_VIEW = 'DataView'; -var PROTOTYPE = 'prototype'; -var WRONG_LENGTH = 'Wrong length'; -var WRONG_INDEX = 'Wrong index'; -var getInternalArrayBufferState = InternalStateModule.getterFor(ARRAY_BUFFER); -var getInternalDataViewState = InternalStateModule.getterFor(DATA_VIEW); -var setInternalState = InternalStateModule.set; -var NativeArrayBuffer = globalThis[ARRAY_BUFFER]; -var $ArrayBuffer = NativeArrayBuffer; -var ArrayBufferPrototype = $ArrayBuffer && $ArrayBuffer[PROTOTYPE]; -var $DataView = globalThis[DATA_VIEW]; -var DataViewPrototype = $DataView && $DataView[PROTOTYPE]; -var ObjectPrototype = Object.prototype; -var Array = globalThis.Array; -var RangeError = globalThis.RangeError; -var fill = uncurryThis(arrayFill); -var reverse = uncurryThis([].reverse); - -var packIEEE754 = IEEE754.pack; -var unpackIEEE754 = IEEE754.unpack; - -var packInt8 = function (number) { - return [number & 0xFF]; -}; - -var packInt16 = function (number) { - return [number & 0xFF, number >> 8 & 0xFF]; -}; +// FF26- bug: ArrayBuffers are non-extensible, but Object.isExtensible does not report it +var fails = __webpack_require__(1); -var packInt32 = function (number) { - return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; -}; +module.exports = fails(function () { + if (typeof ArrayBuffer == 'function') { + var buffer = new ArrayBuffer(8); + // eslint-disable-next-line es/no-object-isextensible, es/no-object-defineproperty -- safe + if (Object.isExtensible(buffer)) Object.defineProperty(buffer, 'a', { value: 8 }); + } +}); -var unpackInt32 = function (buffer) { - return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; -}; -var packFloat32 = function (number) { - return packIEEE754(fround(number), 23, 4); -}; +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { -var packFloat64 = function (number) { - return packIEEE754(number, 52, 8); -}; +"use strict"; -var addGetter = function (Constructor, key, getInternalState) { - defineBuiltInAccessor(Constructor[PROTOTYPE], key, { - configurable: true, - get: function () { - return getInternalState(this)[key]; - } - }); -}; +var toObject = __webpack_require__(15); +var toAbsoluteIndex = __webpack_require__(59); +var lengthOfArrayLike = __webpack_require__(18); -var get = function (view, count, index, isLittleEndian) { - var store = getInternalDataViewState(view); - var intIndex = toIndex(index); - var boolIsLittleEndian = !!isLittleEndian; - if (intIndex + count > store.byteLength) throw new RangeError(WRONG_INDEX); - var bytes = store.bytes; - var start = intIndex + store.byteOffset; - var pack = arraySlice(bytes, start, start + count); - return boolIsLittleEndian ? pack : reverse(pack); +// `Array.prototype.fill` method implementation +// https://tc39.es/ecma262/#sec-array.prototype.fill +module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = lengthOfArrayLike(O); + var argumentsLength = arguments.length; + var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); + var end = argumentsLength > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; }; -var set = function (view, count, index, conversion, value, isLittleEndian) { - var store = getInternalDataViewState(view); - var intIndex = toIndex(index); - var pack = conversion(+value); - var boolIsLittleEndian = !!isLittleEndian; - if (intIndex + count > store.byteLength) throw new RangeError(WRONG_INDEX); - var bytes = store.bytes; - var start = intIndex + store.byteOffset; - for (var i = 0; i < count; i++) bytes[start + i] = pack[boolIsLittleEndian ? i : count - i - 1]; -}; -if (!NATIVE_ARRAY_BUFFER) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, ArrayBufferPrototype); - var byteLength = toIndex(length); - setInternalState(this, { - type: ARRAY_BUFFER, - bytes: fill(Array(byteLength), 0), - byteLength: byteLength - }); - if (!DESCRIPTORS) { - this.byteLength = byteLength; - this.detached = false; - } - }; +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { - ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE]; +"use strict"; - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, DataViewPrototype); - anInstance(buffer, ArrayBufferPrototype); - var bufferState = getInternalArrayBufferState(buffer); - var bufferLength = bufferState.byteLength; - var offset = toIntegerOrInfinity(byteOffset); - if (offset < 0 || offset > bufferLength) throw new RangeError('Wrong offset'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw new RangeError(WRONG_LENGTH); - setInternalState(this, { - type: DATA_VIEW, - buffer: buffer, - byteLength: byteLength, - byteOffset: offset, - bytes: bufferState.bytes - }); - if (!DESCRIPTORS) { - this.buffer = buffer; - this.byteLength = byteLength; - this.byteOffset = offset; - } - }; +var DESCRIPTORS = __webpack_require__(6); +var isArray = __webpack_require__(62); - DataViewPrototype = $DataView[PROTOTYPE]; +var $TypeError = TypeError; +// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - if (DESCRIPTORS) { - addGetter($ArrayBuffer, 'byteLength', getInternalArrayBufferState); - addGetter($DataView, 'buffer', getInternalDataViewState); - addGetter($DataView, 'byteLength', getInternalDataViewState); - addGetter($DataView, 'byteOffset', getInternalDataViewState); +// Safari < 13 does not throw an error in this case +var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () { + // makes no sense without proper strict mode support + if (this !== undefined) return true; + try { + // eslint-disable-next-line es/no-object-defineproperty -- safe + Object.defineProperty([], 'length', { writable: false }).length = 1; + } catch (error) { + return error instanceof TypeError; } +}(); - defineBuiltIns(DataViewPrototype, { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false)); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false)) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false), 23); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : false), 52); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packInt8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packInt8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : false); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : false); - } - }); -} else { - var INCORRECT_ARRAY_BUFFER_NAME = PROPER_FUNCTION_NAME && NativeArrayBuffer.name !== ARRAY_BUFFER; - /* eslint-disable no-new, sonarjs/inconsistent-function-call -- required for testing */ - if (!fails(function () { - NativeArrayBuffer(1); - }) || !fails(function () { - new NativeArrayBuffer(-1); - }) || fails(function () { - new NativeArrayBuffer(); - new NativeArrayBuffer(1.5); - new NativeArrayBuffer(NaN); - return NativeArrayBuffer.length !== 1 || INCORRECT_ARRAY_BUFFER_NAME && !CONFIGURABLE_FUNCTION_NAME; - })) { - /* eslint-enable no-new, sonarjs/inconsistent-function-call -- required for testing */ - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, ArrayBufferPrototype); - return inheritIfRequired(new NativeArrayBuffer(toIndex(length)), this, $ArrayBuffer); - }; +module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) { + if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) { + throw new $TypeError('Cannot set read only .length'); + } return O.length = length; +} : function (O, length) { + return O.length = length; +}; - $ArrayBuffer[PROTOTYPE] = ArrayBufferPrototype; - ArrayBufferPrototype.constructor = $ArrayBuffer; +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { - copyConstructorProperties($ArrayBuffer, NativeArrayBuffer); - } else if (INCORRECT_ARRAY_BUFFER_NAME && CONFIGURABLE_FUNCTION_NAME) { - createNonEnumerableProperty(NativeArrayBuffer, 'name', ARRAY_BUFFER); - } +"use strict"; - // WebKit bug - the same parent prototype for typed arrays and data view - if (setPrototypeOf && getPrototypeOf(DataViewPrototype) !== ObjectPrototype) { - setPrototypeOf(DataViewPrototype, ObjectPrototype); - } +var arraySlice = __webpack_require__(46); - // iOS Safari 7.x bug - var testView = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = uncurryThis(DataViewPrototype.setInt8); - testView.setInt8(0, 2147483648); - testView.setInt8(1, 2147483649); - if (testView.getInt8(0) || !testView.getInt8(1)) defineBuiltIns(DataViewPrototype, { - setInt8: function setInt8(byteOffset, value) { - $setInt8(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8(this, byteOffset, value << 24 >> 24); +var floor = Math.floor; + +var sort = function (array, comparefn) { + var length = array.length; + + if (length < 8) { + // insertion sort + var i = 1; + var element, j; + + while (i < length) { + j = i; + element = array[i]; + while (j && comparefn(array[j - 1], element) > 0) { + array[j] = array[--j]; + } + if (j !== i++) array[j] = element; } - }, { unsafe: true }); -} + } else { + // merge sort + var middle = floor(length / 2); + var left = sort(arraySlice(array, 0, middle), comparefn); + var right = sort(arraySlice(array, middle), comparefn); + var llength = left.length; + var rlength = right.length; + var lindex = 0; + var rindex = 0; -setToStringTag($ArrayBuffer, ARRAY_BUFFER); -setToStringTag($DataView, DATA_VIEW); + while (lindex < llength || rindex < rlength) { + array[lindex + rindex] = (lindex < llength && rindex < rlength) + ? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++] + : lindex < llength ? left[lindex++] : right[rindex++]; + } + } -module.exports = { - ArrayBuffer: $ArrayBuffer, - DataView: $DataView + return array; }; +module.exports = sort; + /***/ }), -/* 142 */ +/* 149 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var lengthOfArrayLike = __webpack_require__(50); +var anObject = __webpack_require__(5); +var iteratorClose = __webpack_require__(29); -module.exports = function (Constructor, list, $length) { - var index = 0; - var length = arguments.length > 2 ? $length : lengthOfArrayLike(list); - var result = new Constructor(length); - while (length > index) result[index] = list[index++]; - return result; +// call something on iterator step with safe closing on error +module.exports = function (iterator, fn, value, ENTRIES) { + try { + return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); + } catch (error) { + iteratorClose(iterator, 'throw', error); + } }; /***/ }), -/* 143 */ +/* 150 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var bind = __webpack_require__(75); -var IndexedObject = __webpack_require__(115); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); +var wellKnownSymbol = __webpack_require__(7); -// `Array.prototype.{ findLast, findLastIndex }` methods implementation -var createMethod = function (TYPE) { - var IS_FIND_LAST_INDEX = TYPE === 1; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IndexedObject(O); - var index = lengthOfArrayLike(self); - var boundFunction = bind(callbackfn, that); - var value, result; - while (index-- > 0) { - value = self[index]; - result = boundFunction(value, index, O); - if (result) switch (TYPE) { - case 0: return value; // findLast - case 1: return index; // findLastIndex - } - } - return IS_FIND_LAST_INDEX ? -1 : undefined; - }; -}; +var MATCH = wellKnownSymbol('match'); -module.exports = { - // `Array.prototype.findLast` method - // https://github.com/tc39/proposal-array-find-from-last - findLast: createMethod(0), - // `Array.prototype.findLastIndex` method - // https://github.com/tc39/proposal-array-find-from-last - findLastIndex: createMethod(1) +module.exports = function (METHOD_NAME) { + var regexp = /./; + try { + '/./'[METHOD_NAME](regexp); + } catch (error1) { + try { + regexp[MATCH] = false; + return '/./'[METHOD_NAME](regexp); + } catch (error2) { /* empty */ } + } return false; }; /***/ }), -/* 144 */ +/* 151 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aCallable = __webpack_require__(42); -var toObject = __webpack_require__(47); -var IndexedObject = __webpack_require__(115); -var lengthOfArrayLike = __webpack_require__(50); - -var $TypeError = TypeError; - -var REDUCE_EMPTY = 'Reduce of empty array with no initial value'; - -// `Array.prototype.{ reduce, reduceRight }` methods implementation -var createMethod = function (IS_RIGHT) { - return function (that, callbackfn, argumentsLength, memo) { - var O = toObject(that); - var self = IndexedObject(O); - var length = lengthOfArrayLike(O); - aCallable(callbackfn); - if (length === 0 && argumentsLength < 2) throw new $TypeError(REDUCE_EMPTY); - var index = IS_RIGHT ? length - 1 : 0; - var i = IS_RIGHT ? -1 : 1; - if (argumentsLength < 2) while (true) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (IS_RIGHT ? index < 0 : length <= index) { - throw new $TypeError(REDUCE_EMPTY); - } - } - for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; -}; +var fails = __webpack_require__(1); -module.exports = { - // `Array.prototype.reduce` method - // https://tc39.es/ecma262/#sec-array.prototype.reduce - left: createMethod(false), - // `Array.prototype.reduceRight` method - // https://tc39.es/ecma262/#sec-array.prototype.reduceright - right: createMethod(true) -}; +module.exports = !fails(function () { + function F() { /* empty */ } + F.prototype.constructor = null; + // eslint-disable-next-line es/no-object-getprototypeof -- required for testing + return Object.getPrototypeOf(new F()) !== F.prototype; +}); /***/ }), -/* 145 */ +/* 152 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var wellKnownSymbol = __webpack_require__(39); - -var ITERATOR = wellKnownSymbol('iterator'); -var SAFE_CLOSING = false; +var globalThis = __webpack_require__(3); -try { - var called = 0; - var iteratorWithReturn = { - next: function () { - return { done: !!called++ }; - }, - 'return': function () { - SAFE_CLOSING = true; - } - }; - iteratorWithReturn[ITERATOR] = function () { - return this; - }; - // eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing - Array.from(iteratorWithReturn, function () { throw 2; }); -} catch (error) { /* empty */ } +// eslint-disable-next-line es/no-object-defineproperty -- safe +var defineProperty = Object.defineProperty; -module.exports = function (exec, SKIP_CLOSING) { - try { - if (!SKIP_CLOSING && !SAFE_CLOSING) return false; - } catch (error) { return false; } // workaround of old WebKit + `eval` bug - var ITERATION_SUPPORT = false; +module.exports = function (key, value) { try { - var object = {}; - object[ITERATOR] = function () { - return { - next: function () { - return { done: ITERATION_SUPPORT = true }; - } - }; - }; - exec(object); - } catch (error) { /* empty */ } - return ITERATION_SUPPORT; + defineProperty(globalThis, key, { value: value, configurable: true, writable: true }); + } catch (error) { + globalThis[key] = value; + } return value; }; /***/ }), -/* 146 */ +/* 153 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var isForced = __webpack_require__(132); -var defineBuiltIn = __webpack_require__(49); -var InternalMetadataModule = __webpack_require__(102); -var iterate = __webpack_require__(56); -var anInstance = __webpack_require__(71); -var isCallable = __webpack_require__(46); -var isNullOrUndefined = __webpack_require__(89); -var isObject = __webpack_require__(40); -var fails = __webpack_require__(33); -var checkCorrectnessOfIteration = __webpack_require__(145); -var setToStringTag = __webpack_require__(70); -var inheritIfRequired = __webpack_require__(101); +// IE8- don't enum bug keys +module.exports = [ + 'constructor', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toLocaleString', + 'toString', + 'valueOf' +]; -module.exports = function (CONSTRUCTOR_NAME, wrapper, common) { - var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; - var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; - var ADDER = IS_MAP ? 'set' : 'add'; - var NativeConstructor = globalThis[CONSTRUCTOR_NAME]; - var NativePrototype = NativeConstructor && NativeConstructor.prototype; - var Constructor = NativeConstructor; - var exported = {}; - var fixMethod = function (KEY) { - var uncurriedNativeMethod = uncurryThis(NativePrototype[KEY]); - defineBuiltIn(NativePrototype, KEY, - KEY === 'add' ? function add(value) { - uncurriedNativeMethod(this, value === 0 ? 0 : value); - return this; - } : KEY === 'delete' ? function (key) { - return IS_WEAK && !isObject(key) ? false : uncurriedNativeMethod(this, key === 0 ? 0 : key); - } : KEY === 'get' ? function get(key) { - return IS_WEAK && !isObject(key) ? undefined : uncurriedNativeMethod(this, key === 0 ? 0 : key); - } : KEY === 'has' ? function has(key) { - return IS_WEAK && !isObject(key) ? false : uncurriedNativeMethod(this, key === 0 ? 0 : key); - } : function set(key, value) { - uncurriedNativeMethod(this, key === 0 ? 0 : key, value); - return this; - } - ); - }; +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { - var REPLACE = isForced( - CONSTRUCTOR_NAME, - !isCallable(NativeConstructor) || !(IS_WEAK || NativePrototype.forEach && !fails(function () { - new NativeConstructor().entries().next(); - })) - ); +"use strict"; - if (REPLACE) { - // create collection constructor - Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); - InternalMetadataModule.enable(); - } else if (isForced(CONSTRUCTOR_NAME, true)) { - var instance = new Constructor(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) !== instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - // eslint-disable-next-line no-new -- required for testing - var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new NativeConstructor(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); +var userAgent = __webpack_require__(51); - if (!ACCEPT_ITERABLES) { - Constructor = wrapper(function (dummy, iterable) { - anInstance(dummy, NativePrototype); - var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); - if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); - return that; - }); - Constructor.prototype = NativePrototype; - NativePrototype.constructor = Constructor; - } +var webkit = userAgent.match(/AppleWebKit\/(\d+)\./); + +module.exports = !!webkit && +webkit[1]; + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var uncurryThis = __webpack_require__(2); + +var $Error = Error; +var replace = uncurryThis(''.replace); + +var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd'); +// eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe +var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/; +var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST); - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } +module.exports = function (stack, dropEntries) { + if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) { + while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, ''); + } return stack; +}; - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; - } +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { - exported[CONSTRUCTOR_NAME] = Constructor; - $({ global: true, constructor: true, forced: Constructor !== NativeConstructor }, exported); +"use strict"; - setToStringTag(Constructor, CONSTRUCTOR_NAME); +var createNonEnumerableProperty = __webpack_require__(27); +var clearErrorStack = __webpack_require__(155); +var ERROR_STACK_INSTALLABLE = __webpack_require__(204); - if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); +// non-standard V8 +// eslint-disable-next-line es/no-nonstandard-error-properties -- safe +var captureStackTrace = Error.captureStackTrace; - return Constructor; +module.exports = function (error, C, stack, dropEntries) { + if (ERROR_STACK_INSTALLABLE) { + if (captureStackTrace) captureStackTrace(error, C); + else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries)); + } }; /***/ }), -/* 147 */ +/* 157 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var tryToString = __webpack_require__(109); +var uncurryThis = __webpack_require__(2); +var isCallable = __webpack_require__(14); +var store = __webpack_require__(132); -var $TypeError = TypeError; +var functionToString = uncurryThis(Function.toString); -module.exports = function (O, P) { - if (!delete O[P]) throw new $TypeError('Cannot delete property ' + tryToString(P) + ' of ' + tryToString(O)); -}; +// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper +if (!isCallable(store.inspectSource)) { + store.inspectSource = function (it) { + return functionToString(it); + }; +} + +module.exports = store.inspectSource; /***/ }), -/* 148 */ +/* 158 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var isObject = __webpack_require__(40); +var wellKnownSymbol = __webpack_require__(7); +var Iterators = __webpack_require__(102); -var document = globalThis.document; -// typeof document.createElement is 'object' in old IE -var EXISTS = isObject(document) && isObject(document.createElement); +var ITERATOR = wellKnownSymbol('iterator'); +var ArrayPrototype = Array.prototype; +// check on default Array iterator module.exports = function (it) { - return EXISTS ? document.createElement(it) : {}; + return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); }; /***/ }), -/* 149 */ +/* 159 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* global Bun, Deno -- detection */ -var globalThis = __webpack_require__(35); -var userAgent = __webpack_require__(83); -var classof = __webpack_require__(64); +var isObject = __webpack_require__(8); -var userAgentStartsWith = function (string) { - return userAgent.slice(0, string.length) === string; +var floor = Math.floor; + +// `IsIntegralNumber` abstract operation +// https://tc39.es/ecma262/#sec-isintegralnumber +// eslint-disable-next-line es/no-number-isinteger -- safe +module.exports = Number.isInteger || function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; }; -module.exports = (function () { - if (userAgentStartsWith('Bun/')) return 'BUN'; - if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE'; - if (userAgentStartsWith('Deno/')) return 'DENO'; - if (userAgentStartsWith('Node.js/')) return 'NODE'; - if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN'; - if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO'; - if (classof(globalThis.process) === 'process') return 'NODE'; - if (globalThis.window && globalThis.document) return 'BROWSER'; - return 'REST'; -})(); + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var IteratorPrototype = __webpack_require__(86).IteratorPrototype; +var create = __webpack_require__(30); +var createPropertyDescriptor = __webpack_require__(41); +var setToStringTag = __webpack_require__(38); +var Iterators = __webpack_require__(102); + +var returnThis = function () { return this; }; + +module.exports = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) { + var TO_STRING_TAG = NAME + ' Iterator'; + IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) }); + setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); + Iterators[TO_STRING_TAG] = returnThis; + return IteratorConstructor; +}; /***/ }), -/* 150 */ +/* 161 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// TODO: Remove from `core-js@4` since it's moved to entry points -__webpack_require__(209); -var call = __webpack_require__(36); -var defineBuiltIn = __webpack_require__(49); -var regexpExec = __webpack_require__(198); -var fails = __webpack_require__(33); -var wellKnownSymbol = __webpack_require__(39); -var createNonEnumerableProperty = __webpack_require__(59); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var IS_PURE = __webpack_require__(16); +var FunctionName = __webpack_require__(82); +var isCallable = __webpack_require__(14); +var createIteratorConstructor = __webpack_require__(160); +var getPrototypeOf = __webpack_require__(35); +var setPrototypeOf = __webpack_require__(49); +var setToStringTag = __webpack_require__(38); +var createNonEnumerableProperty = __webpack_require__(27); +var defineBuiltIn = __webpack_require__(17); +var wellKnownSymbol = __webpack_require__(7); +var Iterators = __webpack_require__(102); +var IteratorsCore = __webpack_require__(86); -var SPECIES = wellKnownSymbol('species'); -var RegExpPrototype = RegExp.prototype; +var PROPER_FUNCTION_NAME = FunctionName.PROPER; +var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE; +var IteratorPrototype = IteratorsCore.IteratorPrototype; +var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; +var ITERATOR = wellKnownSymbol('iterator'); +var KEYS = 'keys'; +var VALUES = 'values'; +var ENTRIES = 'entries'; -module.exports = function (KEY, exec, FORCED, SHAM) { - var SYMBOL = wellKnownSymbol(KEY); +var returnThis = function () { return this; }; - var DELEGATES_TO_SYMBOL = !fails(function () { - // String methods call symbol-named RegExp methods - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) !== 7; - }); +module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { + createIteratorConstructor(IteratorConstructor, NAME, next); - var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { - // Symbol-named RegExp methods call .exec - var execCalled = false; - var re = /a/; + var getIterationMethod = function (KIND) { + if (KIND === DEFAULT && defaultIterator) return defaultIterator; + if (!BUGGY_SAFARI_ITERATORS && KIND && KIND in IterablePrototype) return IterablePrototype[KIND]; - if (KEY === 'split') { - // We can't use real regex here since it causes deoptimization - // and serious performance degradation in V8 - // https://github.com/zloirock/core-js/issues/306 - re = {}; - // RegExp[@@split] doesn't call the regex's exec method, but first creates - // a new one. We need to return the patched regex when creating the new one. - re.constructor = {}; - re.constructor[SPECIES] = function () { return re; }; - re.flags = ''; - re[SYMBOL] = /./[SYMBOL]; + switch (KIND) { + case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; + case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; + case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; } - re.exec = function () { - execCalled = true; - return null; - }; + return function () { return new IteratorConstructor(this); }; + }; - re[SYMBOL](''); - return !execCalled; - }); + var TO_STRING_TAG = NAME + ' Iterator'; + var INCORRECT_VALUES_NAME = false; + var IterablePrototype = Iterable.prototype; + var nativeIterator = IterablePrototype[ITERATOR] + || IterablePrototype['@@iterator'] + || DEFAULT && IterablePrototype[DEFAULT]; + var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); + var anyNativeIterator = NAME === 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; + var CurrentIteratorPrototype, methods, KEY; - if ( - !DELEGATES_TO_SYMBOL || - !DELEGATES_TO_EXEC || - FORCED - ) { - var nativeRegExpMethod = /./[SYMBOL]; - var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { - var $exec = regexp.exec; - if ($exec === regexpExec || $exec === RegExpPrototype.exec) { - if (DELEGATES_TO_SYMBOL && !forceStringMethod) { - // The native String method already delegates to @@method (this - // polyfilled function), leasing to infinite recursion. - // We avoid it by directly calling the native @@method method. - return { done: true, value: call(nativeRegExpMethod, regexp, str, arg2) }; + // fix native + if (anyNativeIterator) { + CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); + if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { + if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { + if (setPrototypeOf) { + setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); + } else if (!isCallable(CurrentIteratorPrototype[ITERATOR])) { + defineBuiltIn(CurrentIteratorPrototype, ITERATOR, returnThis); } - return { done: true, value: call(nativeMethod, str, regexp, arg2) }; } - return { done: false }; - }); + // Set @@toStringTag to native iterators + setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); + if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; + } + } - defineBuiltIn(String.prototype, KEY, methods[0]); - defineBuiltIn(RegExpPrototype, SYMBOL, methods[1]); + // fix Array.prototype.{ values, @@iterator }.name in V8 / FF + if (PROPER_FUNCTION_NAME && DEFAULT === VALUES && nativeIterator && nativeIterator.name !== VALUES) { + if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) { + createNonEnumerableProperty(IterablePrototype, 'name', VALUES); + } else { + INCORRECT_VALUES_NAME = true; + defaultIterator = function values() { return call(nativeIterator, this); }; + } } - if (SHAM) createNonEnumerableProperty(RegExpPrototype[SYMBOL], 'sham', true); + // export additional methods + if (DEFAULT) { + methods = { + values: getIterationMethod(VALUES), + keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), + entries: getIterationMethod(ENTRIES) + }; + if (FORCED) for (KEY in methods) { + if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { + defineBuiltIn(IterablePrototype, KEY, methods[KEY]); + } + } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); + } + + // define iterator + if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { + defineBuiltIn(IterablePrototype, ITERATOR, defaultIterator, { name: DEFAULT }); + } + Iterators[NAME] = defaultIterator; + + return methods; }; /***/ }), -/* 151 */ +/* 162 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var isCallable = __webpack_require__(14); +var hasOwn = __webpack_require__(13); +var DESCRIPTORS = __webpack_require__(6); +var CONFIGURABLE_FUNCTION_NAME = __webpack_require__(82).CONFIGURABLE; +var inspectSource = __webpack_require__(157); +var InternalStateModule = __webpack_require__(21); -module.exports = function (object, key, method) { +var enforceInternalState = InternalStateModule.enforce; +var getInternalState = InternalStateModule.get; +var $String = String; +// eslint-disable-next-line es/no-object-defineproperty -- safe +var defineProperty = Object.defineProperty; +var stringSlice = uncurryThis(''.slice); +var replace = uncurryThis(''.replace); +var join = uncurryThis([].join); + +var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () { + return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8; +}); + +var TEMPLATE = String(String).split('String'); + +var makeBuiltIn = module.exports = function (value, name, options) { + if (stringSlice($String(name), 0, 7) === 'Symbol(') { + name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']'; + } + if (options && options.getter) name = 'get ' + name; + if (options && options.setter) name = 'set ' + name; + if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) { + if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true }); + else value.name = name; + } + if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) { + defineProperty(value, 'length', { value: options.arity }); + } try { - // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe - return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); + if (options && hasOwn(options, 'constructor') && options.constructor) { + if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false }); + // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable + } else if (value.prototype) value.prototype = undefined; } catch (error) { /* empty */ } + var state = enforceInternalState(value); + if (!hasOwn(state, 'source')) { + state.source = join(TEMPLATE, typeof name == 'string' ? name : ''); + } return value; }; +// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative +// eslint-disable-next-line no-extend-native -- required +Function.prototype.toString = makeBuiltIn(function toString() { + return isCallable(this) && getInternalState(this).source || inspectSource(this); +}, 'toString'); + /***/ }), -/* 152 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(40); -var classof = __webpack_require__(64); -var wellKnownSymbol = __webpack_require__(39); - -var MATCH = wellKnownSymbol('match'); - -// `IsRegExp` abstract operation -// https://tc39.es/ecma262/#sec-isregexp -module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) === 'RegExp'); +// `Math.sign` method implementation +// https://tc39.es/ecma262/#sec-math.sign +// eslint-disable-next-line es/no-math-sign -- safe +module.exports = Math.sign || function sign(x) { + var n = +x; + // eslint-disable-next-line no-self-compare -- NaN check + return n === 0 || n !== n ? n : n < 0 ? -1 : 1; }; /***/ }), -/* 153 */ +/* 164 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// Should throw an error on invalid iterator -// https://issues.chromium.org/issues/336839115 -module.exports = function (methodName, argument) { - // eslint-disable-next-line es/no-iterator -- required for testing - var method = typeof Iterator == 'function' && Iterator.prototype[methodName]; - if (method) try { - method.call({ next: null }, argument).next(); - } catch (error) { - return true; - } +var isRegExp = __webpack_require__(122); + +var $TypeError = TypeError; + +module.exports = function (it) { + if (isRegExp(it)) { + throw new $TypeError("The method doesn't accept regular expressions"); + } return it; }; /***/ }), -/* 154 */ +/* 165 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// eslint-disable-next-line es/no-math-expm1 -- safe -var $expm1 = Math.expm1; -var exp = Math.exp; +var DESCRIPTORS = __webpack_require__(6); +var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(250); +var definePropertyModule = __webpack_require__(19); +var anObject = __webpack_require__(5); +var toIndexedObject = __webpack_require__(25); +var objectKeys = __webpack_require__(103); -// `Math.expm1` method implementation -// https://tc39.es/ecma262/#sec-math.expm1 -module.exports = (!$expm1 - // Old FF bug - // eslint-disable-next-line no-loss-of-precision -- required for old engines - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) !== -2e-17 -) ? function expm1(x) { - var n = +x; - return n === 0 ? n : n > -1e-6 && n < 1e-6 ? n + n * n / 2 : exp(n) - 1; -} : $expm1; +// `Object.defineProperties` method +// https://tc39.es/ecma262/#sec-object.defineproperties +// eslint-disable-next-line es/no-object-defineproperties -- safe +exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var props = toIndexedObject(Properties); + var keys = objectKeys(Properties); + var length = keys.length; + var index = 0; + var key; + while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]); + return O; +}; /***/ }), -/* 155 */ +/* 166 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe -exports.f = Object.getOwnPropertySymbols; +/* eslint-disable es/no-object-getownpropertynames -- safe */ +var classof = __webpack_require__(32); +var toIndexedObject = __webpack_require__(25); +var $getOwnPropertyNames = __webpack_require__(75).f; +var arraySlice = __webpack_require__(46); + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return $getOwnPropertyNames(it); + } catch (error) { + return arraySlice(windowNames); + } +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +module.exports.f = function getOwnPropertyNames(it) { + return windowNames && classof(it) === 'Window' + ? getWindowNames(it) + : $getOwnPropertyNames(toIndexedObject(it)); +}; /***/ }), -/* 156 */ +/* 167 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $propertyIsEnumerable = {}.propertyIsEnumerable; -// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var fails = __webpack_require__(1); +var isObject = __webpack_require__(8); +var classof = __webpack_require__(32); +var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(145); -// Nashorn ~ JDK8 bug -var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1); +// eslint-disable-next-line es/no-object-isextensible -- safe +var $isExtensible = Object.isExtensible; +var FAILS_ON_PRIMITIVES = fails(function () { $isExtensible(1); }); -// `Object.prototype.propertyIsEnumerable` method implementation -// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable -exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { - var descriptor = getOwnPropertyDescriptor(this, V); - return !!descriptor && descriptor.enumerable; -} : $propertyIsEnumerable; +// `Object.isExtensible` method +// https://tc39.es/ecma262/#sec-object.isextensible +module.exports = (FAILS_ON_PRIMITIVES || ARRAY_BUFFER_NON_EXTENSIBLE) ? function isExtensible(it) { + if (!isObject(it)) return false; + if (ARRAY_BUFFER_NON_EXTENSIBLE && classof(it) === 'ArrayBuffer') return false; + return $isExtensible ? $isExtensible(it) : true; +} : $isExtensible; /***/ }), -/* 157 */ +/* 168 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable no-undef, no-useless-call, sonarjs/no-reference-error -- required for testing */ -/* eslint-disable es/no-legacy-object-prototype-accessor-methods -- required for testing */ -var IS_PURE = __webpack_require__(48); -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var WEBKIT = __webpack_require__(183); +var getBuiltIn = __webpack_require__(11); +var uncurryThis = __webpack_require__(2); +var getOwnPropertyNamesModule = __webpack_require__(75); +var getOwnPropertySymbolsModule = __webpack_require__(125); +var anObject = __webpack_require__(5); -// Forced replacement object prototype accessors methods -module.exports = IS_PURE || !fails(function () { - // This feature detection crashes old WebKit - // https://github.com/zloirock/core-js/issues/232 - if (WEBKIT && WEBKIT < 535) return; - var key = Math.random(); - // In FF throws only define methods - __defineSetter__.call(null, key, function () { /* empty */ }); - delete globalThis[key]; -}); +var concat = uncurryThis([].concat); + +// all object keys, includes non-enumerable and symbols +module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { + var keys = getOwnPropertyNamesModule.f(anObject(it)); + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys; +}; /***/ }), -/* 158 */ +/* 169 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +/* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */ +/* eslint-disable regexp/no-useless-quantifier -- testing */ +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); +var regexpFlags = __webpack_require__(170); +var stickyHelpers = __webpack_require__(130); +var shared = __webpack_require__(92); +var create = __webpack_require__(30); +var getInternalState = __webpack_require__(21).get; +var UNSUPPORTED_DOT_ALL = __webpack_require__(171); +var UNSUPPORTED_NCG = __webpack_require__(238); + +var nativeReplace = shared('native-string-replace', String.prototype.replace); +var nativeExec = RegExp.prototype.exec; +var patchedExec = nativeExec; +var charAt = uncurryThis(''.charAt); +var indexOf = uncurryThis(''.indexOf); +var replace = uncurryThis(''.replace); +var stringSlice = uncurryThis(''.slice); + +var UPDATES_LAST_INDEX_WRONG = (function () { + var re1 = /a/; + var re2 = /b*/g; + call(nativeExec, re1, 'a'); + call(nativeExec, re2, 'a'); + return re1.lastIndex !== 0 || re2.lastIndex !== 0; +})(); + +var UNSUPPORTED_Y = stickyHelpers.BROKEN_CARET; + +// nonparticipating capturing group, copied from es5-shim's String#split patch. +var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; + +var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG; + +if (PATCH) { + patchedExec = function exec(string) { + var re = this; + var state = getInternalState(re); + var str = toString(string); + var raw = state.raw; + var result, reCopy, lastIndex, match, i, object, group; + + if (raw) { + raw.lastIndex = re.lastIndex; + result = call(patchedExec, raw, str); + re.lastIndex = raw.lastIndex; + return result; + } + + var groups = state.groups; + var sticky = UNSUPPORTED_Y && re.sticky; + var flags = call(regexpFlags, re); + var source = re.source; + var charsAdded = 0; + var strCopy = str; + + if (sticky) { + flags = replace(flags, 'y', ''); + if (indexOf(flags, 'g') === -1) { + flags += 'g'; + } + + strCopy = stringSlice(str, re.lastIndex); + // Support anchored sticky behavior. + if (re.lastIndex > 0 && (!re.multiline || re.multiline && charAt(str, re.lastIndex - 1) !== '\n')) { + source = '(?: ' + source + ')'; + strCopy = ' ' + strCopy; + charsAdded++; + } + // ^(? + rx + ) is needed, in combination with some str slicing, to + // simulate the 'y' flag. + reCopy = new RegExp('^(?:' + source + ')', flags); + } + + if (NPCG_INCLUDED) { + reCopy = new RegExp('^' + source + '$(?!\\s)', flags); + } + if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; + + match = call(nativeExec, sticky ? reCopy : re, strCopy); + + if (sticky) { + if (match) { + match.input = stringSlice(match.input, charsAdded); + match[0] = stringSlice(match[0], charsAdded); + match.index = re.lastIndex; + re.lastIndex += match[0].length; + } else re.lastIndex = 0; + } else if (UPDATES_LAST_INDEX_WRONG && match) { + re.lastIndex = re.global ? match.index + match[0].length : lastIndex; + } + if (NPCG_INCLUDED && match && match.length > 1) { + // Fix browsers whose `exec` methods don't consistently return `undefined` + // for NPCG, like IE8. NOTE: This doesn't work for /(.?)?/ + call(nativeReplace, match[0], reCopy, function () { + for (i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) match[i] = undefined; + } + }); + } + + if (match && groups) { + match.groups = object = create(null); + for (i = 0; i < groups.length; i++) { + group = groups[i]; + object[group[0]] = match[group[1]]; + } + } + + return match; + }; +} -module.exports = globalThis; +module.exports = patchedExec; /***/ }), -/* 159 */ +/* 170 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NativePromiseConstructor = __webpack_require__(120); -var checkCorrectnessOfIteration = __webpack_require__(145); -var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(135).CONSTRUCTOR; +var anObject = __webpack_require__(5); -module.exports = FORCED_PROMISE_CONSTRUCTOR || !checkCorrectnessOfIteration(function (iterable) { - NativePromiseConstructor.all(iterable).then(undefined, function () { /* empty */ }); -}); +// `RegExp.prototype.flags` getter implementation +// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags +module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.hasIndices) result += 'd'; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.dotAll) result += 's'; + if (that.unicode) result += 'u'; + if (that.unicodeSets) result += 'v'; + if (that.sticky) result += 'y'; + return result; +}; /***/ }), -/* 160 */ +/* 171 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var globalThis = __webpack_require__(35); +var fails = __webpack_require__(1); +var globalThis = __webpack_require__(3); -// babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError +// babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError var $RegExp = globalThis.RegExp; -var UNSUPPORTED_Y = fails(function () { - var re = $RegExp('a', 'y'); - re.lastIndex = 2; - return re.exec('abcd') !== null; -}); - -// UC Browser bug -// https://github.com/zloirock/core-js/issues/1008 -var MISSED_STICKY = UNSUPPORTED_Y || fails(function () { - return !$RegExp('a', 'y').sticky; -}); - -var BROKEN_CARET = UNSUPPORTED_Y || fails(function () { - // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 - var re = $RegExp('^r', 'gy'); - re.lastIndex = 2; - return re.exec('str') !== null; +module.exports = fails(function () { + var re = $RegExp('.', 's'); + return !(re.dotAll && re.test('\n') && re.flags === 's'); }); -module.exports = { - BROKEN_CARET: BROKEN_CARET, - MISSED_STICKY: MISSED_STICKY, - UNSUPPORTED_Y: UNSUPPORTED_Y -}; - /***/ }), -/* 161 */ +/* 172 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var shared = __webpack_require__(123); -var uid = __webpack_require__(126); +var globalThis = __webpack_require__(3); +var apply = __webpack_require__(42); +var isCallable = __webpack_require__(14); +var ENVIRONMENT = __webpack_require__(119); +var USER_AGENT = __webpack_require__(51); +var arraySlice = __webpack_require__(46); +var validateArgumentsLength = __webpack_require__(48); -var keys = shared('keys'); +var Function = globalThis.Function; +// dirty IE9- and Bun 0.3.0- checks +var WRAP = /MSIE .\./.test(USER_AGENT) || ENVIRONMENT === 'BUN' && (function () { + var version = globalThis.Bun.version.split('.'); + return version.length < 3 || version[0] === '0' && (version[1] < 3 || version[1] === '3' && version[2] === '0'); +})(); -module.exports = function (key) { - return keys[key] || (keys[key] = uid(key)); +// IE9- / Bun 0.3.0- setTimeout / setInterval / setImmediate additional parameters fix +// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers +// https://github.com/oven-sh/bun/issues/1633 +module.exports = function (scheduler, hasTimeArg) { + var firstParamIndex = hasTimeArg ? 2 : 1; + return WRAP ? function (handler, timeout /* , ...arguments */) { + var boundArgs = validateArgumentsLength(arguments.length, 1) > firstParamIndex; + var fn = isCallable(handler) ? handler : Function(handler); + var params = boundArgs ? arraySlice(arguments, firstParamIndex) : []; + var callback = boundArgs ? function () { + apply(fn, this, params); + } : fn; + return hasTimeArg ? scheduler(callback, timeout) : scheduler(callback); + } : scheduler; }; /***/ }), -/* 162 */ +/* 173 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var IS_PURE = __webpack_require__(48); -var globalThis = __webpack_require__(35); -var defineGlobalProperty = __webpack_require__(181); +var SetHelpers = __webpack_require__(50); +var iterate = __webpack_require__(90); -var SHARED = '__core-js_shared__'; -var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {}); +var Set = SetHelpers.Set; +var add = SetHelpers.add; -(store.versions || (store.versions = [])).push({ - version: '3.43.0', - mode: IS_PURE ? 'pure' : 'global', - copyright: '© 2014-2025 Denis Pushkarev (zloirock.ru)', - license: 'https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE', - source: 'https://github.com/zloirock/core-js' -}); +module.exports = function (set) { + var result = new Set(); + iterate(set, function (it) { + add(result, it); + }); + return result; +}; /***/ }), -/* 163 */ +/* 174 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var anObject = __webpack_require__(37); -var aConstructor = __webpack_require__(173); -var isNullOrUndefined = __webpack_require__(89); -var wellKnownSymbol = __webpack_require__(39); +var PROPER_FUNCTION_NAME = __webpack_require__(82).PROPER; +var fails = __webpack_require__(1); +var whitespaces = __webpack_require__(107); -var SPECIES = wellKnownSymbol('species'); +var non = '\u200B\u0085\u180E'; -// `SpeciesConstructor` abstract operation -// https://tc39.es/ecma262/#sec-speciesconstructor -module.exports = function (O, defaultConstructor) { - var C = anObject(O).constructor; - var S; - return C === undefined || isNullOrUndefined(S = anObject(C)[SPECIES]) ? defaultConstructor : aConstructor(S); +// check that a method works with the correct list +// of whitespaces and has a correct name +module.exports = function (METHOD_NAME) { + return fails(function () { + return !!whitespaces[METHOD_NAME]() + || non[METHOD_NAME]() !== non + || (PROPER_FUNCTION_NAME && whitespaces[METHOD_NAME].name !== METHOD_NAME); + }); }; /***/ }), -/* 164 */ +/* 175 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var toIntegerOrInfinity = __webpack_require__(54); -var toString = __webpack_require__(41); -var requireObjectCoercible = __webpack_require__(52); - -var charAt = uncurryThis(''.charAt); -var charCodeAt = uncurryThis(''.charCodeAt); -var stringSlice = uncurryThis(''.slice); +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var V8 = __webpack_require__(52); +var ENVIRONMENT = __webpack_require__(119); -var createMethod = function (CONVERT_TO_STRING) { - return function ($this, pos) { - var S = toString(requireObjectCoercible($this)); - var position = toIntegerOrInfinity(pos); - var size = S.length; - var first, second; - if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; - first = charCodeAt(S, position); - return first < 0xD800 || first > 0xDBFF || position + 1 === size - || (second = charCodeAt(S, position + 1)) < 0xDC00 || second > 0xDFFF - ? CONVERT_TO_STRING - ? charAt(S, position) - : first - : CONVERT_TO_STRING - ? stringSlice(S, position, position + 2) - : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; - }; -}; +var structuredClone = globalThis.structuredClone; -module.exports = { - // `String.prototype.codePointAt` method - // https://tc39.es/ecma262/#sec-string.prototype.codepointat - codeAt: createMethod(false), - // `String.prototype.at` method - // https://github.com/mathiasbynens/String.prototype.at - charAt: createMethod(true) -}; +module.exports = !!structuredClone && !fails(function () { + // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation + // https://github.com/zloirock/core-js/issues/679 + if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false; + var buffer = new ArrayBuffer(8); + var clone = structuredClone(buffer, { transfer: [buffer] }); + return buffer.byteLength !== 0 || clone.byteLength !== 8; +}); /***/ }), -/* 165 */ +/* 176 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// https://github.com/tc39/proposal-string-pad-start-end -var uncurryThis = __webpack_require__(34); -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var $repeat = __webpack_require__(166); -var requireObjectCoercible = __webpack_require__(52); - -var repeat = uncurryThis($repeat); -var stringSlice = uncurryThis(''.slice); -var ceil = Math.ceil; +var toPrimitive = __webpack_require__(140); -// `String.prototype.{ padStart, padEnd }` methods implementation -var createMethod = function (IS_END) { - return function ($this, maxLength, fillString) { - var S = toString(requireObjectCoercible($this)); - var intMaxLength = toLength(maxLength); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : toString(fillString); - var fillLen, stringFiller; - if (intMaxLength <= stringLength || fillStr === '') return S; - fillLen = intMaxLength - stringLength; - stringFiller = repeat(fillStr, ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringSlice(stringFiller, 0, fillLen); - return IS_END ? S + stringFiller : stringFiller + S; - }; -}; +var $TypeError = TypeError; -module.exports = { - // `String.prototype.padStart` method - // https://tc39.es/ecma262/#sec-string.prototype.padstart - start: createMethod(false), - // `String.prototype.padEnd` method - // https://tc39.es/ecma262/#sec-string.prototype.padend - end: createMethod(true) +// `ToBigInt` abstract operation +// https://tc39.es/ecma262/#sec-tobigint +module.exports = function (argument) { + var prim = toPrimitive(argument, 'number'); + if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint"); + // eslint-disable-next-line es/no-bigint -- safe + return BigInt(prim); }; /***/ }), -/* 166 */ +/* 177 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIntegerOrInfinity = __webpack_require__(54); -var toString = __webpack_require__(41); -var requireObjectCoercible = __webpack_require__(52); +var toIntegerOrInfinity = __webpack_require__(22); var $RangeError = RangeError; -// `String.prototype.repeat` method implementation -// https://tc39.es/ecma262/#sec-string.prototype.repeat -module.exports = function repeat(count) { - var str = toString(requireObjectCoercible(this)); - var result = ''; - var n = toIntegerOrInfinity(count); - if (n < 0 || n === Infinity) throw new $RangeError('Wrong number of repetitions'); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str; +module.exports = function (it) { + var result = toIntegerOrInfinity(it); + if (result < 0) throw new $RangeError("The argument can't be less than 0"); return result; }; /***/ }), -/* 167 */ +/* 178 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var apply = __webpack_require__(74); -var bind = __webpack_require__(75); -var isCallable = __webpack_require__(46); -var hasOwn = __webpack_require__(45); -var fails = __webpack_require__(33); -var html = __webpack_require__(241); -var arraySlice = __webpack_require__(78); -var createElement = __webpack_require__(148); -var validateArgumentsLength = __webpack_require__(80); -var IS_IOS = __webpack_require__(232); -var IS_NODE = __webpack_require__(111); - -var set = globalThis.setImmediate; -var clear = globalThis.clearImmediate; -var process = globalThis.process; -var Dispatch = globalThis.Dispatch; -var Function = globalThis.Function; -var MessageChannel = globalThis.MessageChannel; -var String = globalThis.String; -var counter = 0; -var queue = {}; -var ONREADYSTATECHANGE = 'onreadystatechange'; -var $location, defer, channel, port; - -fails(function () { - // Deno throws a ReferenceError on `location` access without `--location` flag - $location = globalThis.location; -}); - -var run = function (id) { - if (hasOwn(queue, id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } -}; - -var runner = function (id) { - return function () { - run(id); - }; -}; - -var eventListener = function (event) { - run(event.data); -}; +var wellKnownSymbol = __webpack_require__(7); -var globalPostMessageDefer = function (id) { - // old engines have not location.origin - globalThis.postMessage(String(id), $location.protocol + '//' + $location.host); -}; +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var test = {}; -// Node.js 0.9+ & IE10+ has setImmediate, otherwise: -if (!set || !clear) { - set = function setImmediate(handler) { - validateArgumentsLength(arguments.length, 1); - var fn = isCallable(handler) ? handler : Function(handler); - var args = arraySlice(arguments, 1); - queue[++counter] = function () { - apply(fn, undefined, args); - }; - defer(counter); - return counter; - }; - clear = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (IS_NODE) { - defer = function (id) { - process.nextTick(runner(id)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(runner(id)); - }; - // Browsers with MessageChannel, includes WebWorkers - // except iOS - https://github.com/zloirock/core-js/issues/624 - } else if (MessageChannel && !IS_IOS) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = eventListener; - defer = bind(port.postMessage, port); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if ( - globalThis.addEventListener && - isCallable(globalThis.postMessage) && - !globalThis.importScripts && - $location && $location.protocol !== 'file:' && - !fails(globalPostMessageDefer) - ) { - defer = globalPostMessageDefer; - globalThis.addEventListener('message', eventListener, false); - // IE8- - } else if (ONREADYSTATECHANGE in createElement('script')) { - defer = function (id) { - html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(runner(id), 0); - }; - } -} +test[TO_STRING_TAG] = 'z'; -module.exports = { - set: set, - clear: clear -}; +module.exports = String(test) === '[object z]'; /***/ }), -/* 168 */ +/* 179 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); +/* eslint-disable no-new, sonarjs/inconsistent-function-call -- required for testing */ +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var checkCorrectnessOfIteration = __webpack_require__(115); +var NATIVE_ARRAY_BUFFER_VIEWS = __webpack_require__(12).NATIVE_ARRAY_BUFFER_VIEWS; -// `thisNumberValue` abstract operation -// https://tc39.es/ecma262/#sec-thisnumbervalue -module.exports = uncurryThis(1.1.valueOf); +var ArrayBuffer = globalThis.ArrayBuffer; +var Int8Array = globalThis.Int8Array; + +module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () { + Int8Array(1); +}) || !fails(function () { + new Int8Array(-1); +}) || !checkCorrectnessOfIteration(function (iterable) { + new Int8Array(); + new Int8Array(null); + new Int8Array(1.5); + new Int8Array(iterable); +}, true) || fails(function () { + // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill + return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1; +}); /***/ }), -/* 169 */ +/* 180 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIntegerOrInfinity = __webpack_require__(54); -var toLength = __webpack_require__(77); - -var $RangeError = RangeError; +var $ = __webpack_require__(0); +var exec = __webpack_require__(169); -// `ToIndex` abstract operation -// https://tc39.es/ecma262/#sec-toindex -module.exports = function (it) { - if (it === undefined) return 0; - var number = toIntegerOrInfinity(it); - var length = toLength(number); - if (number !== length) throw new $RangeError('Wrong length or index'); - return length; -}; +// `RegExp.prototype.exec` method +// https://tc39.es/ecma262/#sec-regexp.prototype.exec +$({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, { + exec: exec +}); /***/ }), -/* 170 */ +/* 181 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var isObject = __webpack_require__(40); -var isSymbol = __webpack_require__(104); -var getMethod = __webpack_require__(60); -var ordinaryToPrimitive = __webpack_require__(262); -var wellKnownSymbol = __webpack_require__(39); +var isPossiblePrototype = __webpack_require__(217); +var $String = String; var $TypeError = TypeError; -var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); -// `ToPrimitive` abstract operation -// https://tc39.es/ecma262/#sec-toprimitive -module.exports = function (input, pref) { - if (!isObject(input) || isSymbol(input)) return input; - var exoticToPrim = getMethod(input, TO_PRIMITIVE); - var result; - if (exoticToPrim) { - if (pref === undefined) pref = 'default'; - result = call(exoticToPrim, input, pref); - if (!isObject(result) || isSymbol(result)) return result; - throw new $TypeError("Can't convert object to primitive value"); - } - if (pref === undefined) pref = 'number'; - return ordinaryToPrimitive(input, pref); +module.exports = function (argument) { + if (isPossiblePrototype(argument)) return argument; + throw new $TypeError("Can't set " + $String(argument) + ' as a prototype'); }; /***/ }), -/* 171 */ +/* 182 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var wellKnownSymbol = __webpack_require__(39); -var DESCRIPTORS = __webpack_require__(38); -var IS_PURE = __webpack_require__(48); +var getBuiltIn = __webpack_require__(11); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var bind = __webpack_require__(43); +var anObject = __webpack_require__(5); +var aCallable = __webpack_require__(10); +var isNullOrUndefined = __webpack_require__(57); +var getMethod = __webpack_require__(28); +var wellKnownSymbol = __webpack_require__(7); -var ITERATOR = wellKnownSymbol('iterator'); +var ASYNC_DISPOSE = wellKnownSymbol('asyncDispose'); +var DISPOSE = wellKnownSymbol('dispose'); -module.exports = !fails(function () { - // eslint-disable-next-line unicorn/relative-url-style -- required for testing - var url = new URL('b?a=1&b=2&c=3', 'https://a'); - var params = url.searchParams; - var params2 = new URLSearchParams('a=1&a=2&b=3'); - var result = ''; - url.pathname = 'c%20d'; - params.forEach(function (value, key) { - params['delete']('b'); - result += key + value; - }); - params2['delete']('a', 2); - // `undefined` case is a Chromium 117 bug - // https://bugs.chromium.org/p/v8/issues/detail?id=14222 - params2['delete']('b', undefined); - return (IS_PURE && (!url.toJSON || !params2.has('a', 1) || params2.has('a', 2) || !params2.has('a', undefined) || params2.has('b'))) - || (!params.size && (IS_PURE || !DESCRIPTORS)) - || !params.sort - || url.href !== 'https://a/c%20d?a=1&c=3' - || params.get('c') !== '3' - || String(new URLSearchParams('?a=1')) !== 'a=1' - || !params[ITERATOR] - // throws in Edge - || new URL('https://a@b').username !== 'a' - || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' - // not punycoded in Edge - || new URL('https://тест').host !== 'xn--e1aybc' - // not escaped in Chrome 62- - || new URL('https://a#б').hash !== '#%D0%B1' - // fails in Chrome 66- - || result !== 'a1c3' - // throws in Safari - || new URL('https://x', undefined).host !== 'x'; -}); +var push = uncurryThis([].push); + +// `GetDisposeMethod` abstract operation +// https://tc39.es/proposal-explicit-resource-management/#sec-getdisposemethod +var getDisposeMethod = function (V, hint) { + if (hint === 'async-dispose') { + var method = getMethod(V, ASYNC_DISPOSE); + if (method !== undefined) return method; + method = getMethod(V, DISPOSE); + if (method === undefined) return method; + return function () { + var O = this; + var Promise = getBuiltIn('Promise'); + return new Promise(function (resolve) { + call(method, O); + resolve(undefined); + }); + }; + } return getMethod(V, DISPOSE); +}; +// `CreateDisposableResource` abstract operation +// https://tc39.es/proposal-explicit-resource-management/#sec-createdisposableresource +var createDisposableResource = function (V, hint, method) { + if (arguments.length < 3 && !isNullOrUndefined(V)) { + method = aCallable(getDisposeMethod(anObject(V), hint)); + } -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { + return method === undefined ? function () { + return undefined; + } : bind(method, V); +}; -"use strict"; +// `AddDisposableResource` abstract operation +// https://tc39.es/proposal-explicit-resource-management/#sec-adddisposableresource +module.exports = function (disposable, V, hint, method) { + var resource; + if (arguments.length < 4) { + // When `V`` is either `null` or `undefined` and hint is `async-dispose`, + // we record that the resource was evaluated to ensure we will still perform an `Await` when resources are later disposed. + if (isNullOrUndefined(V) && hint === 'sync-dispose') return; + resource = createDisposableResource(V, hint); + } else { + resource = createDisposableResource(undefined, hint, method); + } -var toIndexedObject = __webpack_require__(57); -var addToUnscopables = __webpack_require__(69); -var Iterators = __webpack_require__(133); -var InternalStateModule = __webpack_require__(53); -var defineProperty = __webpack_require__(51).f; -var defineIterator = __webpack_require__(190); -var createIterResultObject = __webpack_require__(96); -var IS_PURE = __webpack_require__(48); -var DESCRIPTORS = __webpack_require__(38); + push(disposable.stack, resource); +}; -var ARRAY_ITERATOR = 'Array Iterator'; -var setInternalState = InternalStateModule.set; -var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); -// `Array.prototype.entries` method -// https://tc39.es/ecma262/#sec-array.prototype.entries -// `Array.prototype.keys` method -// https://tc39.es/ecma262/#sec-array.prototype.keys -// `Array.prototype.values` method -// https://tc39.es/ecma262/#sec-array.prototype.values -// `Array.prototype[@@iterator]` method -// https://tc39.es/ecma262/#sec-array.prototype-@@iterator -// `CreateArrayIterator` internal method -// https://tc39.es/ecma262/#sec-createarrayiterator -module.exports = defineIterator(Array, 'Array', function (iterated, kind) { - setInternalState(this, { - type: ARRAY_ITERATOR, - target: toIndexedObject(iterated), // target - index: 0, // next index - kind: kind // kind - }); -// `%ArrayIteratorPrototype%.next` method -// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next -}, function () { - var state = getInternalState(this); - var target = state.target; - var index = state.index++; - if (!target || index >= target.length) { - state.target = null; - return createIterResultObject(undefined, true); - } - switch (state.kind) { - case 'keys': return createIterResultObject(index, false); - case 'values': return createIterResultObject(target[index], false); - } return createIterResultObject([index, target[index]], false); -}, 'values'); +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { -// argumentsList[@@iterator] is %ArrayProto_values% -// https://tc39.es/ecma262/#sec-createunmappedargumentsobject -// https://tc39.es/ecma262/#sec-createmappedargumentsobject -var values = Iterators.Arguments = Iterators.Array; +"use strict"; -// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); +var globalThis = __webpack_require__(3); +var uncurryThisAccessor = __webpack_require__(121); +var classof = __webpack_require__(32); -// V8 ~ Chrome 45- bug -if (!IS_PURE && DESCRIPTORS && values.name !== 'values') try { - defineProperty(values, 'name', { value: 'values' }); -} catch (error) { /* empty */ } +var ArrayBuffer = globalThis.ArrayBuffer; +var TypeError = globalThis.TypeError; + +// Includes +// - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). +// - If IsSharedArrayBuffer(O) is true, throw a TypeError exception. +module.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) { + if (classof(O) !== 'ArrayBuffer') throw new TypeError('ArrayBuffer expected'); + return O.byteLength; +}; /***/ }), -/* 173 */ +/* 184 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isConstructor = __webpack_require__(103); -var tryToString = __webpack_require__(109); +var globalThis = __webpack_require__(3); +var NATIVE_ARRAY_BUFFER = __webpack_require__(110); +var arrayBufferByteLength = __webpack_require__(183); -var $TypeError = TypeError; +var DataView = globalThis.DataView; -// `Assert: IsConstructor(argument) is true` -module.exports = function (argument) { - if (isConstructor(argument)) return argument; - throw new $TypeError(tryToString(argument) + ' is not a constructor'); +module.exports = function (O) { + if (!NATIVE_ARRAY_BUFFER || arrayBufferByteLength(O) !== 0) return false; + try { + // eslint-disable-next-line no-new -- thrower + new DataView(O); + return false; + } catch (error) { + return true; + } }; /***/ }), -/* 174 */ +/* 185 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// FF26- bug: ArrayBuffers are non-extensible, but Object.isExtensible does not report it -var fails = __webpack_require__(33); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var uncurryThisAccessor = __webpack_require__(121); +var toIndex = __webpack_require__(139); +var notDetached = __webpack_require__(284); +var arrayBufferByteLength = __webpack_require__(183); +var detachTransferable = __webpack_require__(197); +var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(175); -module.exports = fails(function () { - if (typeof ArrayBuffer == 'function') { - var buffer = new ArrayBuffer(8); - // eslint-disable-next-line es/no-object-isextensible, es/no-object-defineproperty -- safe - if (Object.isExtensible(buffer)) Object.defineProperty(buffer, 'a', { value: 8 }); +var structuredClone = globalThis.structuredClone; +var ArrayBuffer = globalThis.ArrayBuffer; +var DataView = globalThis.DataView; +var min = Math.min; +var ArrayBufferPrototype = ArrayBuffer.prototype; +var DataViewPrototype = DataView.prototype; +var slice = uncurryThis(ArrayBufferPrototype.slice); +var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get'); +var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get'); +var getInt8 = uncurryThis(DataViewPrototype.getInt8); +var setInt8 = uncurryThis(DataViewPrototype.setInt8); + +module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) { + var byteLength = arrayBufferByteLength(arrayBuffer); + var newByteLength = newLength === undefined ? byteLength : toIndex(newLength); + var fixedLength = !isResizable || !isResizable(arrayBuffer); + var newBuffer; + notDetached(arrayBuffer); + if (PROPER_STRUCTURED_CLONE_TRANSFER) { + arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] }); + if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer; } -}); + if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) { + newBuffer = slice(arrayBuffer, 0, newByteLength); + } else { + var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined; + newBuffer = new ArrayBuffer(newByteLength, options); + var a = new DataView(arrayBuffer); + var b = new DataView(newBuffer); + var copyLength = min(newByteLength, byteLength); + for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i)); + } + if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer); + return newBuffer; +}; /***/ }), -/* 175 */ +/* 186 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toObject = __webpack_require__(47); -var toAbsoluteIndex = __webpack_require__(91); -var lengthOfArrayLike = __webpack_require__(50); +var toObject = __webpack_require__(15); +var toAbsoluteIndex = __webpack_require__(59); +var lengthOfArrayLike = __webpack_require__(18); +var deletePropertyOrThrow = __webpack_require__(117); -// `Array.prototype.fill` method implementation -// https://tc39.es/ecma262/#sec-array.prototype.fill -module.exports = function fill(value /* , start = 0, end = @length */) { +var min = Math.min; + +// `Array.prototype.copyWithin` method implementation +// https://tc39.es/ecma262/#sec-array.prototype.copywithin +// eslint-disable-next-line es/no-array-prototype-copywithin -- safe +module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { var O = toObject(this); - var length = lengthOfArrayLike(O); - var argumentsLength = arguments.length; - var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); - var end = argumentsLength > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; + var len = lengthOfArrayLike(O); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else deletePropertyOrThrow(O, to); + to += inc; + from += inc; + } return O; }; /***/ }), -/* 176 */ +/* 187 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var isArray = __webpack_require__(93); - -var $TypeError = TypeError; -// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var $forEach = __webpack_require__(26).forEach; +var arrayMethodIsStrict = __webpack_require__(54); -// Safari < 13 does not throw an error in this case -var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () { - // makes no sense without proper strict mode support - if (this !== undefined) return true; - try { - // eslint-disable-next-line es/no-object-defineproperty -- safe - Object.defineProperty([], 'length', { writable: false }).length = 1; - } catch (error) { - return error instanceof TypeError; - } -}(); +var STRICT_METHOD = arrayMethodIsStrict('forEach'); -module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) { - if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) { - throw new $TypeError('Cannot set read only .length'); - } return O.length = length; -} : function (O, length) { - return O.length = length; -}; +// `Array.prototype.forEach` method implementation +// https://tc39.es/ecma262/#sec-array.prototype.foreach +module.exports = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); +// eslint-disable-next-line es/no-array-prototype-foreach -- safe +} : [].forEach; /***/ }), -/* 177 */ +/* 188 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arraySlice = __webpack_require__(78); - -var floor = Math.floor; - -var sort = function (array, comparefn) { - var length = array.length; +var bind = __webpack_require__(43); +var call = __webpack_require__(4); +var toObject = __webpack_require__(15); +var callWithSafeIterationClosing = __webpack_require__(149); +var isArrayIteratorMethod = __webpack_require__(158); +var isConstructor = __webpack_require__(72); +var lengthOfArrayLike = __webpack_require__(18); +var createProperty = __webpack_require__(55); +var getIterator = __webpack_require__(83); +var getIteratorMethod = __webpack_require__(68); - if (length < 8) { - // insertion sort - var i = 1; - var element, j; +var $Array = Array; - while (i < length) { - j = i; - element = array[i]; - while (j && comparefn(array[j - 1], element) > 0) { - array[j] = array[--j]; - } - if (j !== i++) array[j] = element; +// `Array.from` method implementation +// https://tc39.es/ecma262/#sec-array.from +module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var IS_CONSTRUCTOR = isConstructor(this); + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined); + var iteratorMethod = getIteratorMethod(O); + var index = 0; + var length, result, step, iterator, next, value; + // if the target is not iterable or it's an array with the default iterator - use a simple case + if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) { + result = IS_CONSTRUCTOR ? new this() : []; + iterator = getIterator(O, iteratorMethod); + next = iterator.next; + for (;!(step = call(next, iterator)).done; index++) { + value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; + createProperty(result, index, value); } } else { - // merge sort - var middle = floor(length / 2); - var left = sort(arraySlice(array, 0, middle), comparefn); - var right = sort(arraySlice(array, middle), comparefn); - var llength = left.length; - var rlength = right.length; - var lindex = 0; - var rindex = 0; - - while (lindex < llength || rindex < rlength) { - array[lindex + rindex] = (lindex < llength && rindex < rlength) - ? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++] - : lindex < llength ? left[lindex++] : right[rindex++]; + length = lengthOfArrayLike(O); + result = IS_CONSTRUCTOR ? new this(length) : $Array(length); + for (;length > index; index++) { + value = mapping ? mapfn(O[index], index) : O[index]; + createProperty(result, index, value); } } - - return array; + result.length = index; + return result; }; -module.exports = sort; - /***/ }), -/* 178 */ +/* 189 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var anObject = __webpack_require__(37); -var iteratorClose = __webpack_require__(61); +/* eslint-disable es/no-array-prototype-lastindexof -- safe */ +var apply = __webpack_require__(42); +var toIndexedObject = __webpack_require__(25); +var toIntegerOrInfinity = __webpack_require__(22); +var lengthOfArrayLike = __webpack_require__(18); +var arrayMethodIsStrict = __webpack_require__(54); -// call something on iterator step with safe closing on error -module.exports = function (iterator, fn, value, ENTRIES) { - try { - return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); - } catch (error) { - iteratorClose(iterator, 'throw', error); - } -}; +var min = Math.min; +var $lastIndexOf = [].lastIndexOf; +var NEGATIVE_ZERO = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0; +var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); +var FORCED = NEGATIVE_ZERO || !STRICT_METHOD; + +// `Array.prototype.lastIndexOf` method implementation +// https://tc39.es/ecma262/#sec-array.prototype.lastindexof +module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return apply($lastIndexOf, this, arguments) || 0; + var O = toIndexedObject(this); + var length = lengthOfArrayLike(O); + if (length === 0) return -1; + var index = length - 1; + if (arguments.length > 1) index = min(index, toIntegerOrInfinity(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; + return -1; +} : $lastIndexOf; /***/ }), -/* 179 */ +/* 190 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var wellKnownSymbol = __webpack_require__(39); +var lengthOfArrayLike = __webpack_require__(18); -var MATCH = wellKnownSymbol('match'); - -module.exports = function (METHOD_NAME) { - var regexp = /./; - try { - '/./'[METHOD_NAME](regexp); - } catch (error1) { - try { - regexp[MATCH] = false; - return '/./'[METHOD_NAME](regexp); - } catch (error2) { /* empty */ } - } return false; +// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed +// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed +module.exports = function (O, C) { + var len = lengthOfArrayLike(O); + var A = new C(len); + var k = 0; + for (; k < len; k++) A[k] = O[len - k - 1]; + return A; }; /***/ }), -/* 180 */ +/* 191 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); +var lengthOfArrayLike = __webpack_require__(18); +var toIntegerOrInfinity = __webpack_require__(22); -module.exports = !fails(function () { - function F() { /* empty */ } - F.prototype.constructor = null; - // eslint-disable-next-line es/no-object-getprototypeof -- required for testing - return Object.getPrototypeOf(new F()) !== F.prototype; -}); +var $RangeError = RangeError; + +// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with +// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with +module.exports = function (O, C, index, value) { + var len = lengthOfArrayLike(O); + var relativeIndex = toIntegerOrInfinity(index); + var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex; + if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index'); + var A = new C(len); + var k = 0; + for (; k < len; k++) A[k] = k === actualIndex ? value : O[k]; + return A; +}; /***/ }), -/* 181 */ +/* 192 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var create = __webpack_require__(30); +var getMethod = __webpack_require__(28); +var defineBuiltIns = __webpack_require__(56); +var InternalStateModule = __webpack_require__(21); +var iteratorClose = __webpack_require__(29); +var getBuiltIn = __webpack_require__(11); +var AsyncIteratorPrototype = __webpack_require__(193); +var createIterResultObject = __webpack_require__(65); -// eslint-disable-next-line es/no-object-defineproperty -- safe -var defineProperty = Object.defineProperty; +var Promise = getBuiltIn('Promise'); -module.exports = function (key, value) { - try { - defineProperty(globalThis, key, { value: value, configurable: true, writable: true }); - } catch (error) { - globalThis[key] = value; - } return value; +var ASYNC_FROM_SYNC_ITERATOR = 'AsyncFromSyncIterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(ASYNC_FROM_SYNC_ITERATOR); + +var asyncFromSyncIteratorContinuation = function (result, resolve, reject, syncIterator, closeOnRejection) { + var done = result.done; + Promise.resolve(result.value).then(function (value) { + resolve(createIterResultObject(value, done)); + }, function (error) { + if (!done && closeOnRejection) { + try { + iteratorClose(syncIterator, 'throw', error); + } catch (error2) { + error = error2; + } + } + + reject(error); + }); }; +var AsyncFromSyncIterator = function AsyncIterator(iteratorRecord) { + iteratorRecord.type = ASYNC_FROM_SYNC_ITERATOR; + setInternalState(this, iteratorRecord); +}; + +AsyncFromSyncIterator.prototype = defineBuiltIns(create(AsyncIteratorPrototype), { + next: function next() { + var state = getInternalState(this); + return new Promise(function (resolve, reject) { + var result = anObject(call(state.next, state.iterator)); + asyncFromSyncIteratorContinuation(result, resolve, reject, state.iterator, true); + }); + }, + 'return': function () { + var iterator = getInternalState(this).iterator; + return new Promise(function (resolve, reject) { + var $return = getMethod(iterator, 'return'); + if ($return === undefined) return resolve(createIterResultObject(undefined, true)); + var result = anObject(call($return, iterator)); + asyncFromSyncIteratorContinuation(result, resolve, reject, iterator); + }); + } +}); + +module.exports = AsyncFromSyncIterator; + /***/ }), -/* 182 */ +/* 193 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// IE8- don't enum bug keys -module.exports = [ - 'constructor', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'toLocaleString', - 'toString', - 'valueOf' -]; +var globalThis = __webpack_require__(3); +var shared = __webpack_require__(132); +var isCallable = __webpack_require__(14); +var create = __webpack_require__(30); +var getPrototypeOf = __webpack_require__(35); +var defineBuiltIn = __webpack_require__(17); +var wellKnownSymbol = __webpack_require__(7); +var IS_PURE = __webpack_require__(16); + +var USE_FUNCTION_CONSTRUCTOR = 'USE_FUNCTION_CONSTRUCTOR'; +var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); +var AsyncIterator = globalThis.AsyncIterator; +var PassedAsyncIteratorPrototype = shared.AsyncIteratorPrototype; +var AsyncIteratorPrototype, prototype; + +if (PassedAsyncIteratorPrototype) { + AsyncIteratorPrototype = PassedAsyncIteratorPrototype; +} else if (isCallable(AsyncIterator)) { + AsyncIteratorPrototype = AsyncIterator.prototype; +} else if (shared[USE_FUNCTION_CONSTRUCTOR] || globalThis[USE_FUNCTION_CONSTRUCTOR]) { + try { + // eslint-disable-next-line no-new-func -- we have no alternatives without usage of modern syntax + prototype = getPrototypeOf(getPrototypeOf(getPrototypeOf(Function('return async function*(){}()')()))); + if (getPrototypeOf(prototype) === Object.prototype) AsyncIteratorPrototype = prototype; + } catch (error) { /* empty */ } +} + +if (!AsyncIteratorPrototype) AsyncIteratorPrototype = {}; +else if (IS_PURE) AsyncIteratorPrototype = create(AsyncIteratorPrototype); + +if (!isCallable(AsyncIteratorPrototype[ASYNC_ITERATOR])) { + defineBuiltIn(AsyncIteratorPrototype, ASYNC_ITERATOR, function () { + return this; + }); +} + +module.exports = AsyncIteratorPrototype; /***/ }), -/* 183 */ +/* 194 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var userAgent = __webpack_require__(83); +var commonAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +var base64Alphabet = commonAlphabet + '+/'; +var base64UrlAlphabet = commonAlphabet + '-_'; -var webkit = userAgent.match(/AppleWebKit\/(\d+)\./); +var inverse = function (characters) { + // TODO: use `Object.create(null)` in `core-js@4` + var result = {}; + var index = 0; + for (; index < 64; index++) result[characters.charAt(index)] = index; + return result; +}; -module.exports = !!webkit && +webkit[1]; +module.exports = { + i2c: base64Alphabet, + c2i: inverse(base64Alphabet), + i2cUrl: base64UrlAlphabet, + c2iUrl: inverse(base64UrlAlphabet) +}; /***/ }), -/* 184 */ +/* 195 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); +var create = __webpack_require__(30); +var defineBuiltInAccessor = __webpack_require__(23); +var defineBuiltIns = __webpack_require__(56); +var bind = __webpack_require__(43); +var anInstance = __webpack_require__(39); +var isNullOrUndefined = __webpack_require__(57); +var iterate = __webpack_require__(24); +var defineIterator = __webpack_require__(161); +var createIterResultObject = __webpack_require__(65); +var setSpecies = __webpack_require__(91); +var DESCRIPTORS = __webpack_require__(6); +var fastKey = __webpack_require__(71).fastKey; +var InternalStateModule = __webpack_require__(21); -var $Error = Error; -var replace = uncurryThis(''.replace); +var setInternalState = InternalStateModule.set; +var internalStateGetterFor = InternalStateModule.getterFor; -var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd'); -// eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe -var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/; -var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST); +module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var Constructor = wrapper(function (that, iterable) { + anInstance(that, Prototype); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + index: create(null), + first: null, + last: null, + size: 0 + }); + if (!DESCRIPTORS) that.size = 0; + if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); + }); -module.exports = function (stack, dropEntries) { - if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) { - while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, ''); - } return stack; -}; + var Prototype = Constructor.prototype; + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { + var define = function (that, key, value) { + var state = getInternalState(that); + var entry = getEntry(that, key); + var previous, index; + // change existing entry + if (entry) { + entry.value = value; + // create new entry + } else { + state.last = entry = { + index: index = fastKey(key, true), + key: key, + value: value, + previous: previous = state.last, + next: null, + removed: false + }; + if (!state.first) state.first = entry; + if (previous) previous.next = entry; + if (DESCRIPTORS) state.size++; + else that.size++; + // add to index + if (index !== 'F') state.index[index] = entry; + } return that; + }; -"use strict"; + var getEntry = function (that, key) { + var state = getInternalState(that); + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return state.index[index]; + // frozen object case + for (entry = state.first; entry; entry = entry.next) { + if (entry.key === key) return entry; + } + }; -var createNonEnumerableProperty = __webpack_require__(59); -var clearErrorStack = __webpack_require__(184); -var ERROR_STACK_INSTALLABLE = __webpack_require__(233); + defineBuiltIns(Prototype, { + // `{ Map, Set }.prototype.clear()` methods + // https://tc39.es/ecma262/#sec-map.prototype.clear + // https://tc39.es/ecma262/#sec-set.prototype.clear + clear: function clear() { + var that = this; + var state = getInternalState(that); + var entry = state.first; + while (entry) { + entry.removed = true; + if (entry.previous) entry.previous = entry.previous.next = null; + entry = entry.next; + } + state.first = state.last = null; + state.index = create(null); + if (DESCRIPTORS) state.size = 0; + else that.size = 0; + }, + // `{ Map, Set }.prototype.delete(key)` methods + // https://tc39.es/ecma262/#sec-map.prototype.delete + // https://tc39.es/ecma262/#sec-set.prototype.delete + 'delete': function (key) { + var that = this; + var state = getInternalState(that); + var entry = getEntry(that, key); + if (entry) { + var next = entry.next; + var prev = entry.previous; + delete state.index[entry.index]; + entry.removed = true; + if (prev) prev.next = next; + if (next) next.previous = prev; + if (state.first === entry) state.first = next; + if (state.last === entry) state.last = prev; + if (DESCRIPTORS) state.size--; + else that.size--; + } return !!entry; + }, + // `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods + // https://tc39.es/ecma262/#sec-map.prototype.foreach + // https://tc39.es/ecma262/#sec-set.prototype.foreach + forEach: function forEach(callbackfn /* , that = undefined */) { + var state = getInternalState(this); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined); + var entry; + while (entry = entry ? entry.next : state.first) { + boundFunction(entry.value, entry.key, this); + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + } + }, + // `{ Map, Set}.prototype.has(key)` methods + // https://tc39.es/ecma262/#sec-map.prototype.has + // https://tc39.es/ecma262/#sec-set.prototype.has + has: function has(key) { + return !!getEntry(this, key); + } + }); -// non-standard V8 -// eslint-disable-next-line es/no-nonstandard-error-properties -- safe -var captureStackTrace = Error.captureStackTrace; + defineBuiltIns(Prototype, IS_MAP ? { + // `Map.prototype.get(key)` method + // https://tc39.es/ecma262/#sec-map.prototype.get + get: function get(key) { + var entry = getEntry(this, key); + return entry && entry.value; + }, + // `Map.prototype.set(key, value)` method + // https://tc39.es/ecma262/#sec-map.prototype.set + set: function set(key, value) { + return define(this, key === 0 ? 0 : key, value); + } + } : { + // `Set.prototype.add(value)` method + // https://tc39.es/ecma262/#sec-set.prototype.add + add: function add(value) { + return define(this, value = value === 0 ? 0 : value, value); + } + }); + if (DESCRIPTORS) defineBuiltInAccessor(Prototype, 'size', { + configurable: true, + get: function () { + return getInternalState(this).size; + } + }); + return Constructor; + }, + setStrong: function (Constructor, CONSTRUCTOR_NAME, IS_MAP) { + var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; + var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); + var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); + // `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods + // https://tc39.es/ecma262/#sec-map.prototype.entries + // https://tc39.es/ecma262/#sec-map.prototype.keys + // https://tc39.es/ecma262/#sec-map.prototype.values + // https://tc39.es/ecma262/#sec-map.prototype-@@iterator + // https://tc39.es/ecma262/#sec-set.prototype.entries + // https://tc39.es/ecma262/#sec-set.prototype.keys + // https://tc39.es/ecma262/#sec-set.prototype.values + // https://tc39.es/ecma262/#sec-set.prototype-@@iterator + defineIterator(Constructor, CONSTRUCTOR_NAME, function (iterated, kind) { + setInternalState(this, { + type: ITERATOR_NAME, + target: iterated, + state: getInternalCollectionState(iterated), + kind: kind, + last: null + }); + }, function () { + var state = getInternalIteratorState(this); + var kind = state.kind; + var entry = state.last; + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + // get next entry + if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { + // or finish the iteration + state.target = null; + return createIterResultObject(undefined, true); + } + // return step by kind + if (kind === 'keys') return createIterResultObject(entry.key, false); + if (kind === 'values') return createIterResultObject(entry.value, false); + return createIterResultObject([entry.key, entry.value], false); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); -module.exports = function (error, C, stack, dropEntries) { - if (ERROR_STACK_INSTALLABLE) { - if (captureStackTrace) captureStackTrace(error, C); - else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries)); + // `{ Map, Set }.prototype[@@species]` accessors + // https://tc39.es/ecma262/#sec-get-map-@@species + // https://tc39.es/ecma262/#sec-get-set-@@species + setSpecies(CONSTRUCTOR_NAME); } }; /***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var uncurryThis = __webpack_require__(34); -var isCallable = __webpack_require__(46); -var store = __webpack_require__(162); - -var functionToString = uncurryThis(Function.toString); - -// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper -if (!isCallable(store.inspectSource)) { - store.inspectSource = function (it) { - return functionToString(it); - }; -} - -module.exports = store.inspectSource; - - -/***/ }), -/* 187 */ +/* 196 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var wellKnownSymbol = __webpack_require__(39); -var Iterators = __webpack_require__(133); +var uncurryThis = __webpack_require__(2); +var defineBuiltIns = __webpack_require__(56); +var getWeakData = __webpack_require__(71).getWeakData; +var anInstance = __webpack_require__(39); +var anObject = __webpack_require__(5); +var isNullOrUndefined = __webpack_require__(57); +var isObject = __webpack_require__(8); +var iterate = __webpack_require__(24); +var ArrayIterationModule = __webpack_require__(26); +var hasOwn = __webpack_require__(13); +var InternalStateModule = __webpack_require__(21); -var ITERATOR = wellKnownSymbol('iterator'); -var ArrayPrototype = Array.prototype; +var setInternalState = InternalStateModule.set; +var internalStateGetterFor = InternalStateModule.getterFor; +var find = ArrayIterationModule.find; +var findIndex = ArrayIterationModule.findIndex; +var splice = uncurryThis([].splice); +var id = 0; -// check on default Array iterator -module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); +// fallback for uncaught frozen keys +var uncaughtFrozenStore = function (state) { + return state.frozen || (state.frozen = new UncaughtFrozenStore()); }; - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var isObject = __webpack_require__(40); - -var floor = Math.floor; - -// `IsIntegralNumber` abstract operation -// https://tc39.es/ecma262/#sec-isintegralnumber -// eslint-disable-next-line es/no-number-isinteger -- safe -module.exports = Number.isInteger || function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; +var UncaughtFrozenStore = function () { + this.entries = []; }; - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var IteratorPrototype = __webpack_require__(117).IteratorPrototype; -var create = __webpack_require__(62); -var createPropertyDescriptor = __webpack_require__(73); -var setToStringTag = __webpack_require__(70); -var Iterators = __webpack_require__(133); - -var returnThis = function () { return this; }; - -module.exports = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) { - var TO_STRING_TAG = NAME + ' Iterator'; - IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) }); - setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); - Iterators[TO_STRING_TAG] = returnThis; - return IteratorConstructor; +var findUncaughtFrozen = function (store, key) { + return find(store.entries, function (it) { + return it[0] === key; + }); }; +UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.entries.push([key, value]); + }, + 'delete': function (key) { + var index = findIndex(this.entries, function (it) { + return it[0] === key; + }); + if (~index) splice(this.entries, index, 1); + return !!~index; + } +}; -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var IS_PURE = __webpack_require__(48); -var FunctionName = __webpack_require__(113); -var isCallable = __webpack_require__(46); -var createIteratorConstructor = __webpack_require__(189); -var getPrototypeOf = __webpack_require__(67); -var setPrototypeOf = __webpack_require__(81); -var setToStringTag = __webpack_require__(70); -var createNonEnumerableProperty = __webpack_require__(59); -var defineBuiltIn = __webpack_require__(49); -var wellKnownSymbol = __webpack_require__(39); -var Iterators = __webpack_require__(133); -var IteratorsCore = __webpack_require__(117); - -var PROPER_FUNCTION_NAME = FunctionName.PROPER; -var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE; -var IteratorPrototype = IteratorsCore.IteratorPrototype; -var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; -var ITERATOR = wellKnownSymbol('iterator'); -var KEYS = 'keys'; -var VALUES = 'values'; -var ENTRIES = 'entries'; - -var returnThis = function () { return this; }; - -module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { - createIteratorConstructor(IteratorConstructor, NAME, next); +module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var Constructor = wrapper(function (that, iterable) { + anInstance(that, Prototype); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + id: id++, + frozen: null + }); + if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); + }); - var getIterationMethod = function (KIND) { - if (KIND === DEFAULT && defaultIterator) return defaultIterator; - if (!BUGGY_SAFARI_ITERATORS && KIND && KIND in IterablePrototype) return IterablePrototype[KIND]; + var Prototype = Constructor.prototype; - switch (KIND) { - case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; - case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; - case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; - } + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); - return function () { return new IteratorConstructor(this); }; - }; + var define = function (that, key, value) { + var state = getInternalState(that); + var data = getWeakData(anObject(key), true); + if (data === true) uncaughtFrozenStore(state).set(key, value); + else data[state.id] = value; + return that; + }; - var TO_STRING_TAG = NAME + ' Iterator'; - var INCORRECT_VALUES_NAME = false; - var IterablePrototype = Iterable.prototype; - var nativeIterator = IterablePrototype[ITERATOR] - || IterablePrototype['@@iterator'] - || DEFAULT && IterablePrototype[DEFAULT]; - var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); - var anyNativeIterator = NAME === 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; - var CurrentIteratorPrototype, methods, KEY; + defineBuiltIns(Prototype, { + // `{ WeakMap, WeakSet }.prototype.delete(key)` methods + // https://tc39.es/ecma262/#sec-weakmap.prototype.delete + // https://tc39.es/ecma262/#sec-weakset.prototype.delete + 'delete': function (key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state)['delete'](key); + return data && hasOwn(data, state.id) && delete data[state.id]; + }, + // `{ WeakMap, WeakSet }.prototype.has(key)` methods + // https://tc39.es/ecma262/#sec-weakmap.prototype.has + // https://tc39.es/ecma262/#sec-weakset.prototype.has + has: function has(key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).has(key); + return data && hasOwn(data, state.id); + } + }); - // fix native - if (anyNativeIterator) { - CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); - if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { - if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { - if (setPrototypeOf) { - setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); - } else if (!isCallable(CurrentIteratorPrototype[ITERATOR])) { - defineBuiltIn(CurrentIteratorPrototype, ITERATOR, returnThis); + defineBuiltIns(Prototype, IS_MAP ? { + // `WeakMap.prototype.get(key)` method + // https://tc39.es/ecma262/#sec-weakmap.prototype.get + get: function get(key) { + var state = getInternalState(this); + if (isObject(key)) { + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).get(key); + if (data) return data[state.id]; } + }, + // `WeakMap.prototype.set(key, value)` method + // https://tc39.es/ecma262/#sec-weakmap.prototype.set + set: function set(key, value) { + return define(this, key, value); } - // Set @@toStringTag to native iterators - setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); - if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; - } - } - - // fix Array.prototype.{ values, @@iterator }.name in V8 / FF - if (PROPER_FUNCTION_NAME && DEFAULT === VALUES && nativeIterator && nativeIterator.name !== VALUES) { - if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) { - createNonEnumerableProperty(IterablePrototype, 'name', VALUES); - } else { - INCORRECT_VALUES_NAME = true; - defaultIterator = function values() { return call(nativeIterator, this); }; - } - } - - // export additional methods - if (DEFAULT) { - methods = { - values: getIterationMethod(VALUES), - keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), - entries: getIterationMethod(ENTRIES) - }; - if (FORCED) for (KEY in methods) { - if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { - defineBuiltIn(IterablePrototype, KEY, methods[KEY]); + } : { + // `WeakSet.prototype.add(value)` method + // https://tc39.es/ecma262/#sec-weakset.prototype.add + add: function add(value) { + return define(this, value, true); } - } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); - } + }); - // define iterator - if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { - defineBuiltIn(IterablePrototype, ITERATOR, defaultIterator, { name: DEFAULT }); + return Constructor; } - Iterators[NAME] = defaultIterator; - - return methods; }; /***/ }), -/* 191 */ +/* 197 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var isCallable = __webpack_require__(46); -var hasOwn = __webpack_require__(45); -var DESCRIPTORS = __webpack_require__(38); -var CONFIGURABLE_FUNCTION_NAME = __webpack_require__(113).CONFIGURABLE; -var inspectSource = __webpack_require__(186); -var InternalStateModule = __webpack_require__(53); - -var enforceInternalState = InternalStateModule.enforce; -var getInternalState = InternalStateModule.get; -var $String = String; -// eslint-disable-next-line es/no-object-defineproperty -- safe -var defineProperty = Object.defineProperty; -var stringSlice = uncurryThis(''.slice); -var replace = uncurryThis(''.replace); -var join = uncurryThis([].join); - -var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () { - return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8; -}); +var globalThis = __webpack_require__(3); +var getBuiltInNodeModule = __webpack_require__(208); +var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(175); -var TEMPLATE = String(String).split('String'); +var structuredClone = globalThis.structuredClone; +var $ArrayBuffer = globalThis.ArrayBuffer; +var $MessageChannel = globalThis.MessageChannel; +var detach = false; +var WorkerThreads, channel, buffer, $detach; -var makeBuiltIn = module.exports = function (value, name, options) { - if (stringSlice($String(name), 0, 7) === 'Symbol(') { - name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']'; - } - if (options && options.getter) name = 'get ' + name; - if (options && options.setter) name = 'set ' + name; - if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) { - if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true }); - else value.name = name; - } - if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) { - defineProperty(value, 'length', { value: options.arity }); +if (PROPER_STRUCTURED_CLONE_TRANSFER) { + detach = function (transferable) { + structuredClone(transferable, { transfer: [transferable] }); + }; +} else if ($ArrayBuffer) try { + if (!$MessageChannel) { + WorkerThreads = getBuiltInNodeModule('worker_threads'); + if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel; } - try { - if (options && hasOwn(options, 'constructor') && options.constructor) { - if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false }); - // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable - } else if (value.prototype) value.prototype = undefined; - } catch (error) { /* empty */ } - var state = enforceInternalState(value); - if (!hasOwn(state, 'source')) { - state.source = join(TEMPLATE, typeof name == 'string' ? name : ''); - } return value; -}; - -// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative -// eslint-disable-next-line no-extend-native -- required -Function.prototype.toString = makeBuiltIn(function toString() { - return isCallable(this) && getInternalState(this).source || inspectSource(this); -}, 'toString'); + if ($MessageChannel) { + channel = new $MessageChannel(); + buffer = new $ArrayBuffer(2); -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { + $detach = function (transferable) { + channel.port1.postMessage(null, [transferable]); + }; -"use strict"; + if (buffer.byteLength === 2) { + $detach(buffer); + if (buffer.byteLength === 0) detach = $detach; + } + } +} catch (error) { /* empty */ } -// `Math.sign` method implementation -// https://tc39.es/ecma262/#sec-math.sign -// eslint-disable-next-line es/no-math-sign -- safe -module.exports = Math.sign || function sign(x) { - var n = +x; - // eslint-disable-next-line no-self-compare -- NaN check - return n === 0 || n !== n ? n : n < 0 ? -1 : 1; -}; +module.exports = detach; /***/ }), -/* 193 */ +/* 198 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isRegExp = __webpack_require__(152); - -var $TypeError = TypeError; - -module.exports = function (it) { - if (isRegExp(it)) { - throw new $TypeError("The method doesn't accept regular expressions"); - } return it; +module.exports = { + IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 }, + DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 }, + HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 }, + WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 }, + InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 }, + NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 }, + NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 }, + NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 }, + NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 }, + InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 }, + InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 }, + SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 }, + InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 }, + NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 }, + InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 }, + ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 }, + TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 }, + SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 }, + NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 }, + AbortError: { s: 'ABORT_ERR', c: 20, m: 1 }, + URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 }, + QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 }, + TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 }, + InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 }, + DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 } }; /***/ }), -/* 194 */ +/* 199 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(279); -var definePropertyModule = __webpack_require__(51); -var anObject = __webpack_require__(37); -var toIndexedObject = __webpack_require__(57); -var objectKeys = __webpack_require__(134); - -// `Object.defineProperties` method -// https://tc39.es/ecma262/#sec-object.defineproperties -// eslint-disable-next-line es/no-object-defineproperties -- safe -exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var props = toIndexedObject(Properties); - var keys = objectKeys(Properties); - var length = keys.length; - var index = 0; - var key; - while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]); - return O; +// iterable DOM collections +// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods +module.exports = { + CSSRuleList: 0, + CSSStyleDeclaration: 0, + CSSValueList: 0, + ClientRectList: 0, + DOMRectList: 0, + DOMStringList: 0, + DOMTokenList: 1, + DataTransferItemList: 0, + FileList: 0, + HTMLAllCollection: 0, + HTMLCollection: 0, + HTMLFormElement: 0, + HTMLSelectElement: 0, + MediaList: 0, + MimeTypeArray: 0, + NamedNodeMap: 0, + NodeList: 1, + PaintRequestList: 0, + Plugin: 0, + PluginArray: 0, + SVGLengthList: 0, + SVGNumberList: 0, + SVGPathSegList: 0, + SVGPointList: 0, + SVGStringList: 0, + SVGTransformList: 0, + SourceBufferList: 0, + StyleSheetList: 0, + TextTrackCueList: 0, + TextTrackList: 0, + TouchList: 0 }; /***/ }), -/* 195 */ +/* 200 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable es/no-object-getownpropertynames -- safe */ -var classof = __webpack_require__(64); -var toIndexedObject = __webpack_require__(57); -var $getOwnPropertyNames = __webpack_require__(106).f; -var arraySlice = __webpack_require__(78); - -var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - -var getWindowNames = function (it) { - try { - return $getOwnPropertyNames(it); - } catch (error) { - return arraySlice(windowNames); - } -}; +// in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList` +var documentCreateElement = __webpack_require__(118); -// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window -module.exports.f = function getOwnPropertyNames(it) { - return windowNames && classof(it) === 'Window' - ? getWindowNames(it) - : $getOwnPropertyNames(toIndexedObject(it)); -}; +var classList = documentCreateElement('span').classList; +var DOMTokenListPrototype = classList && classList.constructor && classList.constructor.prototype; + +module.exports = DOMTokenListPrototype === Object.prototype ? undefined : DOMTokenListPrototype; /***/ }), -/* 196 */ +/* 201 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var isObject = __webpack_require__(40); -var classof = __webpack_require__(64); -var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(174); +var userAgent = __webpack_require__(51); -// eslint-disable-next-line es/no-object-isextensible -- safe -var $isExtensible = Object.isExtensible; -var FAILS_ON_PRIMITIVES = fails(function () { $isExtensible(1); }); +var firefox = userAgent.match(/firefox\/(\d+)/i); -// `Object.isExtensible` method -// https://tc39.es/ecma262/#sec-object.isextensible -module.exports = (FAILS_ON_PRIMITIVES || ARRAY_BUFFER_NON_EXTENSIBLE) ? function isExtensible(it) { - if (!isObject(it)) return false; - if (ARRAY_BUFFER_NON_EXTENSIBLE && classof(it) === 'ArrayBuffer') return false; - return $isExtensible ? $isExtensible(it) : true; -} : $isExtensible; +module.exports = !!firefox && +firefox[1]; /***/ }), -/* 197 */ +/* 202 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); -var uncurryThis = __webpack_require__(34); -var getOwnPropertyNamesModule = __webpack_require__(106); -var getOwnPropertySymbolsModule = __webpack_require__(155); -var anObject = __webpack_require__(37); +var UA = __webpack_require__(51); -var concat = uncurryThis([].concat); +module.exports = /MSIE|Trident/.test(UA); -// all object keys, includes non-enumerable and symbols -module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { - var keys = getOwnPropertyNamesModule.f(anObject(it)); - var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; - return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys; -}; + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var userAgent = __webpack_require__(51); + +// eslint-disable-next-line redos/no-vulnerable -- safe +module.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent); /***/ }), -/* 198 */ +/* 204 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */ -/* eslint-disable regexp/no-useless-quantifier -- testing */ -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); -var regexpFlags = __webpack_require__(199); -var stickyHelpers = __webpack_require__(160); -var shared = __webpack_require__(123); -var create = __webpack_require__(62); -var getInternalState = __webpack_require__(53).get; -var UNSUPPORTED_DOT_ALL = __webpack_require__(200); -var UNSUPPORTED_NCG = __webpack_require__(267); +var fails = __webpack_require__(1); +var createPropertyDescriptor = __webpack_require__(41); -var nativeReplace = shared('native-string-replace', String.prototype.replace); -var nativeExec = RegExp.prototype.exec; -var patchedExec = nativeExec; -var charAt = uncurryThis(''.charAt); -var indexOf = uncurryThis(''.indexOf); -var replace = uncurryThis(''.replace); -var stringSlice = uncurryThis(''.slice); +module.exports = !fails(function () { + var error = new Error('a'); + if (!('stack' in error)) return true; + // eslint-disable-next-line es/no-object-defineproperty -- safe + Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7)); + return error.stack !== 7; +}); -var UPDATES_LAST_INDEX_WRONG = (function () { - var re1 = /a/; - var re2 = /b*/g; - call(nativeExec, re1, 'a'); - call(nativeExec, re2, 'a'); - return re1.lastIndex !== 0 || re2.lastIndex !== 0; -})(); -var UNSUPPORTED_Y = stickyHelpers.BROKEN_CARET; +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { -// nonparticipating capturing group, copied from es5-shim's String#split patch. -var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; +"use strict"; -var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG; +var DESCRIPTORS = __webpack_require__(6); +var fails = __webpack_require__(1); +var anObject = __webpack_require__(5); +var normalizeStringArgument = __webpack_require__(87); -if (PATCH) { - patchedExec = function exec(string) { - var re = this; - var state = getInternalState(re); - var str = toString(string); - var raw = state.raw; - var result, reCopy, lastIndex, match, i, object, group; +var nativeErrorToString = Error.prototype.toString; - if (raw) { - raw.lastIndex = re.lastIndex; - result = call(patchedExec, raw, str); - re.lastIndex = raw.lastIndex; - return result; - } +var INCORRECT_TO_STRING = fails(function () { + if (DESCRIPTORS) { + // Chrome 32- incorrectly call accessor + // eslint-disable-next-line es/no-object-create, es/no-object-defineproperty -- safe + var object = Object.create(Object.defineProperty({}, 'name', { get: function () { + return this === object; + } })); + if (nativeErrorToString.call(object) !== 'true') return true; + } + // FF10- does not properly handle non-strings + return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1' + // IE8 does not properly handle defaults + || nativeErrorToString.call({}) !== 'Error'; +}); - var groups = state.groups; - var sticky = UNSUPPORTED_Y && re.sticky; - var flags = call(regexpFlags, re); - var source = re.source; - var charsAdded = 0; - var strCopy = str; +module.exports = INCORRECT_TO_STRING ? function toString() { + var O = anObject(this); + var name = normalizeStringArgument(O.name, 'Error'); + var message = normalizeStringArgument(O.message); + return !name ? message : !message ? name : name + ': ' + message; +} : nativeErrorToString; - if (sticky) { - flags = replace(flags, 'y', ''); - if (indexOf(flags, 'g') === -1) { - flags += 'g'; - } - strCopy = stringSlice(str, re.lastIndex); - // Support anchored sticky behavior. - if (re.lastIndex > 0 && (!re.multiline || re.multiline && charAt(str, re.lastIndex - 1) !== '\n')) { - source = '(?: ' + source + ')'; - strCopy = ' ' + strCopy; - charsAdded++; - } - // ^(? + rx + ) is needed, in combination with some str slicing, to - // simulate the 'y' flag. - reCopy = new RegExp('^(?:' + source + ')', flags); - } +/***/ }), +/* 206 */ +/***/ (function(module, exports, __webpack_require__) { - if (NPCG_INCLUDED) { - reCopy = new RegExp('^' + source + '$(?!\\s)', flags); - } - if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; +"use strict"; - match = call(nativeExec, sticky ? reCopy : re, strCopy); +var isArray = __webpack_require__(62); +var lengthOfArrayLike = __webpack_require__(18); +var doesNotExceedSafeInteger = __webpack_require__(66); +var bind = __webpack_require__(43); - if (sticky) { - if (match) { - match.input = stringSlice(match.input, charsAdded); - match[0] = stringSlice(match[0], charsAdded); - match.index = re.lastIndex; - re.lastIndex += match[0].length; - } else re.lastIndex = 0; - } else if (UPDATES_LAST_INDEX_WRONG && match) { - re.lastIndex = re.global ? match.index + match[0].length : lastIndex; - } - if (NPCG_INCLUDED && match && match.length > 1) { - // Fix browsers whose `exec` methods don't consistently return `undefined` - // for NPCG, like IE8. NOTE: This doesn't work for /(.?)?/ - call(nativeReplace, match[0], reCopy, function () { - for (i = 1; i < arguments.length - 2; i++) { - if (arguments[i] === undefined) match[i] = undefined; - } - }); - } +// `FlattenIntoArray` abstract operation +// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray +var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? bind(mapper, thisArg) : false; + var element, elementLen; - if (match && groups) { - match.groups = object = create(null); - for (i = 0; i < groups.length; i++) { - group = groups[i]; - object[group[0]] = match[group[1]]; + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + if (depth > 0 && isArray(element)) { + elementLen = lengthOfArrayLike(element); + targetIndex = flattenIntoArray(target, original, element, elementLen, targetIndex, depth - 1) - 1; + } else { + doesNotExceedSafeInteger(targetIndex + 1); + target[targetIndex] = element; } - } - return match; - }; -} + targetIndex++; + } + sourceIndex++; + } + return targetIndex; +}; -module.exports = patchedExec; +module.exports = flattenIntoArray; /***/ }), -/* 199 */ +/* 207 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var anObject = __webpack_require__(37); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var isObject = __webpack_require__(8); +var hasOwn = __webpack_require__(13); +var arraySlice = __webpack_require__(46); +var NATIVE_BIND = __webpack_require__(99); -// `RegExp.prototype.flags` getter implementation -// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags -module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.hasIndices) result += 'd'; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.dotAll) result += 's'; - if (that.unicode) result += 'u'; - if (that.unicodeSets) result += 'v'; - if (that.sticky) result += 'y'; - return result; +var $Function = Function; +var concat = uncurryThis([].concat); +var join = uncurryThis([].join); +var factories = {}; + +var construct = function (C, argsLength, args) { + if (!hasOwn(factories, argsLength)) { + var list = []; + var i = 0; + for (; i < argsLength; i++) list[i] = 'a[' + i + ']'; + factories[argsLength] = $Function('C,a', 'return new C(' + join(list, ',') + ')'); + } return factories[argsLength](C, args); +}; + +// `Function.prototype.bind` method implementation +// https://tc39.es/ecma262/#sec-function.prototype.bind +// eslint-disable-next-line es/no-function-prototype-bind -- detection +module.exports = NATIVE_BIND ? $Function.bind : function bind(that /* , ...args */) { + var F = aCallable(this); + var Prototype = F.prototype; + var partArgs = arraySlice(arguments, 1); + var boundFunction = function bound(/* args... */) { + var args = concat(partArgs, arraySlice(arguments)); + return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args); + }; + if (isObject(Prototype)) boundFunction.prototype = Prototype; + return boundFunction; }; /***/ }), -/* 200 */ +/* 208 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var globalThis = __webpack_require__(35); +var globalThis = __webpack_require__(3); +var IS_NODE = __webpack_require__(80); -// babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError -var $RegExp = globalThis.RegExp; - -module.exports = fails(function () { - var re = $RegExp('.', 's'); - return !(re.dotAll && re.test('\n') && re.flags === 's'); -}); +module.exports = function (name) { + if (IS_NODE) { + try { + return globalThis.process.getBuiltinModule(name); + } catch (error) { /* empty */ } + try { + // eslint-disable-next-line no-new-func -- safe + return Function('return require("' + name + '")')(); + } catch (error) { /* empty */ } + } +}; /***/ }), -/* 201 */ +/* 209 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var apply = __webpack_require__(74); -var isCallable = __webpack_require__(46); -var ENVIRONMENT = __webpack_require__(149); -var USER_AGENT = __webpack_require__(83); -var arraySlice = __webpack_require__(78); -var validateArgumentsLength = __webpack_require__(80); - -var Function = globalThis.Function; -// dirty IE9- and Bun 0.3.0- checks -var WRAP = /MSIE .\./.test(USER_AGENT) || ENVIRONMENT === 'BUN' && (function () { - var version = globalThis.Bun.version.split('.'); - return version.length < 3 || version[0] === '0' && (version[1] < 3 || version[1] === '3' && version[2] === '0'); -})(); +var globalThis = __webpack_require__(3); -// IE9- / Bun 0.3.0- setTimeout / setInterval / setImmediate additional parameters fix -// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers -// https://github.com/oven-sh/bun/issues/1633 -module.exports = function (scheduler, hasTimeArg) { - var firstParamIndex = hasTimeArg ? 2 : 1; - return WRAP ? function (handler, timeout /* , ...arguments */) { - var boundArgs = validateArgumentsLength(arguments.length, 1) > firstParamIndex; - var fn = isCallable(handler) ? handler : Function(handler); - var params = boundArgs ? arraySlice(arguments, firstParamIndex) : []; - var callback = boundArgs ? function () { - apply(fn, this, params); - } : fn; - return hasTimeArg ? scheduler(callback, timeout) : scheduler(callback); - } : scheduler; +module.exports = function (CONSTRUCTOR, METHOD) { + var Constructor = globalThis[CONSTRUCTOR]; + var Prototype = Constructor && Constructor.prototype; + return Prototype && Prototype[METHOD]; }; /***/ }), -/* 202 */ +/* 210 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var SetHelpers = __webpack_require__(82); -var iterate = __webpack_require__(121); - -var Set = SetHelpers.Set; -var add = SetHelpers.add; +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var getIteratorMethod = __webpack_require__(68); -module.exports = function (set) { - var result = new Set(); - iterate(set, function (it) { - add(result, it); - }); - return result; +module.exports = function (obj, stringHandling) { + if (!stringHandling || typeof obj !== 'string') anObject(obj); + var method = getIteratorMethod(obj); + return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj)); }; /***/ }), -/* 203 */ +/* 211 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var PROPER_FUNCTION_NAME = __webpack_require__(113).PROPER; -var fails = __webpack_require__(33); -var whitespaces = __webpack_require__(138); +var uncurryThis = __webpack_require__(2); +var toObject = __webpack_require__(15); -var non = '\u200B\u0085\u180E'; +var floor = Math.floor; +var charAt = uncurryThis(''.charAt); +var replace = uncurryThis(''.replace); +var stringSlice = uncurryThis(''.slice); +// eslint-disable-next-line redos/no-vulnerable -- safe +var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g; +var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g; -// check that a method works with the correct list -// of whitespaces and has a correct name -module.exports = function (METHOD_NAME) { - return fails(function () { - return !!whitespaces[METHOD_NAME]() - || non[METHOD_NAME]() !== non - || (PROPER_FUNCTION_NAME && whitespaces[METHOD_NAME].name !== METHOD_NAME); +// `GetSubstitution` abstract operation +// https://tc39.es/ecma262/#sec-getsubstitution +module.exports = function (matched, str, position, captures, namedCaptures, replacement) { + var tailPos = position + matched.length; + var m = captures.length; + var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; + if (namedCaptures !== undefined) { + namedCaptures = toObject(namedCaptures); + symbols = SUBSTITUTION_SYMBOLS; + } + return replace(replacement, symbols, function (match, ch) { + var capture; + switch (charAt(ch, 0)) { + case '$': return '$'; + case '&': return matched; + case '`': return stringSlice(str, 0, position); + case "'": return stringSlice(str, tailPos); + case '<': + capture = namedCaptures[stringSlice(ch, 1, -1)]; + break; + default: // \d\d? + var n = +ch; + if (n === 0) return match; + if (n > m) { + var f = floor(n / 10); + if (f === 0) return match; + if (f <= m) return captures[f - 1] === undefined ? charAt(ch, 1) : captures[f - 1] + charAt(ch, 1); + return match; + } + capture = captures[n - 1]; + } + return capture === undefined ? '' : capture; }); }; /***/ }), -/* 204 */ +/* 212 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var V8 = __webpack_require__(84); -var ENVIRONMENT = __webpack_require__(149); - -var structuredClone = globalThis.structuredClone; +var getBuiltIn = __webpack_require__(11); -module.exports = !!structuredClone && !fails(function () { - // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation - // https://github.com/zloirock/core-js/issues/679 - if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false; - var buffer = new ArrayBuffer(8); - var clone = structuredClone(buffer, { transfer: [buffer] }); - return buffer.byteLength !== 0 || clone.byteLength !== 8; -}); +module.exports = getBuiltIn('document', 'documentElement'); /***/ }), -/* 205 */ +/* 213 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toPrimitive = __webpack_require__(170); +var DESCRIPTORS = __webpack_require__(6); +var fails = __webpack_require__(1); +var createElement = __webpack_require__(118); -var $TypeError = TypeError; - -// `ToBigInt` abstract operation -// https://tc39.es/ecma262/#sec-tobigint -module.exports = function (argument) { - var prim = toPrimitive(argument, 'number'); - if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint"); - // eslint-disable-next-line es/no-bigint -- safe - return BigInt(prim); -}; +// Thanks to IE8 for its funny defineProperty +module.exports = !DESCRIPTORS && !fails(function () { + // eslint-disable-next-line es/no-object-defineproperty -- required for testing + return Object.defineProperty(createElement('div'), 'a', { + get: function () { return 7; } + }).a !== 7; +}); /***/ }), -/* 206 */ +/* 214 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toIntegerOrInfinity = __webpack_require__(54); - -var $RangeError = RangeError; +var isObject = __webpack_require__(8); +var createNonEnumerableProperty = __webpack_require__(27); -module.exports = function (it) { - var result = toIntegerOrInfinity(it); - if (result < 0) throw new $RangeError("The argument can't be less than 0"); - return result; +// `InstallErrorCause` abstract operation +// https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause +module.exports = function (O, options) { + if (isObject(options) && 'cause' in options) { + createNonEnumerableProperty(O, 'cause', options.cause); + } }; /***/ }), -/* 207 */ +/* 215 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var wellKnownSymbol = __webpack_require__(39); - -var TO_STRING_TAG = wellKnownSymbol('toStringTag'); -var test = {}; - -test[TO_STRING_TAG] = 'z'; +var classof = __webpack_require__(47); -module.exports = String(test) === '[object z]'; +module.exports = function (it) { + var klass = classof(it); + return klass === 'BigInt64Array' || klass === 'BigUint64Array'; +}; /***/ }), -/* 208 */ +/* 216 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable no-new, sonarjs/inconsistent-function-call -- required for testing */ -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var checkCorrectnessOfIteration = __webpack_require__(145); -var NATIVE_ARRAY_BUFFER_VIEWS = __webpack_require__(44).NATIVE_ARRAY_BUFFER_VIEWS; - -var ArrayBuffer = globalThis.ArrayBuffer; -var Int8Array = globalThis.Int8Array; +var hasOwn = __webpack_require__(13); -module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () { - Int8Array(1); -}) || !fails(function () { - new Int8Array(-1); -}) || !checkCorrectnessOfIteration(function (iterable) { - new Int8Array(); - new Int8Array(null); - new Int8Array(1.5); - new Int8Array(iterable); -}, true) || fails(function () { - // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill - return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1; -}); +module.exports = function (descriptor) { + return descriptor !== undefined && (hasOwn(descriptor, 'value') || hasOwn(descriptor, 'writable')); +}; /***/ }), -/* 209 */ +/* 217 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var exec = __webpack_require__(198); +var isObject = __webpack_require__(8); -// `RegExp.prototype.exec` method -// https://tc39.es/ecma262/#sec-regexp.prototype.exec -$({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, { - exec: exec -}); +module.exports = function (argument) { + return isObject(argument) || argument === null; +}; /***/ }), -/* 210 */ +/* 218 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isPossiblePrototype = __webpack_require__(246); +var uncurryThis = __webpack_require__(2); -var $String = String; -var $TypeError = TypeError; +// eslint-disable-next-line es/no-map -- safe +var MapPrototype = Map.prototype; -module.exports = function (argument) { - if (isPossiblePrototype(argument)) return argument; - throw new $TypeError("Can't set " + $String(argument) + ' as a prototype'); +module.exports = { + // eslint-disable-next-line es/no-map -- safe + Map: Map, + set: uncurryThis(MapPrototype.set), + get: uncurryThis(MapPrototype.get), + has: uncurryThis(MapPrototype.has), + remove: uncurryThis(MapPrototype['delete']), + proto: MapPrototype }; /***/ }), -/* 211 */ +/* 219 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var bind = __webpack_require__(75); -var anObject = __webpack_require__(37); -var aCallable = __webpack_require__(42); -var isNullOrUndefined = __webpack_require__(89); -var getMethod = __webpack_require__(60); -var wellKnownSymbol = __webpack_require__(39); +var sign = __webpack_require__(163); +var roundTiesToEven = __webpack_require__(224); -var ASYNC_DISPOSE = wellKnownSymbol('asyncDispose'); -var DISPOSE = wellKnownSymbol('dispose'); +var abs = Math.abs; -var push = uncurryThis([].push); +var EPSILON = 2.220446049250313e-16; // Number.EPSILON -// `GetDisposeMethod` abstract operation -// https://tc39.es/proposal-explicit-resource-management/#sec-getdisposemethod -var getDisposeMethod = function (V, hint) { - if (hint === 'async-dispose') { - var method = getMethod(V, ASYNC_DISPOSE); - if (method !== undefined) return method; - method = getMethod(V, DISPOSE); - if (method === undefined) return method; - return function () { - var O = this; - var Promise = getBuiltIn('Promise'); - return new Promise(function (resolve) { - call(method, O); - resolve(undefined); - }); - }; - } return getMethod(V, DISPOSE); +module.exports = function (x, FLOAT_EPSILON, FLOAT_MAX_VALUE, FLOAT_MIN_VALUE) { + var n = +x; + var absolute = abs(n); + var s = sign(n); + if (absolute < FLOAT_MIN_VALUE) return s * roundTiesToEven(absolute / FLOAT_MIN_VALUE / FLOAT_EPSILON) * FLOAT_MIN_VALUE * FLOAT_EPSILON; + var a = (1 + FLOAT_EPSILON / EPSILON) * absolute; + var result = a - (a - absolute); + // eslint-disable-next-line no-self-compare -- NaN check + if (result > FLOAT_MAX_VALUE || result !== result) return s * Infinity; + return s * result; }; -// `CreateDisposableResource` abstract operation -// https://tc39.es/proposal-explicit-resource-management/#sec-createdisposableresource -var createDisposableResource = function (V, hint, method) { - if (arguments.length < 3 && !isNullOrUndefined(V)) { - method = aCallable(getDisposeMethod(anObject(V), hint)); - } - return method === undefined ? function () { - return undefined; - } : bind(method, V); -}; +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { -// `AddDisposableResource` abstract operation -// https://tc39.es/proposal-explicit-resource-management/#sec-adddisposableresource -module.exports = function (disposable, V, hint, method) { - var resource; - if (arguments.length < 4) { - // When `V`` is either `null` or `undefined` and hint is `async-dispose`, - // we record that the resource was evaluated to ensure we will still perform an `Await` when resources are later disposed. - if (isNullOrUndefined(V) && hint === 'sync-dispose') return; - resource = createDisposableResource(V, hint); - } else { - resource = createDisposableResource(undefined, hint, method); - } +"use strict"; + +var floatRound = __webpack_require__(219); + +var FLOAT32_EPSILON = 1.1920928955078125e-7; // 2 ** -23; +var FLOAT32_MAX_VALUE = 3.4028234663852886e+38; // 2 ** 128 - 2 ** 104 +var FLOAT32_MIN_VALUE = 1.1754943508222875e-38; // 2 ** -126; - push(disposable.stack, resource); +// `Math.fround` method implementation +// https://tc39.es/ecma262/#sec-math.fround +// eslint-disable-next-line es/no-math-fround -- safe +module.exports = Math.fround || function fround(x) { + return floatRound(x, FLOAT32_EPSILON, FLOAT32_MAX_VALUE, FLOAT32_MIN_VALUE); }; /***/ }), -/* 212 */ +/* 221 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var uncurryThisAccessor = __webpack_require__(151); -var classof = __webpack_require__(64); - -var ArrayBuffer = globalThis.ArrayBuffer; -var TypeError = globalThis.TypeError; +var log = Math.log; +var LOG10E = Math.LOG10E; -// Includes -// - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). -// - If IsSharedArrayBuffer(O) is true, throw a TypeError exception. -module.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) { - if (classof(O) !== 'ArrayBuffer') throw new TypeError('ArrayBuffer expected'); - return O.byteLength; +// eslint-disable-next-line es/no-math-log10 -- safe +module.exports = Math.log10 || function log10(x) { + return log(x) * LOG10E; }; /***/ }), -/* 213 */ +/* 222 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var NATIVE_ARRAY_BUFFER = __webpack_require__(140); -var arrayBufferByteLength = __webpack_require__(212); - -var DataView = globalThis.DataView; +var log = Math.log; -module.exports = function (O) { - if (!NATIVE_ARRAY_BUFFER || arrayBufferByteLength(O) !== 0) return false; - try { - // eslint-disable-next-line no-new -- thrower - new DataView(O); - return false; - } catch (error) { - return true; - } +// `Math.log1p` method implementation +// https://tc39.es/ecma262/#sec-math.log1p +// eslint-disable-next-line es/no-math-log1p -- safe +module.exports = Math.log1p || function log1p(x) { + var n = +x; + return n > -1e-8 && n < 1e-8 ? n - n * n / 2 : log(1 + n); }; /***/ }), -/* 214 */ +/* 223 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var uncurryThisAccessor = __webpack_require__(151); -var toIndex = __webpack_require__(169); -var notDetached = __webpack_require__(289); -var arrayBufferByteLength = __webpack_require__(212); -var detachTransferable = __webpack_require__(226); -var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(204); - -var structuredClone = globalThis.structuredClone; -var ArrayBuffer = globalThis.ArrayBuffer; -var DataView = globalThis.DataView; -var min = Math.min; -var ArrayBufferPrototype = ArrayBuffer.prototype; -var DataViewPrototype = DataView.prototype; -var slice = uncurryThis(ArrayBufferPrototype.slice); -var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get'); -var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get'); -var getInt8 = uncurryThis(DataViewPrototype.getInt8); -var setInt8 = uncurryThis(DataViewPrototype.setInt8); +var log = Math.log; +var LN2 = Math.LN2; -module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) { - var byteLength = arrayBufferByteLength(arrayBuffer); - var newByteLength = newLength === undefined ? byteLength : toIndex(newLength); - var fixedLength = !isResizable || !isResizable(arrayBuffer); - var newBuffer; - notDetached(arrayBuffer); - if (PROPER_STRUCTURED_CLONE_TRANSFER) { - arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] }); - if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer; - } - if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) { - newBuffer = slice(arrayBuffer, 0, newByteLength); - } else { - var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined; - newBuffer = new ArrayBuffer(newByteLength, options); - var a = new DataView(arrayBuffer); - var b = new DataView(newBuffer); - var copyLength = min(newByteLength, byteLength); - for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i)); - } - if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer); - return newBuffer; +// `Math.log2` method +// https://tc39.es/ecma262/#sec-math.log2 +// eslint-disable-next-line es/no-math-log2 -- safe +module.exports = Math.log2 || function log2(x) { + return log(x) / LN2; }; /***/ }), -/* 215 */ +/* 224 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toObject = __webpack_require__(47); -var toAbsoluteIndex = __webpack_require__(91); -var lengthOfArrayLike = __webpack_require__(50); -var deletePropertyOrThrow = __webpack_require__(147); - -var min = Math.min; +var EPSILON = 2.220446049250313e-16; // Number.EPSILON +var INVERSE_EPSILON = 1 / EPSILON; -// `Array.prototype.copyWithin` method implementation -// https://tc39.es/ecma262/#sec-array.prototype.copywithin -// eslint-disable-next-line es/no-array-prototype-copywithin -- safe -module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = lengthOfArrayLike(O); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else deletePropertyOrThrow(O, to); - to += inc; - from += inc; - } return O; +module.exports = function (n) { + return n + INVERSE_EPSILON - INVERSE_EPSILON; }; /***/ }), -/* 216 */ +/* 225 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $forEach = __webpack_require__(58).forEach; -var arrayMethodIsStrict = __webpack_require__(86); - -var STRICT_METHOD = arrayMethodIsStrict('forEach'); +var ceil = Math.ceil; +var floor = Math.floor; -// `Array.prototype.forEach` method implementation -// https://tc39.es/ecma262/#sec-array.prototype.foreach -module.exports = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); -// eslint-disable-next-line es/no-array-prototype-foreach -- safe -} : [].forEach; +// `Math.trunc` method +// https://tc39.es/ecma262/#sec-math.trunc +// eslint-disable-next-line es/no-math-trunc -- safe +module.exports = Math.trunc || function trunc(x) { + var n = +x; + return (n > 0 ? floor : ceil)(n); +}; /***/ }), -/* 217 */ +/* 226 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var bind = __webpack_require__(75); -var call = __webpack_require__(36); -var toObject = __webpack_require__(47); -var callWithSafeIterationClosing = __webpack_require__(178); -var isArrayIteratorMethod = __webpack_require__(187); -var isConstructor = __webpack_require__(103); -var lengthOfArrayLike = __webpack_require__(50); -var createProperty = __webpack_require__(87); -var getIterator = __webpack_require__(114); -var getIteratorMethod = __webpack_require__(99); +var globalThis = __webpack_require__(3); +var safeGetBuiltIn = __webpack_require__(239); +var bind = __webpack_require__(43); +var macrotask = __webpack_require__(137).set; +var Queue = __webpack_require__(236); +var IS_IOS = __webpack_require__(203); +var IS_IOS_PEBBLE = __webpack_require__(291); +var IS_WEBOS_WEBKIT = __webpack_require__(292); +var IS_NODE = __webpack_require__(80); -var $Array = Array; +var MutationObserver = globalThis.MutationObserver || globalThis.WebKitMutationObserver; +var document = globalThis.document; +var process = globalThis.process; +var Promise = globalThis.Promise; +var microtask = safeGetBuiltIn('queueMicrotask'); +var notify, toggle, node, promise, then; -// `Array.from` method implementation -// https://tc39.es/ecma262/#sec-array.from -module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var IS_CONSTRUCTOR = isConstructor(this); - var argumentsLength = arguments.length; - var mapfn = argumentsLength > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined); - var iteratorMethod = getIteratorMethod(O); - var index = 0; - var length, result, step, iterator, next, value; - // if the target is not iterable or it's an array with the default iterator - use a simple case - if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) { - result = IS_CONSTRUCTOR ? new this() : []; - iterator = getIterator(O, iteratorMethod); - next = iterator.next; - for (;!(step = call(next, iterator)).done; index++) { - value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; - createProperty(result, index, value); +// modern engines have queueMicrotask method +if (!microtask) { + var queue = new Queue(); + + var flush = function () { + var parent, fn; + if (IS_NODE && (parent = process.domain)) parent.exit(); + while (fn = queue.get()) try { + fn(); + } catch (error) { + if (queue.head) notify(); + throw error; } + if (parent) parent.enter(); + }; + + // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 + // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898 + if (!IS_IOS && !IS_NODE && !IS_WEBOS_WEBKIT && MutationObserver && document) { + toggle = true; + node = document.createTextNode(''); + new MutationObserver(flush).observe(node, { characterData: true }); + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (!IS_IOS_PEBBLE && Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + promise = Promise.resolve(undefined); + // workaround of WebKit ~ iOS Safari 10.1 bug + promise.constructor = Promise; + then = bind(promise.then, promise); + notify = function () { + then(flush); + }; + // Node.js without promises + } else if (IS_NODE) { + notify = function () { + process.nextTick(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessage + // - onreadystatechange + // - setTimeout } else { - length = lengthOfArrayLike(O); - result = IS_CONSTRUCTOR ? new this(length) : $Array(length); - for (;length > index; index++) { - value = mapping ? mapfn(O[index], index) : O[index]; - createProperty(result, index, value); - } + // `webpack` dev server bug on IE global methods - use bind(fn, global) + macrotask = bind(macrotask, globalThis); + notify = function () { + macrotask(flush); + }; } - result.length = index; - return result; -}; + + microtask = function (fn) { + if (!queue.head) notify(); + queue.add(fn); + }; +} + +module.exports = microtask; /***/ }), -/* 218 */ +/* 227 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable es/no-array-prototype-lastindexof -- safe */ -var apply = __webpack_require__(74); -var toIndexedObject = __webpack_require__(57); -var toIntegerOrInfinity = __webpack_require__(54); -var lengthOfArrayLike = __webpack_require__(50); -var arrayMethodIsStrict = __webpack_require__(86); - -var min = Math.min; -var $lastIndexOf = [].lastIndexOf; -var NEGATIVE_ZERO = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0; -var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); -var FORCED = NEGATIVE_ZERO || !STRICT_METHOD; +var $RangeError = RangeError; -// `Array.prototype.lastIndexOf` method implementation -// https://tc39.es/ecma262/#sec-array.prototype.lastindexof -module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return apply($lastIndexOf, this, arguments) || 0; - var O = toIndexedObject(this); - var length = lengthOfArrayLike(O); - if (length === 0) return -1; - var index = length - 1; - if (arguments.length > 1) index = min(index, toIntegerOrInfinity(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; - return -1; -} : $lastIndexOf; +module.exports = function (it) { + // eslint-disable-next-line no-self-compare -- NaN check + if (it === it) return it; + throw new $RangeError('NaN is not allowed'); +}; /***/ }), -/* 219 */ +/* 228 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var lengthOfArrayLike = __webpack_require__(50); +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); +var trim = __webpack_require__(93).trim; +var whitespaces = __webpack_require__(107); -// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed -// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed -module.exports = function (O, C) { - var len = lengthOfArrayLike(O); - var A = new C(len); - var k = 0; - for (; k < len; k++) A[k] = O[len - k - 1]; - return A; -}; +var charAt = uncurryThis(''.charAt); +var $parseFloat = globalThis.parseFloat; +var Symbol = globalThis.Symbol; +var ITERATOR = Symbol && Symbol.iterator; +var FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity + // MS Edge 18- broken with boxed symbols + || (ITERATOR && !fails(function () { $parseFloat(Object(ITERATOR)); })); + +// `parseFloat` method +// https://tc39.es/ecma262/#sec-parsefloat-string +module.exports = FORCED ? function parseFloat(string) { + var trimmedString = trim(toString(string)); + var result = $parseFloat(trimmedString); + return result === 0 && charAt(trimmedString, 0) === '-' ? -0 : result; +} : $parseFloat; /***/ }), -/* 220 */ +/* 229 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var lengthOfArrayLike = __webpack_require__(50); -var toIntegerOrInfinity = __webpack_require__(54); +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); +var trim = __webpack_require__(93).trim; +var whitespaces = __webpack_require__(107); -var $RangeError = RangeError; +var $parseInt = globalThis.parseInt; +var Symbol = globalThis.Symbol; +var ITERATOR = Symbol && Symbol.iterator; +var hex = /^[+-]?0x/i; +var exec = uncurryThis(hex.exec); +var FORCED = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22 + // MS Edge 18- broken with boxed symbols + || (ITERATOR && !fails(function () { $parseInt(Object(ITERATOR)); })); -// https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with -// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with -module.exports = function (O, C, index, value) { - var len = lengthOfArrayLike(O); - var relativeIndex = toIntegerOrInfinity(index); - var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex; - if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index'); - var A = new C(len); - var k = 0; - for (; k < len; k++) A[k] = k === actualIndex ? value : O[k]; - return A; -}; +// `parseInt` method +// https://tc39.es/ecma262/#sec-parseint-string-radix +module.exports = FORCED ? function parseInt(string, radix) { + var S = trim(toString(string)); + return $parseInt(S, (radix >>> 0) || (exec(hex, S) ? 16 : 10)); +} : $parseInt; /***/ }), -/* 221 */ +/* 230 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var create = __webpack_require__(62); -var getMethod = __webpack_require__(60); -var defineBuiltIns = __webpack_require__(88); -var InternalStateModule = __webpack_require__(53); -var iteratorClose = __webpack_require__(61); -var getBuiltIn = __webpack_require__(43); -var AsyncIteratorPrototype = __webpack_require__(222); -var createIterResultObject = __webpack_require__(96); - -var Promise = getBuiltIn('Promise'); +var DESCRIPTORS = __webpack_require__(6); +var uncurryThis = __webpack_require__(2); +var call = __webpack_require__(4); +var fails = __webpack_require__(1); +var objectKeys = __webpack_require__(103); +var getOwnPropertySymbolsModule = __webpack_require__(125); +var propertyIsEnumerableModule = __webpack_require__(126); +var toObject = __webpack_require__(15); +var IndexedObject = __webpack_require__(84); -var ASYNC_FROM_SYNC_ITERATOR = 'AsyncFromSyncIterator'; -var setInternalState = InternalStateModule.set; -var getInternalState = InternalStateModule.getterFor(ASYNC_FROM_SYNC_ITERATOR); +// eslint-disable-next-line es/no-object-assign -- safe +var $assign = Object.assign; +// eslint-disable-next-line es/no-object-defineproperty -- required for testing +var defineProperty = Object.defineProperty; +var concat = uncurryThis([].concat); -var asyncFromSyncIteratorContinuation = function (result, resolve, reject, syncIterator, closeOnRejection) { - var done = result.done; - Promise.resolve(result.value).then(function (value) { - resolve(createIterResultObject(value, done)); - }, function (error) { - if (!done && closeOnRejection) { - try { - iteratorClose(syncIterator, 'throw', error); - } catch (error2) { - error = error2; - } +// `Object.assign` method +// https://tc39.es/ecma262/#sec-object.assign +module.exports = !$assign || fails(function () { + // should have correct order of operations (Edge bug) + if (DESCRIPTORS && $assign({ b: 1 }, $assign(defineProperty({}, 'a', { + enumerable: true, + get: function () { + defineProperty(this, 'b', { + value: 3, + enumerable: false + }); + } + }), { b: 2 })).b !== 1) return true; + // should work with symbols and should have deterministic property order (V8 bug) + var A = {}; + var B = {}; + // eslint-disable-next-line es/no-symbol -- safe + var symbol = Symbol('assign detection'); + var alphabet = 'abcdefghijklmnopqrst'; + A[symbol] = 7; + // eslint-disable-next-line es/no-array-prototype-foreach -- safe + alphabet.split('').forEach(function (chr) { B[chr] = chr; }); + return $assign({}, A)[symbol] !== 7 || objectKeys($assign({}, B)).join('') !== alphabet; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length` + var T = toObject(target); + var argumentsLength = arguments.length; + var index = 1; + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + var propertyIsEnumerable = propertyIsEnumerableModule.f; + while (argumentsLength > index) { + var S = IndexedObject(arguments[index++]); + var keys = getOwnPropertySymbols ? concat(objectKeys(S), getOwnPropertySymbols(S)) : objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) { + key = keys[j++]; + if (!DESCRIPTORS || call(propertyIsEnumerable, S, key)) T[key] = S[key]; } + } return T; +} : $assign; - reject(error); - }); -}; -var AsyncFromSyncIterator = function AsyncIterator(iteratorRecord) { - iteratorRecord.type = ASYNC_FROM_SYNC_ITERATOR; - setInternalState(this, iteratorRecord); -}; +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { -AsyncFromSyncIterator.prototype = defineBuiltIns(create(AsyncIteratorPrototype), { - next: function next() { - var state = getInternalState(this); - return new Promise(function (resolve, reject) { - var result = anObject(call(state.next, state.iterator)); - asyncFromSyncIteratorContinuation(result, resolve, reject, state.iterator, true); - }); - }, - 'return': function () { - var iterator = getInternalState(this).iterator; - return new Promise(function (resolve, reject) { - var $return = getMethod(iterator, 'return'); - if ($return === undefined) return resolve(createIterResultObject(undefined, true)); - var result = anObject(call($return, iterator)); - asyncFromSyncIteratorContinuation(result, resolve, reject, iterator); - }); - } -}); +"use strict"; -module.exports = AsyncFromSyncIterator; +var uncurryThis = __webpack_require__(2); +var hasOwn = __webpack_require__(13); +var toIndexedObject = __webpack_require__(25); +var indexOf = __webpack_require__(96).indexOf; +var hiddenKeys = __webpack_require__(100); + +var push = uncurryThis([].push); + +module.exports = function (object, names) { + var O = toIndexedObject(object); + var i = 0; + var result = []; + var key; + for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key); + // Don't enum bug & hidden keys + while (names.length > i) if (hasOwn(O, key = names[i++])) { + ~indexOf(result, key) || push(result, key); + } + return result; +}; /***/ }), -/* 222 */ +/* 232 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var shared = __webpack_require__(162); -var isCallable = __webpack_require__(46); -var create = __webpack_require__(62); -var getPrototypeOf = __webpack_require__(67); -var defineBuiltIn = __webpack_require__(49); -var wellKnownSymbol = __webpack_require__(39); -var IS_PURE = __webpack_require__(48); - -var USE_FUNCTION_CONSTRUCTOR = 'USE_FUNCTION_CONSTRUCTOR'; -var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); -var AsyncIterator = globalThis.AsyncIterator; -var PassedAsyncIteratorPrototype = shared.AsyncIteratorPrototype; -var AsyncIteratorPrototype, prototype; +var DESCRIPTORS = __webpack_require__(6); +var fails = __webpack_require__(1); +var uncurryThis = __webpack_require__(2); +var objectGetPrototypeOf = __webpack_require__(35); +var objectKeys = __webpack_require__(103); +var toIndexedObject = __webpack_require__(25); +var $propertyIsEnumerable = __webpack_require__(126).f; -if (PassedAsyncIteratorPrototype) { - AsyncIteratorPrototype = PassedAsyncIteratorPrototype; -} else if (isCallable(AsyncIterator)) { - AsyncIteratorPrototype = AsyncIterator.prototype; -} else if (shared[USE_FUNCTION_CONSTRUCTOR] || globalThis[USE_FUNCTION_CONSTRUCTOR]) { - try { - // eslint-disable-next-line no-new-func -- we have no alternatives without usage of modern syntax - prototype = getPrototypeOf(getPrototypeOf(getPrototypeOf(Function('return async function*(){}()')()))); - if (getPrototypeOf(prototype) === Object.prototype) AsyncIteratorPrototype = prototype; - } catch (error) { /* empty */ } -} +var propertyIsEnumerable = uncurryThis($propertyIsEnumerable); +var push = uncurryThis([].push); -if (!AsyncIteratorPrototype) AsyncIteratorPrototype = {}; -else if (IS_PURE) AsyncIteratorPrototype = create(AsyncIteratorPrototype); +// in some IE versions, `propertyIsEnumerable` returns incorrect result on integer keys +// of `null` prototype objects +var IE_BUG = DESCRIPTORS && fails(function () { + // eslint-disable-next-line es/no-object-create -- safe + var O = Object.create(null); + O[2] = 2; + return !propertyIsEnumerable(O, 2); +}); -if (!isCallable(AsyncIteratorPrototype[ASYNC_ITERATOR])) { - defineBuiltIn(AsyncIteratorPrototype, ASYNC_ITERATOR, function () { - return this; - }); -} +// `Object.{ entries, values }` methods implementation +var createMethod = function (TO_ENTRIES) { + return function (it) { + var O = toIndexedObject(it); + var keys = objectKeys(O); + var IE_WORKAROUND = IE_BUG && objectGetPrototypeOf(O) === null; + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) { + key = keys[i++]; + if (!DESCRIPTORS || (IE_WORKAROUND ? key in O : propertyIsEnumerable(O, key))) { + push(result, TO_ENTRIES ? [key, O[key]] : O[key]); + } + } + return result; + }; +}; -module.exports = AsyncIteratorPrototype; +module.exports = { + // `Object.entries` method + // https://tc39.es/ecma262/#sec-object.entries + entries: createMethod(true), + // `Object.values` method + // https://tc39.es/ecma262/#sec-object.values + values: createMethod(false) +}; /***/ }), -/* 223 */ +/* 233 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var commonAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; -var base64Alphabet = commonAlphabet + '+/'; -var base64UrlAlphabet = commonAlphabet + '-_'; +var call = __webpack_require__(4); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); -var inverse = function (characters) { - // TODO: use `Object.create(null)` in `core-js@4` - var result = {}; - var index = 0; - for (; index < 64; index++) result[characters.charAt(index)] = index; - return result; -}; +var $TypeError = TypeError; -module.exports = { - i2c: base64Alphabet, - c2i: inverse(base64Alphabet), - i2cUrl: base64UrlAlphabet, - c2iUrl: inverse(base64UrlAlphabet) +// `OrdinaryToPrimitive` abstract operation +// https://tc39.es/ecma262/#sec-ordinarytoprimitive +module.exports = function (input, pref) { + var fn, val; + if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; + if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val; + if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; + throw new $TypeError("Can't convert object to primitive value"); }; /***/ }), -/* 224 */ +/* 234 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var create = __webpack_require__(62); -var defineBuiltInAccessor = __webpack_require__(55); -var defineBuiltIns = __webpack_require__(88); -var bind = __webpack_require__(75); -var anInstance = __webpack_require__(71); -var isNullOrUndefined = __webpack_require__(89); -var iterate = __webpack_require__(56); -var defineIterator = __webpack_require__(190); -var createIterResultObject = __webpack_require__(96); -var setSpecies = __webpack_require__(122); -var DESCRIPTORS = __webpack_require__(38); -var fastKey = __webpack_require__(102).fastKey; -var InternalStateModule = __webpack_require__(53); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var newPromiseCapability = __webpack_require__(58); -var setInternalState = InternalStateModule.set; -var internalStateGetterFor = InternalStateModule.getterFor; +module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; +}; -module.exports = { - getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { - var Constructor = wrapper(function (that, iterable) { - anInstance(that, Prototype); - setInternalState(that, { - type: CONSTRUCTOR_NAME, - index: create(null), - first: null, - last: null, - size: 0 - }); - if (!DESCRIPTORS) that.size = 0; - if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); - }); - var Prototype = Constructor.prototype; +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { - var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); +"use strict"; - var define = function (that, key, value) { - var state = getInternalState(that); - var entry = getEntry(that, key); - var previous, index; - // change existing entry - if (entry) { - entry.value = value; - // create new entry - } else { - state.last = entry = { - index: index = fastKey(key, true), - key: key, - value: value, - previous: previous = state.last, - next: null, - removed: false - }; - if (!state.first) state.first = entry; - if (previous) previous.next = entry; - if (DESCRIPTORS) state.size++; - else that.size++; - // add to index - if (index !== 'F') state.index[index] = entry; - } return that; - }; +var defineProperty = __webpack_require__(19).f; - var getEntry = function (that, key) { - var state = getInternalState(that); - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return state.index[index]; - // frozen object case - for (entry = state.first; entry; entry = entry.next) { - if (entry.key === key) return entry; - } - }; +module.exports = function (Target, Source, key) { + key in Target || defineProperty(Target, key, { + configurable: true, + get: function () { return Source[key]; }, + set: function (it) { Source[key] = it; } + }); +}; - defineBuiltIns(Prototype, { - // `{ Map, Set }.prototype.clear()` methods - // https://tc39.es/ecma262/#sec-map.prototype.clear - // https://tc39.es/ecma262/#sec-set.prototype.clear - clear: function clear() { - var that = this; - var state = getInternalState(that); - var entry = state.first; - while (entry) { - entry.removed = true; - if (entry.previous) entry.previous = entry.previous.next = null; - entry = entry.next; - } - state.first = state.last = null; - state.index = create(null); - if (DESCRIPTORS) state.size = 0; - else that.size = 0; - }, - // `{ Map, Set }.prototype.delete(key)` methods - // https://tc39.es/ecma262/#sec-map.prototype.delete - // https://tc39.es/ecma262/#sec-set.prototype.delete - 'delete': function (key) { - var that = this; - var state = getInternalState(that); - var entry = getEntry(that, key); - if (entry) { - var next = entry.next; - var prev = entry.previous; - delete state.index[entry.index]; - entry.removed = true; - if (prev) prev.next = next; - if (next) next.previous = prev; - if (state.first === entry) state.first = next; - if (state.last === entry) state.last = prev; - if (DESCRIPTORS) state.size--; - else that.size--; - } return !!entry; - }, - // `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods - // https://tc39.es/ecma262/#sec-map.prototype.foreach - // https://tc39.es/ecma262/#sec-set.prototype.foreach - forEach: function forEach(callbackfn /* , that = undefined */) { - var state = getInternalState(this); - var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined); - var entry; - while (entry = entry ? entry.next : state.first) { - boundFunction(entry.value, entry.key, this); - // revert to the last existing entry - while (entry && entry.removed) entry = entry.previous; - } - }, - // `{ Map, Set}.prototype.has(key)` methods - // https://tc39.es/ecma262/#sec-map.prototype.has - // https://tc39.es/ecma262/#sec-set.prototype.has - has: function has(key) { - return !!getEntry(this, key); - } - }); - defineBuiltIns(Prototype, IS_MAP ? { - // `Map.prototype.get(key)` method - // https://tc39.es/ecma262/#sec-map.prototype.get - get: function get(key) { - var entry = getEntry(this, key); - return entry && entry.value; - }, - // `Map.prototype.set(key, value)` method - // https://tc39.es/ecma262/#sec-map.prototype.set - set: function set(key, value) { - return define(this, key === 0 ? 0 : key, value); - } - } : { - // `Set.prototype.add(value)` method - // https://tc39.es/ecma262/#sec-set.prototype.add - add: function add(value) { - return define(this, value = value === 0 ? 0 : value, value); - } - }); - if (DESCRIPTORS) defineBuiltInAccessor(Prototype, 'size', { - configurable: true, - get: function () { - return getInternalState(this).size; - } - }); - return Constructor; - }, - setStrong: function (Constructor, CONSTRUCTOR_NAME, IS_MAP) { - var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; - var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); - var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); - // `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods - // https://tc39.es/ecma262/#sec-map.prototype.entries - // https://tc39.es/ecma262/#sec-map.prototype.keys - // https://tc39.es/ecma262/#sec-map.prototype.values - // https://tc39.es/ecma262/#sec-map.prototype-@@iterator - // https://tc39.es/ecma262/#sec-set.prototype.entries - // https://tc39.es/ecma262/#sec-set.prototype.keys - // https://tc39.es/ecma262/#sec-set.prototype.values - // https://tc39.es/ecma262/#sec-set.prototype-@@iterator - defineIterator(Constructor, CONSTRUCTOR_NAME, function (iterated, kind) { - setInternalState(this, { - type: ITERATOR_NAME, - target: iterated, - state: getInternalCollectionState(iterated), - kind: kind, - last: null - }); - }, function () { - var state = getInternalIteratorState(this); - var kind = state.kind; - var entry = state.last; - // revert to the last existing entry - while (entry && entry.removed) entry = entry.previous; - // get next entry - if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { - // or finish the iteration - state.target = null; - return createIterResultObject(undefined, true); - } - // return step by kind - if (kind === 'keys') return createIterResultObject(entry.key, false); - if (kind === 'values') return createIterResultObject(entry.value, false); - return createIterResultObject([entry.key, entry.value], false); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { - // `{ Map, Set }.prototype[@@species]` accessors - // https://tc39.es/ecma262/#sec-get-map-@@species - // https://tc39.es/ecma262/#sec-get-set-@@species - setSpecies(CONSTRUCTOR_NAME); +"use strict"; + +var Queue = function () { + this.head = null; + this.tail = null; +}; + +Queue.prototype = { + add: function (item) { + var entry = { item: item, next: null }; + var tail = this.tail; + if (tail) tail.next = entry; + else this.head = entry; + this.tail = entry; + }, + get: function () { + var entry = this.head; + if (entry) { + var next = this.head = entry.next; + if (next === null) this.tail = null; + return entry.item; + } } }; +module.exports = Queue; + /***/ }), -/* 225 */ +/* 237 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var defineBuiltIns = __webpack_require__(88); -var getWeakData = __webpack_require__(102).getWeakData; -var anInstance = __webpack_require__(71); -var anObject = __webpack_require__(37); -var isNullOrUndefined = __webpack_require__(89); -var isObject = __webpack_require__(40); -var iterate = __webpack_require__(56); -var ArrayIterationModule = __webpack_require__(58); -var hasOwn = __webpack_require__(45); -var InternalStateModule = __webpack_require__(53); - -var setInternalState = InternalStateModule.set; -var internalStateGetterFor = InternalStateModule.getterFor; -var find = ArrayIterationModule.find; -var findIndex = ArrayIterationModule.findIndex; -var splice = uncurryThis([].splice); -var id = 0; - -// fallback for uncaught frozen keys -var uncaughtFrozenStore = function (state) { - return state.frozen || (state.frozen = new UncaughtFrozenStore()); -}; - -var UncaughtFrozenStore = function () { - this.entries = []; -}; +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); -var findUncaughtFrozen = function (store, key) { - return find(store.entries, function (it) { - return it[0] === key; - }); -}; +// babel-minify and Closure Compiler transpiles RegExp('.', 'd') -> /./d and it causes SyntaxError +var RegExp = globalThis.RegExp; -UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.entries.push([key, value]); - }, - 'delete': function (key) { - var index = findIndex(this.entries, function (it) { - return it[0] === key; - }); - if (~index) splice(this.entries, index, 1); - return !!~index; +var FLAGS_GETTER_IS_CORRECT = !fails(function () { + var INDICES_SUPPORT = true; + try { + RegExp('.', 'd'); + } catch (error) { + INDICES_SUPPORT = false; } -}; -module.exports = { - getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { - var Constructor = wrapper(function (that, iterable) { - anInstance(that, Prototype); - setInternalState(that, { - type: CONSTRUCTOR_NAME, - id: id++, - frozen: null - }); - if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); - }); + var O = {}; + // modern V8 bug + var calls = ''; + var expected = INDICES_SUPPORT ? 'dgimsy' : 'gimsy'; - var Prototype = Constructor.prototype; + var addGetter = function (key, chr) { + // eslint-disable-next-line es/no-object-defineproperty -- safe + Object.defineProperty(O, key, { get: function () { + calls += chr; + return true; + } }); + }; - var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); + var pairs = { + dotAll: 's', + global: 'g', + ignoreCase: 'i', + multiline: 'm', + sticky: 'y' + }; - var define = function (that, key, value) { - var state = getInternalState(that); - var data = getWeakData(anObject(key), true); - if (data === true) uncaughtFrozenStore(state).set(key, value); - else data[state.id] = value; - return that; - }; + if (INDICES_SUPPORT) pairs.hasIndices = 'd'; - defineBuiltIns(Prototype, { - // `{ WeakMap, WeakSet }.prototype.delete(key)` methods - // https://tc39.es/ecma262/#sec-weakmap.prototype.delete - // https://tc39.es/ecma262/#sec-weakset.prototype.delete - 'delete': function (key) { - var state = getInternalState(this); - if (!isObject(key)) return false; - var data = getWeakData(key); - if (data === true) return uncaughtFrozenStore(state)['delete'](key); - return data && hasOwn(data, state.id) && delete data[state.id]; - }, - // `{ WeakMap, WeakSet }.prototype.has(key)` methods - // https://tc39.es/ecma262/#sec-weakmap.prototype.has - // https://tc39.es/ecma262/#sec-weakset.prototype.has - has: function has(key) { - var state = getInternalState(this); - if (!isObject(key)) return false; - var data = getWeakData(key); - if (data === true) return uncaughtFrozenStore(state).has(key); - return data && hasOwn(data, state.id); - } - }); + for (var key in pairs) addGetter(key, pairs[key]); - defineBuiltIns(Prototype, IS_MAP ? { - // `WeakMap.prototype.get(key)` method - // https://tc39.es/ecma262/#sec-weakmap.prototype.get - get: function get(key) { - var state = getInternalState(this); - if (isObject(key)) { - var data = getWeakData(key); - if (data === true) return uncaughtFrozenStore(state).get(key); - if (data) return data[state.id]; - } - }, - // `WeakMap.prototype.set(key, value)` method - // https://tc39.es/ecma262/#sec-weakmap.prototype.set - set: function set(key, value) { - return define(this, key, value); - } - } : { - // `WeakSet.prototype.add(value)` method - // https://tc39.es/ecma262/#sec-weakset.prototype.add - add: function add(value) { - return define(this, value, true); - } - }); + // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe + var result = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags').get.call(O); - return Constructor; - } -}; + return result !== expected || calls !== expected; +}); + +module.exports = { correct: FLAGS_GETTER_IS_CORRECT }; /***/ }), -/* 226 */ +/* 238 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var getBuiltInNodeModule = __webpack_require__(237); -var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(204); +var fails = __webpack_require__(1); +var globalThis = __webpack_require__(3); -var structuredClone = globalThis.structuredClone; -var $ArrayBuffer = globalThis.ArrayBuffer; -var $MessageChannel = globalThis.MessageChannel; -var detach = false; -var WorkerThreads, channel, buffer, $detach; +// babel-minify and Closure Compiler transpiles RegExp('(?b)', 'g') -> /(?b)/g and it causes SyntaxError +var $RegExp = globalThis.RegExp; -if (PROPER_STRUCTURED_CLONE_TRANSFER) { - detach = function (transferable) { - structuredClone(transferable, { transfer: [transferable] }); - }; -} else if ($ArrayBuffer) try { - if (!$MessageChannel) { - WorkerThreads = getBuiltInNodeModule('worker_threads'); - if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel; - } +module.exports = fails(function () { + var re = $RegExp('(?b)', 'g'); + return re.exec('b').groups.a !== 'b' || + 'b'.replace(re, '$c') !== 'bc'; +}); - if ($MessageChannel) { - channel = new $MessageChannel(); - buffer = new $ArrayBuffer(2); - $detach = function (transferable) { - channel.port1.postMessage(null, [transferable]); - }; +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { - if (buffer.byteLength === 2) { - $detach(buffer); - if (buffer.byteLength === 0) detach = $detach; - } - } -} catch (error) { /* empty */ } +"use strict"; -module.exports = detach; +var globalThis = __webpack_require__(3); +var DESCRIPTORS = __webpack_require__(6); + +// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +// Avoid NodeJS experimental warning +module.exports = function (name) { + if (!DESCRIPTORS) return globalThis[name]; + var descriptor = getOwnPropertyDescriptor(globalThis, name); + return descriptor && descriptor.value; +}; /***/ }), -/* 227 */ +/* 240 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = { - IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 }, - DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 }, - HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 }, - WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 }, - InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 }, - NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 }, - NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 }, - NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 }, - NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 }, - InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 }, - InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 }, - SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 }, - InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 }, - NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 }, - InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 }, - ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 }, - TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 }, - SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 }, - NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 }, - AbortError: { s: 'ABORT_ERR', c: 20, m: 1 }, - URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 }, - QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 }, - TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 }, - InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 }, - DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 } +// `SameValue` abstract operation +// https://tc39.es/ecma262/#sec-samevalue +// eslint-disable-next-line es/no-object-is -- safe +module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare -- NaN check + return x === y ? x !== 0 || 1 / x === 1 / y : x !== x && y !== y; }; /***/ }), -/* 228 */ +/* 241 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// iterable DOM collections -// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods -module.exports = { - CSSRuleList: 0, - CSSStyleDeclaration: 0, - CSSValueList: 0, - ClientRectList: 0, - DOMRectList: 0, - DOMStringList: 0, - DOMTokenList: 1, - DataTransferItemList: 0, - FileList: 0, - HTMLAllCollection: 0, - HTMLCollection: 0, - HTMLFormElement: 0, - HTMLSelectElement: 0, - MediaList: 0, - MimeTypeArray: 0, - NamedNodeMap: 0, - NodeList: 1, - PaintRequestList: 0, - Plugin: 0, - PluginArray: 0, - SVGLengthList: 0, - SVGNumberList: 0, - SVGPathSegList: 0, - SVGPointList: 0, - SVGStringList: 0, - SVGTransformList: 0, - SourceBufferList: 0, - StyleSheetList: 0, - TextTrackCueList: 0, - TextTrackList: 0, - TouchList: 0 +// Should get iterator record of a set-like object before cloning this +// https://bugs.webkit.org/show_bug.cgi?id=289430 +module.exports = function (METHOD_NAME) { + try { + // eslint-disable-next-line es/no-set -- needed for test + var baseSet = new Set(); + var setLike = { + size: 0, + has: function () { return true; }, + keys: function () { + // eslint-disable-next-line es/no-object-defineproperty -- needed for test + return Object.defineProperty({}, 'next', { + get: function () { + baseSet.clear(); + baseSet.add(4); + return function () { + return { done: true }; + }; + } + }); + } + }; + var result = baseSet[METHOD_NAME](setLike); + + return result.size !== 1 || result.values().next().value !== 4; + } catch (error) { + return false; + } }; /***/ }), -/* 229 */ +/* 242 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList` -var documentCreateElement = __webpack_require__(148); - -var classList = documentCreateElement('span').classList; -var DOMTokenListPrototype = classList && classList.constructor && classList.constructor.prototype; +// https://github.com/zloirock/core-js/issues/280 +var userAgent = __webpack_require__(51); -module.exports = DOMTokenListPrototype === Object.prototype ? undefined : DOMTokenListPrototype; +module.exports = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent); /***/ }), -/* 230 */ +/* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var userAgent = __webpack_require__(83); - -var firefox = userAgent.match(/firefox\/(\d+)/i); +var $trimEnd = __webpack_require__(93).end; +var forcedStringTrimMethod = __webpack_require__(174); -module.exports = !!firefox && +firefox[1]; +// `String.prototype.{ trimEnd, trimRight }` method +// https://tc39.es/ecma262/#sec-string.prototype.trimend +// https://tc39.es/ecma262/#String.prototype.trimright +module.exports = forcedStringTrimMethod('trimEnd') ? function trimEnd() { + return $trimEnd(this); +// eslint-disable-next-line es/no-string-prototype-trimstart-trimend -- safe +} : ''.trimEnd; /***/ }), -/* 231 */ +/* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var UA = __webpack_require__(83); +var $trimStart = __webpack_require__(93).start; +var forcedStringTrimMethod = __webpack_require__(174); -module.exports = /MSIE|Trident/.test(UA); +// `String.prototype.{ trimStart, trimLeft }` method +// https://tc39.es/ecma262/#sec-string.prototype.trimstart +// https://tc39.es/ecma262/#String.prototype.trimleft +module.exports = forcedStringTrimMethod('trimStart') ? function trimStart() { + return $trimStart(this); +// eslint-disable-next-line es/no-string-prototype-trimstart-trimend -- safe +} : ''.trimStart; /***/ }), -/* 232 */ +/* 245 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var userAgent = __webpack_require__(83); +var call = __webpack_require__(4); +var getBuiltIn = __webpack_require__(11); +var wellKnownSymbol = __webpack_require__(7); +var defineBuiltIn = __webpack_require__(17); -// eslint-disable-next-line redos/no-vulnerable -- safe -module.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent); +module.exports = function () { + var Symbol = getBuiltIn('Symbol'); + var SymbolPrototype = Symbol && Symbol.prototype; + var valueOf = SymbolPrototype && SymbolPrototype.valueOf; + var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); + + if (SymbolPrototype && !SymbolPrototype[TO_PRIMITIVE]) { + // `Symbol.prototype[@@toPrimitive]` method + // https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive + // eslint-disable-next-line no-unused-vars -- required for .length + defineBuiltIn(SymbolPrototype, TO_PRIMITIVE, function (hint) { + return call(valueOf, this); + }, { arity: 1 }); + } +}; /***/ }), -/* 233 */ +/* 246 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fails = __webpack_require__(33); -var createPropertyDescriptor = __webpack_require__(73); +var NATIVE_SYMBOL = __webpack_require__(94); -module.exports = !fails(function () { - var error = new Error('a'); - if (!('stack' in error)) return true; - // eslint-disable-next-line es/no-object-defineproperty -- safe - Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7)); - return error.stack !== 7; -}); +/* eslint-disable es/no-symbol -- safe */ +module.exports = NATIVE_SYMBOL && !!Symbol['for'] && !!Symbol.keyFor; /***/ }), -/* 234 */ +/* 247 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var fails = __webpack_require__(33); -var anObject = __webpack_require__(37); -var normalizeStringArgument = __webpack_require__(118); - -var nativeErrorToString = Error.prototype.toString; +var toPositiveInteger = __webpack_require__(177); -var INCORRECT_TO_STRING = fails(function () { - if (DESCRIPTORS) { - // Chrome 32- incorrectly call accessor - // eslint-disable-next-line es/no-object-create, es/no-object-defineproperty -- safe - var object = Object.create(Object.defineProperty({}, 'name', { get: function () { - return this === object; - } })); - if (nativeErrorToString.call(object) !== 'true') return true; - } - // FF10- does not properly handle non-strings - return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1' - // IE8 does not properly handle defaults - || nativeErrorToString.call({}) !== 'Error'; -}); +var $RangeError = RangeError; -module.exports = INCORRECT_TO_STRING ? function toString() { - var O = anObject(this); - var name = normalizeStringArgument(O.name, 'Error'); - var message = normalizeStringArgument(O.message); - return !name ? message : !message ? name : name + ': ' + message; -} : nativeErrorToString; +module.exports = function (it, BYTES) { + var offset = toPositiveInteger(it); + if (offset % BYTES) throw new $RangeError('Wrong offset'); + return offset; +}; /***/ }), -/* 235 */ +/* 248 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isArray = __webpack_require__(93); -var lengthOfArrayLike = __webpack_require__(50); -var doesNotExceedSafeInteger = __webpack_require__(97); -var bind = __webpack_require__(75); - -// `FlattenIntoArray` abstract operation -// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray -var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? bind(mapper, thisArg) : false; - var element, elementLen; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - if (depth > 0 && isArray(element)) { - elementLen = lengthOfArrayLike(element); - targetIndex = flattenIntoArray(target, original, element, elementLen, targetIndex, depth - 1) - 1; - } else { - doesNotExceedSafeInteger(targetIndex + 1); - target[targetIndex] = element; - } +var bind = __webpack_require__(43); +var call = __webpack_require__(4); +var aConstructor = __webpack_require__(144); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var getIterator = __webpack_require__(83); +var getIteratorMethod = __webpack_require__(68); +var isArrayIteratorMethod = __webpack_require__(158); +var isBigIntArray = __webpack_require__(215); +var aTypedArrayConstructor = __webpack_require__(12).aTypedArrayConstructor; +var toBigInt = __webpack_require__(176); - targetIndex++; +module.exports = function from(source /* , mapfn, thisArg */) { + var C = aConstructor(this); + var O = toObject(source); + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iteratorMethod = getIteratorMethod(O); + var i, length, result, thisIsBigIntArray, value, step, iterator, next; + if (iteratorMethod && !isArrayIteratorMethod(iteratorMethod)) { + iterator = getIterator(O, iteratorMethod); + next = iterator.next; + O = []; + while (!(step = call(next, iterator)).done) { + O.push(step.value); } - sourceIndex++; } - return targetIndex; + if (mapping && argumentsLength > 2) { + mapfn = bind(mapfn, arguments[2]); + } + length = lengthOfArrayLike(O); + result = new (aTypedArrayConstructor(C))(length); + thisIsBigIntArray = isBigIntArray(result); + for (i = 0; length > i; i++) { + value = mapping ? mapfn(O[i], i) : O[i]; + // FF30- typed arrays doesn't properly convert objects to typed array values + result[i] = thisIsBigIntArray ? toBigInt(value) : +value; + } + return result; }; -module.exports = flattenIntoArray; - /***/ }), -/* 236 */ +/* 249 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var isObject = __webpack_require__(40); -var hasOwn = __webpack_require__(45); -var arraySlice = __webpack_require__(78); -var NATIVE_BIND = __webpack_require__(130); +/* eslint-disable es/no-symbol -- required for testing */ +var NATIVE_SYMBOL = __webpack_require__(94); -var $Function = Function; -var concat = uncurryThis([].concat); -var join = uncurryThis([].join); -var factories = {}; +module.exports = NATIVE_SYMBOL && + !Symbol.sham && + typeof Symbol.iterator == 'symbol'; -var construct = function (C, argsLength, args) { - if (!hasOwn(factories, argsLength)) { - var list = []; - var i = 0; - for (; i < argsLength; i++) list[i] = 'a[' + i + ']'; - factories[argsLength] = $Function('C,a', 'return new C(' + join(list, ',') + ')'); - } return factories[argsLength](C, args); -}; -// `Function.prototype.bind` method implementation -// https://tc39.es/ecma262/#sec-function.prototype.bind -// eslint-disable-next-line es/no-function-prototype-bind -- detection -module.exports = NATIVE_BIND ? $Function.bind : function bind(that /* , ...args */) { - var F = aCallable(this); - var Prototype = F.prototype; - var partArgs = arraySlice(arguments, 1); - var boundFunction = function bound(/* args... */) { - var args = concat(partArgs, arraySlice(arguments)); - return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args); - }; - if (isObject(Prototype)) boundFunction.prototype = Prototype; - return boundFunction; -}; +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var DESCRIPTORS = __webpack_require__(6); +var fails = __webpack_require__(1); + +// V8 ~ Chrome 36- +// https://bugs.chromium.org/p/v8/issues/detail?id=3334 +module.exports = DESCRIPTORS && fails(function () { + // eslint-disable-next-line es/no-object-defineproperty -- required for testing + return Object.defineProperty(function () { /* empty */ }, 'prototype', { + value: 42, + writable: false + }).prototype !== 42; +}); /***/ }), -/* 237 */ +/* 251 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var IS_NODE = __webpack_require__(111); +var globalThis = __webpack_require__(3); +var isCallable = __webpack_require__(14); -module.exports = function (name) { - if (IS_NODE) { - try { - return globalThis.process.getBuiltinModule(name); - } catch (error) { /* empty */ } - try { - // eslint-disable-next-line no-new-func -- safe - return Function('return require("' + name + '")')(); - } catch (error) { /* empty */ } - } -}; +var WeakMap = globalThis.WeakMap; + +module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap)); /***/ }), -/* 238 */ +/* 252 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +var wellKnownSymbol = __webpack_require__(7); -module.exports = function (CONSTRUCTOR, METHOD) { - var Constructor = globalThis[CONSTRUCTOR]; - var Prototype = Constructor && Constructor.prototype; - return Prototype && Prototype[METHOD]; -}; +exports.f = wellKnownSymbol; /***/ }), -/* 239 */ +/* 253 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var getIteratorMethod = __webpack_require__(99); +var getBuiltIn = __webpack_require__(11); +var hasOwn = __webpack_require__(13); +var createNonEnumerableProperty = __webpack_require__(27); +var isPrototypeOf = __webpack_require__(36); +var setPrototypeOf = __webpack_require__(49); +var copyConstructorProperties = __webpack_require__(79); +var proxyAccessor = __webpack_require__(235); +var inheritIfRequired = __webpack_require__(70); +var normalizeStringArgument = __webpack_require__(87); +var installErrorCause = __webpack_require__(214); +var installErrorStack = __webpack_require__(156); +var DESCRIPTORS = __webpack_require__(6); +var IS_PURE = __webpack_require__(16); -module.exports = function (obj, stringHandling) { - if (!stringHandling || typeof obj !== 'string') anObject(obj); - var method = getIteratorMethod(obj); - return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj)); +module.exports = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) { + var STACK_TRACE_LIMIT = 'stackTraceLimit'; + var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1; + var path = FULL_NAME.split('.'); + var ERROR_NAME = path[path.length - 1]; + var OriginalError = getBuiltIn.apply(null, path); + + if (!OriginalError) return; + + var OriginalErrorPrototype = OriginalError.prototype; + + // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006 + if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause; + + if (!FORCED) return OriginalError; + + var BaseError = getBuiltIn('Error'); + + var WrappedError = wrapper(function (a, b) { + var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined); + var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError(); + if (message !== undefined) createNonEnumerableProperty(result, 'message', message); + installErrorStack(result, WrappedError, result.stack, 2); + if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError); + if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]); + return result; + }); + + WrappedError.prototype = OriginalErrorPrototype; + + if (ERROR_NAME !== 'Error') { + if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError); + else copyConstructorProperties(WrappedError, BaseError, { name: true }); + } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) { + proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT); + proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace'); + } + + copyConstructorProperties(WrappedError, OriginalError); + + if (!IS_PURE) try { + // Safari 13- bug: WebAssembly errors does not have a proper `.name` + if (OriginalErrorPrototype.name !== ERROR_NAME) { + createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME); + } + OriginalErrorPrototype.constructor = WrappedError; + } catch (error) { /* empty */ } + + return WrappedError; }; /***/ }), -/* 240 */ +/* 254 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var toObject = __webpack_require__(47); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var apply = __webpack_require__(42); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var isCallable = __webpack_require__(14); +var isSymbol = __webpack_require__(73); +var arraySlice = __webpack_require__(46); +var getReplacerFunction = __webpack_require__(294); +var NATIVE_SYMBOL = __webpack_require__(94); -var floor = Math.floor; +var $String = String; +var $stringify = getBuiltIn('JSON', 'stringify'); +var exec = uncurryThis(/./.exec); var charAt = uncurryThis(''.charAt); +var charCodeAt = uncurryThis(''.charCodeAt); var replace = uncurryThis(''.replace); -var stringSlice = uncurryThis(''.slice); -// eslint-disable-next-line redos/no-vulnerable -- safe -var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g; -var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g; +var numberToString = uncurryThis(1.1.toString); -// `GetSubstitution` abstract operation -// https://tc39.es/ecma262/#sec-getsubstitution -module.exports = function (matched, str, position, captures, namedCaptures, replacement) { - var tailPos = position + matched.length; - var m = captures.length; - var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; - if (namedCaptures !== undefined) { - namedCaptures = toObject(namedCaptures); - symbols = SUBSTITUTION_SYMBOLS; - } - return replace(replacement, symbols, function (match, ch) { - var capture; - switch (charAt(ch, 0)) { - case '$': return '$'; - case '&': return matched; - case '`': return stringSlice(str, 0, position); - case "'": return stringSlice(str, tailPos); - case '<': - capture = namedCaptures[stringSlice(ch, 1, -1)]; - break; - default: // \d\d? - var n = +ch; - if (n === 0) return match; - if (n > m) { - var f = floor(n / 10); - if (f === 0) return match; - if (f <= m) return captures[f - 1] === undefined ? charAt(ch, 1) : captures[f - 1] + charAt(ch, 1); - return match; - } - capture = captures[n - 1]; +var tester = /[\uD800-\uDFFF]/g; +var low = /^[\uD800-\uDBFF]$/; +var hi = /^[\uDC00-\uDFFF]$/; + +var WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails(function () { + var symbol = getBuiltIn('Symbol')('stringify detection'); + // MS Edge converts symbol values to JSON as {} + return $stringify([symbol]) !== '[null]' + // WebKit converts symbol values to JSON as null + || $stringify({ a: symbol }) !== '{}' + // V8 throws on boxed symbols + || $stringify(Object(symbol)) !== '{}'; +}); + +// https://github.com/tc39/proposal-well-formed-stringify +var ILL_FORMED_UNICODE = fails(function () { + return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"' + || $stringify('\uDEAD') !== '"\\udead"'; +}); + +var stringifyWithSymbolsFix = function (it, replacer) { + var args = arraySlice(arguments); + var $replacer = getReplacerFunction(replacer); + if (!isCallable($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined + args[1] = function (key, value) { + // some old implementations (like WebKit) could pass numbers as keys + if (isCallable($replacer)) value = call($replacer, this, $String(key), value); + if (!isSymbol(value)) return value; + }; + return apply($stringify, null, args); +}; + +var fixIllFormed = function (match, offset, string) { + var prev = charAt(string, offset - 1); + var next = charAt(string, offset + 1); + if ((exec(low, match) && !exec(hi, next)) || (exec(hi, match) && !exec(low, prev))) { + return '\\u' + numberToString(charCodeAt(match, 0), 16); + } return match; +}; + +if ($stringify) { + // `JSON.stringify` method + // https://tc39.es/ecma262/#sec-json.stringify + $({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE }, { + // eslint-disable-next-line no-unused-vars -- required for `.length` + stringify: function stringify(it, replacer, space) { + var args = arraySlice(arguments); + var result = apply(WRONG_SYMBOLS_CONVERSION ? stringifyWithSymbolsFix : $stringify, null, args); + return ILL_FORMED_UNICODE && typeof result == 'string' ? replace(result, tester, fixIllFormed) : result; } - return capture === undefined ? '' : capture; }); -}; +} /***/ }), -/* 241 */ +/* 255 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toAbsoluteIndex = __webpack_require__(59); -module.exports = getBuiltIn('document', 'documentElement'); +var $RangeError = RangeError; +var fromCharCode = String.fromCharCode; +// eslint-disable-next-line es/no-string-fromcodepoint -- required for testing +var $fromCodePoint = String.fromCodePoint; +var join = uncurryThis([].join); + +// length should be 1, old FF problem +var INCORRECT_LENGTH = !!$fromCodePoint && $fromCodePoint.length !== 1; + +// `String.fromCodePoint` method +// https://tc39.es/ecma262/#sec-string.fromcodepoint +$({ target: 'String', stat: true, arity: 1, forced: INCORRECT_LENGTH }, { + // eslint-disable-next-line no-unused-vars -- required for `.length` + fromCodePoint: function fromCodePoint(x) { + var elements = []; + var length = arguments.length; + var i = 0; + var code; + while (length > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw new $RangeError(code + ' is not a valid code point'); + elements[i] = code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00); + } return join(elements, ''); + } +}); /***/ }), -/* 242 */ +/* 256 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var fails = __webpack_require__(33); -var createElement = __webpack_require__(148); +var charAt = __webpack_require__(134).charAt; +var toString = __webpack_require__(9); +var InternalStateModule = __webpack_require__(21); +var defineIterator = __webpack_require__(161); +var createIterResultObject = __webpack_require__(65); -// Thanks to IE8 for its funny defineProperty -module.exports = !DESCRIPTORS && !fails(function () { - // eslint-disable-next-line es/no-object-defineproperty -- required for testing - return Object.defineProperty(createElement('div'), 'a', { - get: function () { return 7; } - }).a !== 7; +var STRING_ITERATOR = 'String Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + +// `String.prototype[@@iterator]` method +// https://tc39.es/ecma262/#sec-string.prototype-@@iterator +defineIterator(String, 'String', function (iterated) { + setInternalState(this, { + type: STRING_ITERATOR, + string: toString(iterated), + index: 0 + }); +// `%StringIteratorPrototype%.next` method +// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next +}, function next() { + var state = getInternalState(this); + var string = state.string; + var index = state.index; + var point; + if (index >= string.length) return createIterResultObject(undefined, true); + point = charAt(string, index); + state.index += point.length; + return createIterResultObject(point, false); }); -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +__webpack_require__(142); +__webpack_require__(255); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var safeGetBuiltIn = __webpack_require__(239); +var getBuiltIn = __webpack_require__(11); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var DESCRIPTORS = __webpack_require__(6); +var USE_NATIVE_URL = __webpack_require__(141); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltInAccessor = __webpack_require__(23); +var defineBuiltIns = __webpack_require__(56); +var setToStringTag = __webpack_require__(38); +var createIteratorConstructor = __webpack_require__(160); +var InternalStateModule = __webpack_require__(21); +var anInstance = __webpack_require__(39); +var isCallable = __webpack_require__(14); +var hasOwn = __webpack_require__(13); +var bind = __webpack_require__(43); +var classof = __webpack_require__(47); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var $toString = __webpack_require__(9); +var create = __webpack_require__(30); +var createPropertyDescriptor = __webpack_require__(41); +var getIterator = __webpack_require__(83); +var getIteratorMethod = __webpack_require__(68); +var createIterResultObject = __webpack_require__(65); +var validateArgumentsLength = __webpack_require__(48); +var wellKnownSymbol = __webpack_require__(7); +var arraySort = __webpack_require__(148); + +var ITERATOR = wellKnownSymbol('iterator'); +var URL_SEARCH_PARAMS = 'URLSearchParams'; +var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS); +var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR); + +var nativeFetch = safeGetBuiltIn('fetch'); +var NativeRequest = safeGetBuiltIn('Request'); +var Headers = safeGetBuiltIn('Headers'); +var RequestPrototype = NativeRequest && NativeRequest.prototype; +var HeadersPrototype = Headers && Headers.prototype; +var TypeError = globalThis.TypeError; +var encodeURIComponent = globalThis.encodeURIComponent; +var fromCharCode = String.fromCharCode; +var fromCodePoint = getBuiltIn('String', 'fromCodePoint'); +var $parseInt = parseInt; +var charAt = uncurryThis(''.charAt); +var join = uncurryThis([].join); +var push = uncurryThis([].push); +var replace = uncurryThis(''.replace); +var shift = uncurryThis([].shift); +var splice = uncurryThis([].splice); +var split = uncurryThis(''.split); +var stringSlice = uncurryThis(''.slice); +var exec = uncurryThis(/./.exec); + +var plus = /\+/g; +var FALLBACK_REPLACER = '\uFFFD'; +var VALID_HEX = /^[0-9a-f]+$/i; + +var parseHexOctet = function (string, start) { + var substr = stringSlice(string, start, start + 2); + if (!exec(VALID_HEX, substr)) return NaN; + + return $parseInt(substr, 16); +}; + +var getLeadingOnes = function (octet) { + var count = 0; + for (var mask = 0x80; mask > 0 && (octet & mask) !== 0; mask >>= 1) { + count++; + } + return count; +}; + +var utf8Decode = function (octets) { + var codePoint = null; + + switch (octets.length) { + case 1: + codePoint = octets[0]; + break; + case 2: + codePoint = (octets[0] & 0x1F) << 6 | (octets[1] & 0x3F); + break; + case 3: + codePoint = (octets[0] & 0x0F) << 12 | (octets[1] & 0x3F) << 6 | (octets[2] & 0x3F); + break; + case 4: + codePoint = (octets[0] & 0x07) << 18 | (octets[1] & 0x3F) << 12 | (octets[2] & 0x3F) << 6 | (octets[3] & 0x3F); + break; + } + + return codePoint > 0x10FFFF ? null : codePoint; +}; + +var decode = function (input) { + input = replace(input, plus, ' '); + var length = input.length; + var result = ''; + var i = 0; + + while (i < length) { + var decodedChar = charAt(input, i); -"use strict"; + if (decodedChar === '%') { + if (charAt(input, i + 1) === '%' || i + 3 > length) { + result += '%'; + i++; + continue; + } -var isObject = __webpack_require__(40); -var createNonEnumerableProperty = __webpack_require__(59); + var octet = parseHexOctet(input, i + 1); -// `InstallErrorCause` abstract operation -// https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause -module.exports = function (O, options) { - if (isObject(options) && 'cause' in options) { - createNonEnumerableProperty(O, 'cause', options.cause); - } -}; + // eslint-disable-next-line no-self-compare -- NaN check + if (octet !== octet) { + result += decodedChar; + i++; + continue; + } + i += 2; + var byteSequenceLength = getLeadingOnes(octet); -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { + if (byteSequenceLength === 0) { + decodedChar = fromCharCode(octet); + } else { + if (byteSequenceLength === 1 || byteSequenceLength > 4) { + result += FALLBACK_REPLACER; + i++; + continue; + } -"use strict"; + var octets = [octet]; + var sequenceIndex = 1; -var classof = __webpack_require__(79); + while (sequenceIndex < byteSequenceLength) { + i++; + if (i + 3 > length || charAt(input, i) !== '%') break; -module.exports = function (it) { - var klass = classof(it); - return klass === 'BigInt64Array' || klass === 'BigUint64Array'; -}; + var nextByte = parseHexOctet(input, i + 1); + // eslint-disable-next-line no-self-compare -- NaN check + if (nextByte !== nextByte) { + i += 3; + break; + } + if (nextByte > 191 || nextByte < 128) break; -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { + push(octets, nextByte); + i += 2; + sequenceIndex++; + } -"use strict"; + if (octets.length !== byteSequenceLength) { + result += FALLBACK_REPLACER; + continue; + } + + var codePoint = utf8Decode(octets); + if (codePoint === null) { + result += FALLBACK_REPLACER; + } else { + decodedChar = fromCodePoint(codePoint); + } + } + } -var hasOwn = __webpack_require__(45); + result += decodedChar; + i++; + } -module.exports = function (descriptor) { - return descriptor !== undefined && (hasOwn(descriptor, 'value') || hasOwn(descriptor, 'writable')); + return result; }; +var find = /[!'()~]|%20/g; -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +var replacements = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+' +}; -var isObject = __webpack_require__(40); +var replacer = function (match) { + return replacements[match]; +}; -module.exports = function (argument) { - return isObject(argument) || argument === null; +var serialize = function (it) { + return replace(encodeURIComponent(it), find, replacer); }; +var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { + setInternalState(this, { + type: URL_SEARCH_PARAMS_ITERATOR, + target: getInternalParamsState(params).entries, + index: 0, + kind: kind + }); +}, URL_SEARCH_PARAMS, function next() { + var state = getInternalIteratorState(this); + var target = state.target; + var index = state.index++; + if (!target || index >= target.length) { + state.target = null; + return createIterResultObject(undefined, true); + } + var entry = target[index]; + switch (state.kind) { + case 'keys': return createIterResultObject(entry.key, false); + case 'values': return createIterResultObject(entry.value, false); + } return createIterResultObject([entry.key, entry.value], false); +}, true); -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { +var URLSearchParamsState = function (init) { + this.entries = []; + this.url = null; -"use strict"; + if (init !== undefined) { + if (isObject(init)) this.parseObject(init); + else this.parseQuery(typeof init == 'string' ? charAt(init, 0) === '?' ? stringSlice(init, 1) : init : $toString(init)); + } +}; -var uncurryThis = __webpack_require__(34); +URLSearchParamsState.prototype = { + type: URL_SEARCH_PARAMS, + bindURL: function (url) { + this.url = url; + this.update(); + }, + parseObject: function (object) { + var entries = this.entries; + var iteratorMethod = getIteratorMethod(object); + var iterator, next, step, entryIterator, entryNext, first, second; -// eslint-disable-next-line es/no-map -- safe -var MapPrototype = Map.prototype; + if (iteratorMethod) { + iterator = getIterator(object, iteratorMethod); + next = iterator.next; + while (!(step = call(next, iterator)).done) { + entryIterator = getIterator(anObject(step.value)); + entryNext = entryIterator.next; + if ( + (first = call(entryNext, entryIterator)).done || + (second = call(entryNext, entryIterator)).done || + !call(entryNext, entryIterator).done + ) throw new TypeError('Expected sequence with length 2'); + push(entries, { key: $toString(first.value), value: $toString(second.value) }); + } + } else for (var key in object) if (hasOwn(object, key)) { + push(entries, { key: key, value: $toString(object[key]) }); + } + }, + parseQuery: function (query) { + if (query) { + var entries = this.entries; + var attributes = split(query, '&'); + var index = 0; + var attribute, entry; + while (index < attributes.length) { + attribute = attributes[index++]; + if (attribute.length) { + entry = split(attribute, '='); + push(entries, { + key: decode(shift(entry)), + value: decode(join(entry, '=')) + }); + } + } + } + }, + serialize: function () { + var entries = this.entries; + var result = []; + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + push(result, serialize(entry.key) + '=' + serialize(entry.value)); + } return join(result, '&'); + }, + update: function () { + this.entries.length = 0; + this.parseQuery(this.url.query); + }, + updateURL: function () { + if (this.url) this.url.update(); + } +}; -module.exports = { - // eslint-disable-next-line es/no-map -- safe - Map: Map, - set: uncurryThis(MapPrototype.set), - get: uncurryThis(MapPrototype.get), - has: uncurryThis(MapPrototype.has), - remove: uncurryThis(MapPrototype['delete']), - proto: MapPrototype +// `URLSearchParams` constructor +// https://url.spec.whatwg.org/#interface-urlsearchparams +var URLSearchParamsConstructor = function URLSearchParams(/* init */) { + anInstance(this, URLSearchParamsPrototype); + var init = arguments.length > 0 ? arguments[0] : undefined; + var state = setInternalState(this, new URLSearchParamsState(init)); + if (!DESCRIPTORS) this.size = state.entries.length; }; +var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { +defineBuiltIns(URLSearchParamsPrototype, { + // `URLSearchParams.prototype.append` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-append + append: function append(name, value) { + var state = getInternalParamsState(this); + validateArgumentsLength(arguments.length, 2); + push(state.entries, { key: $toString(name), value: $toString(value) }); + if (!DESCRIPTORS) this.length++; + state.updateURL(); + }, + // `URLSearchParams.prototype.delete` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-delete + 'delete': function (name /* , value */) { + var state = getInternalParamsState(this); + var length = validateArgumentsLength(arguments.length, 1); + var entries = state.entries; + var key = $toString(name); + var $value = length < 2 ? undefined : arguments[1]; + var value = $value === undefined ? $value : $toString($value); + var index = 0; + while (index < entries.length) { + var entry = entries[index]; + if (entry.key === key && (value === undefined || entry.value === value)) { + splice(entries, index, 1); + if (value !== undefined) break; + } else index++; + } + if (!DESCRIPTORS) this.size = entries.length; + state.updateURL(); + }, + // `URLSearchParams.prototype.get` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-get + get: function get(name) { + var entries = getInternalParamsState(this).entries; + validateArgumentsLength(arguments.length, 1); + var key = $toString(name); + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) return entries[index].value; + } + return null; + }, + // `URLSearchParams.prototype.getAll` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-getall + getAll: function getAll(name) { + var entries = getInternalParamsState(this).entries; + validateArgumentsLength(arguments.length, 1); + var key = $toString(name); + var result = []; + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) push(result, entries[index].value); + } + return result; + }, + // `URLSearchParams.prototype.has` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-has + has: function has(name /* , value */) { + var entries = getInternalParamsState(this).entries; + var length = validateArgumentsLength(arguments.length, 1); + var key = $toString(name); + var $value = length < 2 ? undefined : arguments[1]; + var value = $value === undefined ? $value : $toString($value); + var index = 0; + while (index < entries.length) { + var entry = entries[index++]; + if (entry.key === key && (value === undefined || entry.value === value)) return true; + } + return false; + }, + // `URLSearchParams.prototype.set` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-set + set: function set(name, value) { + var state = getInternalParamsState(this); + validateArgumentsLength(arguments.length, 1); + var entries = state.entries; + var found = false; + var key = $toString(name); + var val = $toString(value); + var index = 0; + var entry; + for (; index < entries.length; index++) { + entry = entries[index]; + if (entry.key === key) { + if (found) splice(entries, index--, 1); + else { + found = true; + entry.value = val; + } + } + } + if (!found) push(entries, { key: key, value: val }); + if (!DESCRIPTORS) this.size = entries.length; + state.updateURL(); + }, + // `URLSearchParams.prototype.sort` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-sort + sort: function sort() { + var state = getInternalParamsState(this); + arraySort(state.entries, function (a, b) { + return a.key > b.key ? 1 : -1; + }); + state.updateURL(); + }, + // `URLSearchParams.prototype.forEach` method + forEach: function forEach(callback /* , thisArg */) { + var entries = getInternalParamsState(this).entries; + var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined); + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + boundFunction(entry.value, entry.key, this); + } + }, + // `URLSearchParams.prototype.keys` method + keys: function keys() { + return new URLSearchParamsIterator(this, 'keys'); + }, + // `URLSearchParams.prototype.values` method + values: function values() { + return new URLSearchParamsIterator(this, 'values'); + }, + // `URLSearchParams.prototype.entries` method + entries: function entries() { + return new URLSearchParamsIterator(this, 'entries'); + } +}, { enumerable: true }); -"use strict"; +// `URLSearchParams.prototype[@@iterator]` method +defineBuiltIn(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries, { name: 'entries' }); -var sign = __webpack_require__(192); -var roundTiesToEven = __webpack_require__(253); +// `URLSearchParams.prototype.toString` method +// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior +defineBuiltIn(URLSearchParamsPrototype, 'toString', function toString() { + return getInternalParamsState(this).serialize(); +}, { enumerable: true }); -var abs = Math.abs; +// `URLSearchParams.prototype.size` getter +// https://github.com/whatwg/url/pull/734 +if (DESCRIPTORS) defineBuiltInAccessor(URLSearchParamsPrototype, 'size', { + get: function size() { + return getInternalParamsState(this).entries.length; + }, + configurable: true, + enumerable: true +}); -var EPSILON = 2.220446049250313e-16; // Number.EPSILON +setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); -module.exports = function (x, FLOAT_EPSILON, FLOAT_MAX_VALUE, FLOAT_MIN_VALUE) { - var n = +x; - var absolute = abs(n); - var s = sign(n); - if (absolute < FLOAT_MIN_VALUE) return s * roundTiesToEven(absolute / FLOAT_MIN_VALUE / FLOAT_EPSILON) * FLOAT_MIN_VALUE * FLOAT_EPSILON; - var a = (1 + FLOAT_EPSILON / EPSILON) * absolute; - var result = a - (a - absolute); - // eslint-disable-next-line no-self-compare -- NaN check - if (result > FLOAT_MAX_VALUE || result !== result) return s * Infinity; - return s * result; -}; +$({ global: true, constructor: true, forced: !USE_NATIVE_URL }, { + URLSearchParams: URLSearchParamsConstructor +}); +// Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams` +if (!USE_NATIVE_URL && isCallable(Headers)) { + var headersHas = uncurryThis(HeadersPrototype.has); + var headersSet = uncurryThis(HeadersPrototype.set); -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { + var wrapRequestOptions = function (init) { + if (isObject(init)) { + var body = init.body; + var headers; + if (classof(body) === URL_SEARCH_PARAMS) { + headers = init.headers ? new Headers(init.headers) : new Headers(); + if (!headersHas(headers, 'content-type')) { + headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + return create(init, { + body: createPropertyDescriptor(0, $toString(body)), + headers: createPropertyDescriptor(0, headers) + }); + } + } return init; + }; -"use strict"; + if (isCallable(nativeFetch)) { + $({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, { + fetch: function fetch(input /* , init */) { + return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); + } + }); + } -var floatRound = __webpack_require__(248); + if (isCallable(NativeRequest)) { + var RequestConstructor = function Request(input /* , init */) { + anInstance(this, RequestPrototype); + return new NativeRequest(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); + }; -var FLOAT32_EPSILON = 1.1920928955078125e-7; // 2 ** -23; -var FLOAT32_MAX_VALUE = 3.4028234663852886e+38; // 2 ** 128 - 2 ** 104 -var FLOAT32_MIN_VALUE = 1.1754943508222875e-38; // 2 ** -126; + RequestPrototype.constructor = RequestConstructor; + RequestConstructor.prototype = RequestPrototype; -// `Math.fround` method implementation -// https://tc39.es/ecma262/#sec-math.fround -// eslint-disable-next-line es/no-math-fround -- safe -module.exports = Math.fround || function fround(x) { - return floatRound(x, FLOAT32_EPSILON, FLOAT32_MAX_VALUE, FLOAT32_MIN_VALUE); + $({ global: true, constructor: true, dontCallGetSet: true, forced: true }, { + Request: RequestConstructor + }); + } +} + +module.exports = { + URLSearchParams: URLSearchParamsConstructor, + getState: getInternalParamsState }; /***/ }), -/* 250 */ +/* 258 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var log = Math.log; -var LOG10E = Math.LOG10E; -// eslint-disable-next-line es/no-math-log10 -- safe -module.exports = Math.log10 || function log10(x) { - return log(x) * LOG10E; -}; +/** +* FUNCTION: isArray( value ) +* Validates if a value is an array. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is an array +*/ +function isArray( value ) { + return Object.prototype.toString.call( value ) === '[object Array]'; +} // end FUNCTION isArray() +// EXPORTS // -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = Array.isArray || isArray; -"use strict"; -var log = Math.log; +/***/ }), +/* 259 */ +/***/ (function(module, exports) { -// `Math.log1p` method implementation -// https://tc39.es/ecma262/#sec-math.log1p -// eslint-disable-next-line es/no-math-log1p -- safe -module.exports = Math.log1p || function log1p(x) { - var n = +x; - return n > -1e-8 && n < 1e-8 ? n - n * n / 2 : log(1 + n); -}; +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; /***/ }), -/* 252 */ +/* 260 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var log = Math.log; -var LN2 = Math.LN2; - -// `Math.log2` method -// https://tc39.es/ecma262/#sec-math.log2 -// eslint-disable-next-line es/no-math-log2 -- safe -module.exports = Math.log2 || function log2(x) { - return log(x) / LN2; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +/** + * Iquizeles color generator + * @module lib/color.js; + */ -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { +var palettes = [[[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.0, 0.33, 0.67]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.0, 0.1, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.3, 0.2, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 1.0, 0.5], [0.8, 0.9, 0.3]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1.0, 0.7, 0.4], [0.0, 0.15, 0.2]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [2.0, 1.0, 0.0], [0.5, 0.2, 0.25]], [[0.8, 0.5, 0.4], [0.2, 0.4, 0.2], [2.0, 1.0, 1.0], [0.0, 0.25, 0.25]]]; -"use strict"; +var palette = palettes[0]; -var EPSILON = 2.220446049250313e-16; // Number.EPSILON -var INVERSE_EPSILON = 1 / EPSILON; +function channel(t, a, b, c, d, add, mul) { + return a + b * Math.cos(2 * Math.PI * (c * t + d)) * mul + add; +} -module.exports = function (n) { - return n + INVERSE_EPSILON - INVERSE_EPSILON; -}; +function color(t, add, mul) { + var a = void 0, + b = void 0, + c = void 0, + d = void 0; + var rgb = []; + for (var i = 0; i < 3; i++) { + a = palette[0][i]; + b = palette[1][i]; + c = palette[2][i]; + d = palette[3][i]; + rgb[i] = Math.round(channel(-t, a, b, c, d, add, mul) * 255); + } + return "rgb(" + rgb + ")"; +} +exports.default = color; /***/ }), -/* 254 */ +/* 261 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ceil = Math.ceil; -var floor = Math.floor; -// `Math.trunc` method -// https://tc39.es/ecma262/#sec-math.trunc -// eslint-disable-next-line es/no-math-trunc -- safe -module.exports = Math.trunc || function trunc(x) { - var n = +x; - return (n > 0 ? floor : ceil)(n); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _tone = __webpack_require__(108); -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { +var _tone2 = _interopRequireDefault(_tone); -"use strict"; +var _util = __webpack_require__(143); -var globalThis = __webpack_require__(35); -var safeGetBuiltIn = __webpack_require__(268); -var bind = __webpack_require__(75); -var macrotask = __webpack_require__(167).set; -var Queue = __webpack_require__(265); -var IS_IOS = __webpack_require__(232); -var IS_IOS_PEBBLE = __webpack_require__(296); -var IS_WEBOS_WEBKIT = __webpack_require__(297); -var IS_NODE = __webpack_require__(111); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var MutationObserver = globalThis.MutationObserver || globalThis.WebKitMutationObserver; -var document = globalThis.document; -var process = globalThis.process; -var Promise = globalThis.Promise; -var microtask = safeGetBuiltIn('queueMicrotask'); -var notify, toggle, node, promise, then; +/** + * Kalimba + * @module lib/kalimba.js; + */ -// modern engines have queueMicrotask method -if (!microtask) { - var queue = new Queue(); +var player_count = 4; - var flush = function () { - var parent, fn; - if (IS_NODE && (parent = process.domain)) parent.exit(); - while (fn = queue.get()) try { - fn(); - } catch (error) { - if (queue.head) notify(); - throw error; +var samples = [{ root: 219.5, fn: "samples/380737__cabled-mess__sansula-01-a-raw.wav" }, { root: 260.9, fn: "samples/380736__cabled-mess__sansula-02-c-raw.wav" }, { root: 330.2, fn: "samples/380735__cabled-mess__sansula-03-e-raw.wav" }]; + +function load(_ref) { + var output = _ref.output; + + samples.forEach(function (sample) { + sample.players = []; + sample.index = -1; + for (var i = 0; i < player_count; i++) { + var fn = sample.fn; + if (window.location.href.match(/asdf.us/)) { + fn = "//asdf.us/kalimba/" + fn.replace("wav", "mp3"); + } + var player = new _tone2.default.Player({ + url: fn, + retrigger: true, + playbackRate: 1 + }); + player.name = fn; + var gain = new _tone2.default.Gain(1.6); + player.connect(gain); + gain.connect(output); + sample.players.push(player); } - if (parent) parent.enter(); - }; + }); + console.log("+ Voices:", samples.reduce(function (count, sample) { + return count + sample.players.length; + }, 0)); +} - // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 - // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898 - if (!IS_IOS && !IS_NODE && !IS_WEBOS_WEBKIT && MutationObserver && document) { - toggle = true; - node = document.createTextNode(''); - new MutationObserver(flush).observe(node, { characterData: true }); - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (!IS_IOS_PEBBLE && Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - promise = Promise.resolve(undefined); - // workaround of WebKit ~ iOS Safari 10.1 bug - promise.constructor = Promise; - then = bind(promise.then, promise); - notify = function () { - then(flush); - }; - // Node.js without promises - } else if (IS_NODE) { - notify = function () { - process.nextTick(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessage - // - onreadystatechange - // - setTimeout - } else { - // `webpack` dev server bug on IE global methods - use bind(fn, global) - macrotask = bind(macrotask, globalThis); - notify = function () { - macrotask(flush); - }; - } +function play(interval, root) { + var sample = (0, _util.choice)(samples); + sample.index = (sample.index + 1) % sample.players.length; - microtask = function (fn) { - if (!queue.head) notify(); - queue.add(fn); - }; + var player = sample.players[sample.index]; + player.playbackRate = interval * root / sample.root; + player.start(); } -module.exports = microtask; +function pause() { + // no-op +} + +exports.default = { load: load, play: play, pause: pause }; +// for help tuning the kalimba samples +// function keydown(e) { +// // console.log(e.keyCode) +// if (e.metaKey && last) { +// let step = e.shiftKey ? (e.ctrlKey ? 0.01 : 0.1) : 1; +// switch (e.keyCode) { +// case 38: // up +// e.preventDefault(); +// samples[0].root -= step; +// play(last); +// break; +// case 40: // down +// e.preventDefault(); +// samples[0].root += step; +// play(last); +// break; +// } +// console.log(samples[0].root); +// } +// } +// window.addEventListener("keydown", keydown, true); /***/ }), -/* 256 */ +/* 262 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $RangeError = RangeError; -module.exports = function (it) { - // eslint-disable-next-line no-self-compare -- NaN check - if (it === it) return it; - throw new $RangeError('NaN is not allowed'); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +/** + * Keyboard helper + * @module lib/keys.js; + */ +var keys = {}; +var key_numbers = {}; +var letters = "zxcvbnmasdfghjklqwertyuiop"; +var numbers = "1234567890"; -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { +var callback = function callback() {}; -"use strict"; +letters.toUpperCase().split("").map(function (k, i) { + keys[k.charCodeAt(0)] = i; +}); -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); -var trim = __webpack_require__(124).trim; -var whitespaces = __webpack_require__(138); +numbers.split("").map(function (k, i) { + keys[k.charCodeAt(0)] = i + letters.length; + key_numbers[k.charCodeAt(0)] = true; +}); -var charAt = uncurryThis(''.charAt); -var $parseFloat = globalThis.parseFloat; -var Symbol = globalThis.Symbol; -var ITERATOR = Symbol && Symbol.iterator; -var FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity - // MS Edge 18- broken with boxed symbols - || (ITERATOR && !fails(function () { $parseFloat(Object(ITERATOR)); })); +window.addEventListener("keydown", keydown, true); +function keydown(e) { + if (e.altKey || e.ctrlKey || e.metaKey) { + e.stopPropagation(); + return; + } + if (document.activeElement instanceof HTMLInputElement && e.keyCode in key_numbers) { + e.stopPropagation(); + return; + } + if (!(e.keyCode in keys)) return; + var index = keys[e.keyCode]; + if (e.shiftKey) index += letters.length; + callback(index); +} -// `parseFloat` method -// https://tc39.es/ecma262/#sec-parsefloat-string -module.exports = FORCED ? function parseFloat(string) { - var trimmedString = trim(toString(string)); - var result = $parseFloat(trimmedString); - return result === 0 && charAt(trimmedString, 0) === '-' ? -0 : result; -} : $parseFloat; +function listen(fn) { + callback = fn; +} +exports.default = { listen: listen }; /***/ }), -/* 258 */ +/* 263 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); -var trim = __webpack_require__(124).trim; -var whitespaces = __webpack_require__(138); -var $parseInt = globalThis.parseInt; -var Symbol = globalThis.Symbol; -var ITERATOR = Symbol && Symbol.iterator; -var hex = /^[+-]?0x/i; -var exec = uncurryThis(hex.exec); -var FORCED = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22 - // MS Edge 18- broken with boxed symbols - || (ITERATOR && !fails(function () { $parseInt(Object(ITERATOR)); })); +Object.defineProperty(exports, "__esModule", { + value: true +}); -// `parseInt` method -// https://tc39.es/ecma262/#sec-parseint-string-radix -module.exports = FORCED ? function parseInt(string, radix) { - var S = trim(toString(string)); - return $parseInt(S, (radix >>> 0) || (exec(hex, S) ? 16 : 10)); -} : $parseInt; +var _webmidi = __webpack_require__(637); + +function enable(play) { + _webmidi.WebMidi.enable().then(onEnabled).catch(function (error) { + return console.error(error); + }); + + // Function triggered when WEBMIDI.js is ready + function onEnabled() { + // Display available MIDI input devices + if (_webmidi.WebMidi.inputs.length < 1) { + console.log("No device detected."); + return; + } else { + _webmidi.WebMidi.inputs.forEach(function (device, index) { + document.body.innerHTML += index + ": " + device.name + "
"; + }); + var mySynth = _webmidi.WebMidi.inputs[0]; + // const mySynth = WebMidi.getInputByName("TYPE NAME HERE!") + + mySynth.channels[1].addListener("noteon", function (event) { + console.log(event.note); + }); + } + } +} /** + * MIDI + * @module midi.js; + */ +exports.default = { enable: enable }; /***/ }), -/* 259 */ +/* 264 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var uncurryThis = __webpack_require__(34); -var call = __webpack_require__(36); -var fails = __webpack_require__(33); -var objectKeys = __webpack_require__(134); -var getOwnPropertySymbolsModule = __webpack_require__(155); -var propertyIsEnumerableModule = __webpack_require__(156); -var toObject = __webpack_require__(47); -var IndexedObject = __webpack_require__(115); -// eslint-disable-next-line es/no-object-assign -- safe -var $assign = Object.assign; -// eslint-disable-next-line es/no-object-defineproperty -- required for testing -var defineProperty = Object.defineProperty; -var concat = uncurryThis([].concat); +Object.defineProperty(exports, "__esModule", { + value: true +}); -// `Object.assign` method -// https://tc39.es/ecma262/#sec-object.assign -module.exports = !$assign || fails(function () { - // should have correct order of operations (Edge bug) - if (DESCRIPTORS && $assign({ b: 1 }, $assign(defineProperty({}, 'a', { - enumerable: true, - get: function () { - defineProperty(this, 'b', { - value: 3, - enumerable: false - }); - } - }), { b: 2 })).b !== 1) return true; - // should work with symbols and should have deterministic property order (V8 bug) - var A = {}; - var B = {}; - // eslint-disable-next-line es/no-symbol -- safe - var symbol = Symbol('assign detection'); - var alphabet = 'abcdefghijklmnopqrst'; - A[symbol] = 7; - // eslint-disable-next-line es/no-array-prototype-foreach -- safe - alphabet.split('').forEach(function (chr) { B[chr] = chr; }); - return $assign({}, A)[symbol] !== 7 || objectKeys($assign({}, B)).join('') !== alphabet; -}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length` - var T = toObject(target); - var argumentsLength = arguments.length; - var index = 1; - var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; - var propertyIsEnumerable = propertyIsEnumerableModule.f; - while (argumentsLength > index) { - var S = IndexedObject(arguments[index++]); - var keys = getOwnPropertySymbols ? concat(objectKeys(S), getOwnPropertySymbols(S)) : objectKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) { - key = keys[j++]; - if (!DESCRIPTORS || call(propertyIsEnumerable, S, key)) T[key] = S[key]; - } - } return T; -} : $assign; +var _tone = __webpack_require__(108); +var _tone2 = _interopRequireDefault(_tone); -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { +var _util = __webpack_require__(143); -"use strict"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sine wave organ + * @module lib/organ.js; + */ -var uncurryThis = __webpack_require__(34); -var hasOwn = __webpack_require__(45); -var toIndexedObject = __webpack_require__(57); -var indexOf = __webpack_require__(127).indexOf; -var hiddenKeys = __webpack_require__(131); +var root = 440; -var push = uncurryThis([].push); +var oscillators = {}; +var output = void 0; +var lastPlayed = void 0; -module.exports = function (object, names) { - var O = toIndexedObject(object); - var i = 0; - var result = []; - var key; - for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key); - // Don't enum bug & hidden keys - while (names.length > i) if (hasOwn(O, key = names[i++])) { - ~indexOf(result, key) || push(result, key); +function load(out) { + output = out; +} +function isPlaying(interval) { + var rounded = (0, _util.roundInterval)(interval); + var osc = oscillators[rounded]; + return osc && osc.playing; +} +function play(interval) { + if (!output) { + return; } - return result; -}; - + var rounded = (0, _util.roundInterval)(interval); + var osc = oscillators[rounded] = oscillators[rounded] || {}; + if (!osc.el) { + osc.interval = interval; + osc.el = new _tone2.default.Oscillator(interval * root, "sine"); + osc.el.connect(output); + } + osc.el.start(); + osc.playing = true; + lastPlayed = osc; + return osc; +} -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { +function pause(interval) { + var rounded = (0, _util.roundInterval)(interval); + if (!oscillators[rounded]) return; + var osc = oscillators[rounded] = oscillators[rounded] || {}; + if (osc.el) { + osc.el.stop(); + } + osc.playing = false; + return osc; +} -"use strict"; +function setRoot(newRoot) { + root = newRoot; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -var DESCRIPTORS = __webpack_require__(38); -var fails = __webpack_require__(33); -var uncurryThis = __webpack_require__(34); -var objectGetPrototypeOf = __webpack_require__(67); -var objectKeys = __webpack_require__(134); -var toIndexedObject = __webpack_require__(57); -var $propertyIsEnumerable = __webpack_require__(156).f; + try { + for (var _iterator = Object.values(oscillators)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var osc = _step.value; -var propertyIsEnumerable = uncurryThis($propertyIsEnumerable); -var push = uncurryThis([].push); + osc.el.frequency.value = osc.interval * newRoot; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } +} +function stop() { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -// in some IE versions, `propertyIsEnumerable` returns incorrect result on integer keys -// of `null` prototype objects -var IE_BUG = DESCRIPTORS && fails(function () { - // eslint-disable-next-line es/no-object-create -- safe - var O = Object.create(null); - O[2] = 2; - return !propertyIsEnumerable(O, 2); -}); + try { + for (var _iterator2 = Object.values(oscillators)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var osc = _step2.value; -// `Object.{ entries, values }` methods implementation -var createMethod = function (TO_ENTRIES) { - return function (it) { - var O = toIndexedObject(it); - var keys = objectKeys(O); - var IE_WORKAROUND = IE_BUG && objectGetPrototypeOf(O) === null; - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) { - key = keys[i++]; - if (!DESCRIPTORS || (IE_WORKAROUND ? key in O : propertyIsEnumerable(O, key))) { - push(result, TO_ENTRIES ? [key, O[key]] : O[key]); + osc.el.stop(); + osc.el.disconnect(); + osc.playing = false; + delete osc.el; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; } } - return result; - }; -}; + } -module.exports = { - // `Object.entries` method - // https://tc39.es/ecma262/#sec-object.entries - entries: createMethod(true), - // `Object.values` method - // https://tc39.es/ecma262/#sec-object.values - values: createMethod(false) -}; + oscillators = {}; +} +exports.default = { load: load, isPlaying: isPlaying, play: play, pause: pause, stop: stop, setRoot: setRoot }; /***/ }), -/* 262 */ +/* 265 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); - -var $TypeError = TypeError; -// `OrdinaryToPrimitive` abstract operation -// https://tc39.es/ecma262/#sec-ordinarytoprimitive -module.exports = function (input, pref) { - var fn, val; - if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; - if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val; - if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; - throw new $TypeError("Can't convert object to primitive value"); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOutput = getOutput; +var _tone = __webpack_require__(108); -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { +var _tone2 = _interopRequireDefault(_tone); -"use strict"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var newPromiseCapability = __webpack_require__(90); +var output = null; /** + * Common output stage + * @module lib/output.js; + */ -module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; -}; +function getOutput() { + if (!output) output = makeOutput(); + return output; +} +function makeOutput() { + var compressor = new _tone2.default.Compressor(-30, 3); + var gain = new _tone2.default.Gain(0.3); + compressor.connect(gain); + gain.toMaster(); + + return compressor; +} /***/ }), -/* 264 */ +/* 266 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineProperty = __webpack_require__(51).f; -module.exports = function (Target, Source, key) { - key in Target || defineProperty(Target, key, { - configurable: true, - get: function () { return Source[key]; }, - set: function (it) { Source[key] = it; } - }); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.load = load; +exports.dragOver = dragOver; +exports.drop = drop; +exports.loadSampleFromFile = loadSampleFromFile; +var _tone = __webpack_require__(108); -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { +var _tone2 = _interopRequireDefault(_tone); -"use strict"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Queue = function () { - this.head = null; - this.tail = null; -}; +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** + * Sampler + * @module lib/sampler.js; + */ -Queue.prototype = { - add: function (item) { - var entry = { item: item, next: null }; - var tail = this.tail; - if (tail) tail.next = entry; - else this.head = entry; - this.tail = entry; - }, - get: function () { - var entry = this.head; - if (entry) { - var next = this.head = entry.next; - if (next === null) this.tail = null; - return entry.item; - } - } -}; +var root = 440; -module.exports = Queue; +var output = void 0; +var ready = void 0; +var current = ""; +var samples = {}; +var player_count = 12; -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { +function load(out, readyCallback) { + output = out; + ready = readyCallback; + document.body.addEventListener("dragover", dragOver); + document.body.addEventListener("drop", drop); +} -"use strict"; +/** + * Drag and drop + */ +function dragOver(event) { + event.preventDefault(); +} +function drop(event) { + event.preventDefault(); + var files = event.dataTransfer.items ? [].concat(_toConsumableArray(event.dataTransfer.items)).filter(function (item) { + return item.kind === "file"; + }).map(function (item) { + return item.getAsFile(); + }) : [].concat(_toConsumableArray(event.dataTransfer.files)); -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); + var file = files[0]; + var reader = new FileReader(); -// babel-minify and Closure Compiler transpiles RegExp('.', 'd') -> /./d and it causes SyntaxError -var RegExp = globalThis.RegExp; + reader.addEventListener("load", function () { + return loadSampleFromFile(file, reader.result); + }, false); -var FLAGS_GETTER_IS_CORRECT = !fails(function () { - var INDICES_SUPPORT = true; - try { - RegExp('.', 'd'); - } catch (error) { - INDICES_SUPPORT = false; + if (file) { + reader.readAsDataURL(file); } +} - var O = {}; - // modern V8 bug - var calls = ''; - var expected = INDICES_SUPPORT ? 'dgimsy' : 'gimsy'; +function loadSampleFromFile(file, url) { + var name = file.name; - var addGetter = function (key, chr) { - // eslint-disable-next-line es/no-object-defineproperty -- safe - Object.defineProperty(O, key, { get: function () { - calls += chr; - return true; - } }); - }; + current = name; - var pairs = { - dotAll: 's', - global: 'g', - ignoreCase: 'i', - multiline: 'm', - sticky: 'y' - }; + var sample = samples[name] = samples[name] || {}; + sample.root = 440; + sample.players = []; + sample.index = -1; + for (var i = 0; i < player_count; i++) { + var player = new _tone2.default.Player({ + url: url, + retrigger: true, + playbackRate: 1 + }); + player.name = name; + player.connect(output); + sample.players.push(player); + } + console.log("+ Sampler:", name, "(" + sample.players.length + " voices)"); + ready(); +} - if (INDICES_SUPPORT) pairs.hasIndices = 'd'; +/** + * Player + */ +var last = [1, 440]; - for (var key in pairs) addGetter(key, pairs[key]); +function stop() { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe - var result = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags').get.call(O); + try { + for (var _iterator = Object.values(samples)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var sample = _step.value; - return result !== expected || calls !== expected; -}); + sample.players.forEach(function (player) { + return player.stop(); + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } +} +function play(interval, root) { + last = [interval, root]; + var sample = samples[current]; + sample.index = (sample.index + 1) % sample.players.length; + var player = sample.players[sample.index]; + player.playbackRate = interval * root / sample.root; + player.start(); +} -module.exports = { correct: FLAGS_GETTER_IS_CORRECT }; +function pause() { + // no-op +} + +exports.default = { load: load, play: play, pause: pause, stop: stop }; + +// for help tuning +function keydown(e) { + // console.log(e.keyCode) + if (e.metaKey && last && current) { + var sample = samples[current]; + var step = e.shiftKey ? e.ctrlKey ? 0.1 : 1 : 10; + switch (e.keyCode) { + case 38: + // up + e.preventDefault(); + sample.root -= step; + stop(); + play(last[0], last[1]); + break; + case 40: + // down + e.preventDefault(); + sample.root += step; + stop(); + play(last[0], last[1]); + break; + } + } +} +window.addEventListener("keydown", keydown, true); /***/ }), /* 267 */ @@ -39361,18 +38105,73 @@ module.exports = { correct: FLAGS_GETTER_IS_CORRECT }; "use strict"; -var fails = __webpack_require__(33); -var globalThis = __webpack_require__(35); - -// babel-minify and Closure Compiler transpiles RegExp('(?
b)', 'g') -> /(?b)/g and it causes SyntaxError -var $RegExp = globalThis.RegExp; -module.exports = fails(function () { - var re = $RegExp('(?b)', 'g'); - return re.exec('b').groups.a !== 'b' || - 'b'.replace(re, '$c') !== 'bc'; +Object.defineProperty(exports, "__esModule", { + value: true }); +exports.scales = undefined; + +__webpack_require__(630); + +__webpack_require__(632); + +var _index = __webpack_require__(276); + +var a = void 0, + b = void 0; /** + * Scales + * @module client/lib/scales.js; + */ +var scales = exports.scales = [{ name: "natural", get: function get(i, j) { + return [i + 1, j + 1]; + } }, { name: "undertone", get: function get(i, j) { + return [i + 1, i + j + 2]; + } }, { name: "overtone", get: function get(i, j) { + return [i + j + 2, j + 1]; + } }, { + name: "primes", + reset: function reset(x, y, w, h) { + a = (0, _index.Prime)().skip(x).take(w).toJS(); + b = (0, _index.Prime)().skip(y).take(h).toJS(); + }, + get: function get(ii, jj, i, j) { + return [a[i], b[j]]; + } +}, { + name: "arithmetic", + reset: function reset(x, y, w, h) { + a = (0, _index.Arithmetic)(x + 1, x + 1).take(w).toJS(); + b = (0, _index.Arithmetic)(y + 1, y + 1).take(h).toJS(); + console.log(a); + }, + get: function get(ii, jj, i, j) { + return [a[i], b[j]]; + } +}, +// { +// name: "triangle", +// reset: (x, y, w, h) => { +// a = Triangle().skip(x).take(w).toJS(); +// b = Triangle().skip(y).take(h).toJS(); +// }, +// get: (ii, jj, i, j) => [a[i], b[j]], +// }, +{ + name: "collatz", + reset: function reset(x, y, w, h) { + a = (0, _index.Collatz)(x + 1).take(w).toJS(); + b = (0, _index.Collatz)(y + 1).take(h).toJS(); + }, + get: function get(ii, jj, i, j) { + return [a[i], b[j]]; + } +}, { + name: "pythagorean", + get: function get(i, j) { + return i < j ? [Math.pow(3, i + 1), Math.pow(2, j + Math.ceil(Math.max(0, i * 1.0 / 2)))] : [Math.pow(2, i + Math.ceil(Math.max(0, j * 1.2 / 2))), Math.pow(3, j)]; + } +}]; /***/ }), /* 268 */ @@ -39380,1039 +38179,1533 @@ module.exports = fails(function () { "use strict"; -var globalThis = __webpack_require__(35); -var DESCRIPTORS = __webpack_require__(38); - -// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe -var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; -// Avoid NodeJS experimental warning -module.exports = function (name) { - if (!DESCRIPTORS) return globalThis[name]; - var descriptor = getOwnPropertyDescriptor(globalThis, name); - return descriptor && descriptor.value; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +/* + oktransition.add({ + obj: el.style, + units: "px", + from: { left: 0 }, + to: { left: 100 }, + duration: 1000, + easing: oktransition.easing.circ_out, + update: function(obj){ + console.log(obj.left) + } + finished: function(){ + console.log("done") + } + }) +*/ +var oktransition = {}; +var transitions = []; -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { +var last_t = 0; +var id = 0; -"use strict"; +var lerp = function lerp(n, a, b) { + return (b - a) * n + a; +}; -// `SameValue` abstract operation -// https://tc39.es/ecma262/#sec-samevalue -// eslint-disable-next-line es/no-object-is -- safe -module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare -- NaN check - return x === y ? x !== 0 || 1 / x === 1 / y : x !== x && y !== y; +oktransition.speed = 1; +oktransition.add = function (transition) { + transition.id = id++; + transition.obj = transition.obj || {}; + if (transition.easing) { + if (typeof transition.easing === "string") { + transition.easing = oktransition.easing[transition.easing]; + } + } else { + transition.easing = oktransition.easing.linear; + } + if (!("from" in transition) && !("to" in transition)) { + transition.keys = []; + } else if (!("from" in transition)) { + transition.from = {}; + transition.keys = Object.keys(transition.to); + transition.keys.forEach(function (prop) { + transition.from[prop] = parseFloat(transition.obj[prop]); + }); + } else { + transition.keys = Object.keys(transition.from); + } + transition.delay = transition.delay || 0; + transition.start = last_t + transition.delay; + transition.done = false; + transition.after = transition.after || []; + transition.then = function (fn) { + transition.after.push(fn); + return transition; + }; + transition.tick = 0; + transition.skip = transition.skip || 1; + transition.dt = 0; + transition.cancel = function () { + return transitions = transitions.filter(function (item) { + return item !== transition; + }); + }; + transitions.push(transition); + return transition; +}; +oktransition.update = function (t) { + var done = false; + requestAnimationFrame(oktransition.update); + last_t = t * oktransition.speed; + if (transitions.length === 0) return; + transitions.forEach(function (transition, i) { + var dt = Math.min(1.0, (t - transition.start) / transition.duration); + transition.tick++; + if (dt < 0 || dt < 1 && transition.tick % transition.skip != 0 || transition.done) return; + var ddt = transition.easing(dt); + transition.dt = ddt; + transition.keys.forEach(function (prop) { + var val = lerp(ddt, transition.from[prop], transition.to[prop]); + if (transition.round) val = Math.round(val); + if (transition.units) val = Math.round(val) + transition.units; + transition.obj[prop] = val; + }); + if (transition.update) { + transition.update(transition.obj, dt); + } + if (dt === 1) { + if (transition.finished) { + transition.finished(transition); + } + if (transition.after.length) { + var twn = transition.after.shift(); + twn.obj = twn.obj || transition.obj; + twn.after = transition.after; + oktransition.add(twn); + } + if (transition.loop) { + transition.start = t + transition.delay; + } else { + done = true; + transition.done = true; + } + } + }); + if (done) { + transitions = transitions.filter(function (transition) { + return !transition.done; + }); + } }; +requestAnimationFrame(oktransition.update); -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { +oktransition.easing = { + linear: function linear(t) { + return t; + }, + circ_out: function circ_out(t) { + return Math.sqrt(1 - (t = t - 1) * t); + }, + circ_in: function circ_in(t) { + return -(Math.sqrt(1 - t * t) - 1); + }, + circ_in_out: function circ_in_out(t) { + return (t *= 2) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); + }, + quad_in: function quad_in(n) { + return Math.pow(n, 2); + }, + quad_out: function quad_out(n) { + return n * (n - 2) * -1; + }, + quad_in_out: function quad_in_out(n) { + n = n * 2; + if (n < 1) { + return Math.pow(n, 2) / 2; + } + return -1 * (--n * (n - 2) - 1) / 2; + }, + cubic_bezier: function cubic_bezier(mX1, mY1, mX2, mY2) { + function A(aA1, aA2) { + return 1.0 - 3.0 * aA2 + 3.0 * aA1; + } + function B(aA1, aA2) { + return 3.0 * aA2 - 6.0 * aA1; + } + function C(aA1) { + return 3.0 * aA1; + } -"use strict"; + // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. + function CalcBezier(aT, aA1, aA2) { + return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; + } -// Should get iterator record of a set-like object before cloning this -// https://bugs.webkit.org/show_bug.cgi?id=289430 -module.exports = function (METHOD_NAME) { - try { - // eslint-disable-next-line es/no-set -- needed for test - var baseSet = new Set(); - var setLike = { - size: 0, - has: function () { return true; }, - keys: function () { - // eslint-disable-next-line es/no-object-defineproperty -- needed for test - return Object.defineProperty({}, 'next', { - get: function () { - baseSet.clear(); - baseSet.add(4); - return function () { - return { done: true }; - }; - } - }); + // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. + function GetSlope(aT, aA1, aA2) { + return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); + } + + function GetTForX(aX) { + // Newton raphson iteration + var aGuessT = aX; + for (var i = 0; i < 10; ++i) { + var currentSlope = GetSlope(aGuessT, mX1, mX2); + if (currentSlope == 0.0) return aGuessT; + var currentX = CalcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; } - }; - var result = baseSet[METHOD_NAME](setLike); + return aGuessT; + } - return result.size !== 1 || result.values().next().value !== 4; - } catch (error) { - return false; + return function (aX) { + if (mX1 == mY1 && mX2 == mY2) return aX; // linear + return CalcBezier(aX, mY1, mY2); + }; } }; +exports.default = oktransition; /***/ }), -/* 271 */ +/* 269 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// https://github.com/zloirock/core-js/issues/280 -var userAgent = __webpack_require__(83); -module.exports = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent); +// MODULES // +var isArray = __webpack_require__( 258 ), + isIntegerArray = __webpack_require__( 634 ), + isFunction = __webpack_require__( 633 ); -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +// VARIABLES // -var $trimEnd = __webpack_require__(124).end; -var forcedStringTrimMethod = __webpack_require__(203); +var MAXINT = Math.pow( 2, 31 ) - 1; -// `String.prototype.{ trimEnd, trimRight }` method -// https://tc39.es/ecma262/#sec-string.prototype.trimend -// https://tc39.es/ecma262/#String.prototype.trimright -module.exports = forcedStringTrimMethod('trimEnd') ? function trimEnd() { - return $trimEnd(this); -// eslint-disable-next-line es/no-string-prototype-trimstart-trimend -- safe -} : ''.trimEnd; +// FUNCTIONS // -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { +/** +* FUNCTION: gcd( a, b ) +* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm. +* +* @param {Number} a - integer +* @param {Number} b - integer +* @returns {Number} greatest common divisor +*/ +function gcd( a, b ) { + var k = 1, + t; + // Simple cases: + if ( a === 0 ) { + return b; + } + if ( b === 0 ) { + return a; + } + // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... + while ( a%2 === 0 && b%2 === 0 ) { + a = a / 2; // right shift + b = b / 2; // right shift + k = k * 2; // left shift + } + // Reduce `a` to an odd number... + while ( a%2 === 0 ) { + a = a / 2; // right shift + } + // Henceforth, `a` is always odd... + while ( b ) { + // Remove all factors of 2 in `b`, as they are not common... + while ( b%2 === 0 ) { + b = b / 2; // right shift + } + // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... + if ( a > b ) { + t = b; + b = a; + a = t; + } + b = b - a; // b=0 iff b=a + } + // Restore common factors of 2... + return k * a; +} // end FUNCTION gcd() -"use strict"; +/** +* FUNCTION: bitwise( a, b ) +* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm and bitwise operations. +* +* @param {Number} a - safe integer +* @param {Number} b - safe integer +* @returns {Number} greatest common divisor +*/ +function bitwise( a, b ) { + var k = 0, + t; + // Simple cases: + if ( a === 0 ) { + return b; + } + if ( b === 0 ) { + return a; + } + // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... + while ( (a & 1) === 0 && (b & 1) === 0 ) { + a >>>= 1; // right shift + b >>>= 1; // right shift + k++; + } + // Reduce `a` to an odd number... + while ( (a & 1) === 0 ) { + a >>>= 1; // right shift + } + // Henceforth, `a` is always odd... + while ( b ) { + // Remove all factors of 2 in `b`, as they are not common... + while ( (b & 1) === 0 ) { + b >>>= 1; // right shift + } + // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... + if ( a > b ) { + t = b; + b = a; + a = t; + } + b = b - a; // b=0 iff b=a + } + // Restore common factors of 2... + return a << k; +} // end FUNCTION bitwise() -var $trimStart = __webpack_require__(124).start; -var forcedStringTrimMethod = __webpack_require__(203); -// `String.prototype.{ trimStart, trimLeft }` method -// https://tc39.es/ecma262/#sec-string.prototype.trimstart -// https://tc39.es/ecma262/#String.prototype.trimleft -module.exports = forcedStringTrimMethod('trimStart') ? function trimStart() { - return $trimStart(this); -// eslint-disable-next-line es/no-string-prototype-trimstart-trimend -- safe -} : ''.trimStart; +// GREATEST COMMON DIVISOR // +/** +* FUNCTION: compute( arr[, clbk] ) +* Computes the greatest common divisor. +* +* @param {Number[]|Number} arr - input array of integers +* @param {Function|Number} [clbk] - accessor function for accessing array values +* @returns {Number|Null} greatest common divisor or null +*/ +function compute() { + var nargs = arguments.length, + args, + clbk, + arr, + len, + a, b, + i; -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { + // Copy the input arguments to an array... + args = new Array( nargs ); + for ( i = 0; i < nargs; i++ ) { + args[ i ] = arguments[ i ]; + } + // Have we been provided with integer arguments? + if ( isIntegerArray( args ) ) { + if ( nargs === 2 ) { + a = args[ 0 ]; + b = args[ 1 ]; + if ( a < 0 ) { + a = -a; + } + if ( b < 0 ) { + b = -b; + } + if ( a <= MAXINT && b <= MAXINT ) { + return bitwise( a, b ); + } else { + return gcd( a, b ); + } + } + arr = args; + } + // If not integers, ensure the first argument is an array... + else if ( !isArray( args[ 0 ] ) ) { + throw new TypeError( 'gcd()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' ); + } + // Have we been provided with more than one argument? If so, ensure that the accessor argument is a function... + else if ( nargs > 1 ) { + arr = args[ 0 ]; + clbk = args[ 1 ]; + if ( !isFunction( clbk ) ) { + throw new TypeError( 'gcd()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' ); + } + } + // We have been provided an array... + else { + arr = args[ 0 ]; + } + len = arr.length; -"use strict"; + // Check if a sufficient number of values have been provided... + if ( len < 2 ) { + return null; + } + // If an accessor is provided, extract the array values... + if ( clbk ) { + a = new Array( len ); + for ( i = 0; i < len; i++ ) { + a[ i ] = clbk( arr[ i ], i ); + } + arr = a; + } + // Given an input array, ensure all array values are integers... + if ( nargs < 3 ) { + if ( !isIntegerArray( arr ) ) { + throw new TypeError( 'gcd()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' ); + } + } + // Convert any negative integers to positive integers... + for ( i = 0; i < len; i++ ) { + a = arr[ i ]; + if ( a < 0 ) { + arr[ i ] = -a; + } + } + // Exploit the fact that the gcd is an associative function... + a = arr[ 0 ]; + for ( i = 1; i < len; i++ ) { + b = arr[ i ]; + if ( b <= MAXINT && a <= MAXINT ) { + a = bitwise( a, b ); + } else { + a = gcd( a, b ); + } + } + return a; +} // end FUNCTION compute() -var call = __webpack_require__(36); -var getBuiltIn = __webpack_require__(43); -var wellKnownSymbol = __webpack_require__(39); -var defineBuiltIn = __webpack_require__(49); -module.exports = function () { - var Symbol = getBuiltIn('Symbol'); - var SymbolPrototype = Symbol && Symbol.prototype; - var valueOf = SymbolPrototype && SymbolPrototype.valueOf; - var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); +// EXPORTS // - if (SymbolPrototype && !SymbolPrototype[TO_PRIMITIVE]) { - // `Symbol.prototype[@@toPrimitive]` method - // https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive - // eslint-disable-next-line no-unused-vars -- required for .length - defineBuiltIn(SymbolPrototype, TO_PRIMITIVE, function (hint) { - return call(valueOf, this); - }, { arity: 1 }); - } -}; +module.exports = compute; /***/ }), -/* 275 */ +/* 270 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NATIVE_SYMBOL = __webpack_require__(125); -/* eslint-disable es/no-symbol -- safe */ -module.exports = NATIVE_SYMBOL && !!Symbol['for'] && !!Symbol.keyFor; +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /** + * Lambdoma Triangle + * @module index.js; + */ +var _computeGcd = __webpack_require__(269); -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { +var _computeGcd2 = _interopRequireDefault(_computeGcd); -"use strict"; +var _keys = __webpack_require__(262); -var toPositiveInteger = __webpack_require__(206); +var _keys2 = _interopRequireDefault(_keys); -var $RangeError = RangeError; +var _color = __webpack_require__(260); -module.exports = function (it, BYTES) { - var offset = toPositiveInteger(it); - if (offset % BYTES) throw new $RangeError('Wrong offset'); - return offset; -}; +var _color2 = _interopRequireDefault(_color); +var _kalimba = __webpack_require__(261); -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { +var _kalimba2 = _interopRequireDefault(_kalimba); -"use strict"; +var _sampler = __webpack_require__(266); -var bind = __webpack_require__(75); -var call = __webpack_require__(36); -var aConstructor = __webpack_require__(173); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var getIterator = __webpack_require__(114); -var getIteratorMethod = __webpack_require__(99); -var isArrayIteratorMethod = __webpack_require__(187); -var isBigIntArray = __webpack_require__(244); -var aTypedArrayConstructor = __webpack_require__(44).aTypedArrayConstructor; -var toBigInt = __webpack_require__(205); +var _sampler2 = _interopRequireDefault(_sampler); -module.exports = function from(source /* , mapfn, thisArg */) { - var C = aConstructor(this); - var O = toObject(source); - var argumentsLength = arguments.length; - var mapfn = argumentsLength > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iteratorMethod = getIteratorMethod(O); - var i, length, result, thisIsBigIntArray, value, step, iterator, next; - if (iteratorMethod && !isArrayIteratorMethod(iteratorMethod)) { - iterator = getIterator(O, iteratorMethod); - next = iterator.next; - O = []; - while (!(step = call(next, iterator)).done) { - O.push(step.value); - } - } - if (mapping && argumentsLength > 2) { - mapfn = bind(mapfn, arguments[2]); - } - length = lengthOfArrayLike(O); - result = new (aTypedArrayConstructor(C))(length); - thisIsBigIntArray = isBigIntArray(result); - for (i = 0; length > i; i++) { - value = mapping ? mapfn(O[i], i) : O[i]; - // FF30- typed arrays doesn't properly convert objects to typed array values - result[i] = thisIsBigIntArray ? toBigInt(value) : +value; - } - return result; -}; +var _organ = __webpack_require__(264); +var _organ2 = _interopRequireDefault(_organ); -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { +var _midi = __webpack_require__(263); -"use strict"; +var _midi2 = _interopRequireDefault(_midi); -/* eslint-disable es/no-symbol -- required for testing */ -var NATIVE_SYMBOL = __webpack_require__(125); +var _oktransition = __webpack_require__(268); -module.exports = NATIVE_SYMBOL && - !Symbol.sham && - typeof Symbol.iterator == 'symbol'; +var _oktransition2 = _interopRequireDefault(_oktransition); +var _output = __webpack_require__(265); -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { +var _util = __webpack_require__(143); -"use strict"; +var _scales = __webpack_require__(267); -var DESCRIPTORS = __webpack_require__(38); -var fails = __webpack_require__(33); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// V8 ~ Chrome 36- -// https://bugs.chromium.org/p/v8/issues/detail?id=3334 -module.exports = DESCRIPTORS && fails(function () { - // eslint-disable-next-line es/no-object-defineproperty -- required for testing - return Object.defineProperty(function () { /* empty */ }, 'prototype', { - value: 42, - writable: false - }).prototype !== 42; +var instrument = _kalimba2.default; + +var grid = document.createElement("grid"); +var root = 440; +var s = 50; +var w = void 0, + h = void 0, + ws = void 0, + hs = void 0; + +var add_on = 0; +var mul_on = 1.0; +var add_off = 0.1; +var mul_off = 0.9; + +var dragging = false; +var erasing = false; +var lastNote = 0; +var notes = []; +var base_x = 0; +var base_y = 0; +var scaleMode = 0; +var is_split = false; +var intervals = void 0; + +(0, _util.requestAudioContext)(function () { + var output = (0, _output.getOutput)(); + document.body.appendChild(grid); + _kalimba2.default.load(output); + _organ2.default.load(output); + _sampler2.default.load(output, function ready() { + instrument = _sampler2.default; + }); + build(); + bind(); }); +function build() { + w = window.innerWidth; + h = window.innerHeight; + ws = Math.ceil(w / s); + hs = Math.ceil(h / s); + var scale = _scales.scales[scaleMode % _scales.scales.length]; + if (scale.reset) { + scale.reset(Math.round(base_x), Math.round(base_y), ws, hs); + } + for (var i = 0; i < ws; i++) { + notes[i] = []; + for (var j = 0; j < hs; j++) { + notes[i][j] = add(i, j); + } + } + log(); +} +function rebuild() { + notes.forEach(function (row) { + return row.forEach(function (note) { + return note.destroy(); + }); + }); + build(); +} +function log() { + var seen = {}; + // console.log(notes); + for (var i = 0; i < 8; i++) { + for (var j = 0; j < 8; j++) { + var interval = notes[i][j].interval; + var rounded = (0, _util.roundInterval)(interval); + if (!seen[rounded] && (0, _util.intervalInRange)(interval, root)) { + seen[rounded] = notes[i][j].interval; + } + } + } + intervals = Object.values(seen).sort(function (a, b) { + return a - b; + }); + // console.log(intervals); + console.log(intervals.length, "unique intervals in 8x8"); +} +function play(note) { + if (!_organ2.default.isPlaying(note.interval)) { + var interval = note.interval; + // while (interval < root) { + // interval *= 2; + // } + // while (interval > root) { + // interval /= 2; + // } + var rounded = (0, _util.roundInterval)(note.interval); + _organ2.default.play(interval); + notes.forEach(function (row) { + return row.forEach(function (note) { + return note.rounded === rounded && note.div.classList.add("playing"); + }); + }); + } +} +function trigger(note) { + if ((0, _util.intervalInRange)(note.interval, root)) { + instrument.play(note.interval, root); + } +} +function trigger_index(index) { + var interval = intervals[index]; + if (interval) { + instrument.play(interval, root); + } +} +function pause(note) { + _organ2.default.pause(note.interval); + var rounded = (0, _util.roundInterval)(note.interval); + notes.forEach(function (row) { + return row.forEach(function (note) { + return note.rounded === rounded && note.div.classList.remove("playing"); + }); + }); +} +function toggle(note) { + if (_organ2.default.isPlaying(note.rounded) || note.div.classList.contains("playing")) { + pause(note); + } else { + play(note); + } +} + +function add(i, j) { + var ii = i + Math.round(base_x); + var jj = j + Math.round(base_y); + + var scale = _scales.scales[scaleMode % _scales.scales.length]; + + var _scale$get = scale.get(ii, jj, i, j, Math.round(base_x), Math.round(base_y)), + _scale$get2 = _slicedToArray(_scale$get, 2), + a = _scale$get2[0], + b = _scale$get2[1]; + + var div = document.createElement("div"); + var interval = a / b; + // const interval = root * Math.pow(2, ((b / a) % 1) + 1); + var add = 0; + var frac = void 0; + div.style.left = i * s + "px"; + div.style.top = j * s + "px"; + + var note = { + interval: interval, + rounded: (0, _util.roundInterval)(interval, root), + div: div, + i: i, + j: j, + playing: false, + destroy: function destroy() { + div.parentNode && div.parentNode.removeChild(div); + }, + recolor: function recolor(numerator, denominator) { + var aa = a / numerator; + var bb = b / denominator; + if (aa < bb) { + add = -Math.log(bb / aa) / 3.5; + } else { + add = Math.log(aa / bb) / 6; + } + var a_inv = a * denominator; + var b_inv = b * numerator; + var ba_gcd = (0, _computeGcd2.default)(a_inv, b_inv); + var a_disp = a_inv / ba_gcd; + var b_disp = b_inv / ba_gcd; + + frac = Math.log2(aa / bb) % 1; + var frac_orig = Math.log2(a / b) % 1; + if (frac < 0) { + frac += 1; + } + if (frac_orig < 0) { + frac += 1; + } + if (frac_orig === 0) { + div.style.fontWeight = "900"; + } else { + div.style.fontWeight = "500"; + } + + div.innerHTML = "
" + a_disp + "
/
" + b_disp + "
"; + if (note.playing) { + div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); + } else { + div.style.backgroundColor = (0, _color2.default)(frac, add + add_off, mul_off); + } -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { + if (_organ2.default.isPlaying(interval)) { + div.classList.add("playing"); + } + } + }; -"use strict"; + note.recolor(1, 1); -var globalThis = __webpack_require__(35); -var isCallable = __webpack_require__(46); + if (_util.browser.isDesktop) { + div.addEventListener("mousedown", function (event) { + if (event.button === 2) { + // rightclick + event.preventDefault(); + // notes.forEach((row) => row.forEach((note) => note.recolor(a, b))); + is_split = [a, b]; + toggle(note); + return; + } + div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); + dragging = true; + trigger(note); + }); + div.addEventListener("mouseenter", function () { + div.style.backgroundColor = (0, _color2.default)(frac, add + add_on, mul_on); + if (dragging) { + trigger(note); + } + }); + div.addEventListener("mouseleave", function () { + div.style.backgroundColor = (0, _color2.default)(frac, add + add_off, mul_off); + }); + div.addEventListener("contextmenu", function (event) { + if (!event.ctrlKey || !event.metaKey || !event.altKey) { + event.preventDefault(); + } + }); + } else { + div.addEventListener("touchstart", function (e) { + e.preventDefault(); + trigger(note); + // erasing = !note.playing; + dragging = true; + lastNote = note; + }); + } + grid.appendChild(div); + return note; +} -var WeakMap = globalThis.WeakMap; +function bind() { + if (_util.browser.isDesktop) { + document.addEventListener("mousedown", function (event) { + if (event.button !== 2) { + dragging = true; + } + }); + document.addEventListener("mouseup", function () { + dragging = false; + }); + } else { + document.addEventListener("touchstart", function (e) { + e.preventDefault(); + dragging = true; + }); + document.addEventListener("touchmove", function (e) { + e.preventDefault(); + var x = Math.floor(e.touches[0].pageX / s); + var y = Math.floor(e.touches[0].pageY / s); + if (!(x in notes) || !(y in notes[x])) return; + var note = notes[x][y]; + if (note !== lastNote) { + if (dragging) { + trigger(note); + } + lastNote = note; + } + }); + document.addEventListener("touchend", function () { + dragging = false; + }); + } + window.addEventListener("resize", build); + window.addEventListener("keydown", keydown, true); + _keys2.default.listen(trigger_index); + document.querySelector("#help .close").addEventListener("click", function () { + return document.querySelector("#help").classList.remove("visible"); + }); + document.querySelector("#help-button").addEventListener("click", function () { + return document.querySelector("#help").classList.toggle("visible"); + }); + if (_util.browser.isDesktop) { + grid.addEventListener("wheel", function (e) { + var new_base_x = Math.max(0, base_x + e.deltaX / 32); + var new_base_y = Math.max(0, base_y + e.deltaY / 32); + if (Math.round(base_x) !== Math.round(new_base_x) || Math.round(base_y) !== Math.round(new_base_y)) { + base_x = new_base_x; + base_y = new_base_y; + rebuild(); + } else { + base_x = new_base_x; + base_y = new_base_y; + } + }); + } +} -module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap)); +var isReset = false; +function keydown(e) { + var step = 1; + if (e.shiftKey) { + step += 4; + } + console.log(e.keyCode); + switch (e.keyCode) { + case 27: + // esc - PANIC + if (isReset) { + base_x = 0; + base_y = 0; + showMessage("reset!"); + } + _organ2.default.stop(); + _sampler2.default.stop(); + rebuild(); + isReset = true; + setTimeout(function () { + return isReset = false; + }, 500); + break; + case 37: + // left + if (e.altKey || e.ctrlKey || e.metaKey) return; + base_x = Math.max(0, base_x - step); + rebuild(); + break; + case 38: + // up + if (e.altKey || e.ctrlKey || e.metaKey) return; + base_y = Math.max(0, base_y - step); + rebuild(); + break; + case 39: + // right + if (e.altKey || e.ctrlKey || e.metaKey) return; + base_x += step; + rebuild(); + break; + case 40: + // down + if (e.altKey || e.ctrlKey || e.metaKey) return; + base_y += step; + rebuild(); + break; + case 220: + // \ + _midi2.default.enable(trigger_index); + break; + case 191: + // ? + document.querySelector("#help").classList.toggle("visible"); + break; + case 189: + // - + e.preventDefault(); + if (e.altKey || e.metaKey) { + root = (0, _util.clamp)(root - (e.shiftKey ? 10 : 1), 1, 200000); + _organ2.default.setRoot(root); + showMessage("Root: " + root + " hz"); + } else { + scaleMode = (0, _util.mod)(scaleMode - 1, _scales.scales.length); + rebuild(); + showMessage(_scales.scales[scaleMode].name); + } + break; + case 187: + // = + e.preventDefault(); + if (e.altKey || e.metaKey) { + root = (0, _util.clamp)(root + (e.shiftKey ? 10 : 1), 1, 200000); + _organ2.default.setRoot(root); + showMessage("Root: " + root + " hz"); + } else { + scaleMode = (0, _util.mod)(scaleMode + 1, _scales.scales.length); + rebuild(); + showMessage(_scales.scales[scaleMode].name); + } + break; + } +} +var messageTransition = void 0; +function showMessage(message) { + var el = document.getElementById("message"); + el.innerHTML = message; + el.style.opacity = 1; + if (messageTransition) { + messageTransition.cancel(); + } + messageTransition = _oktransition2.default.add({ + obj: el.style, + from: { opacity: 1 }, + to: { opacity: 0 }, + delay: 1500, + duration: 2000, + easing: _oktransition2.default.easing.circ_out + }); +} /***/ }), -/* 281 */ +/* 271 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; -var wellKnownSymbol = __webpack_require__(39); - -exports.f = wellKnownSymbol; - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -"use strict"; +/** + * StartAudioContext.js + * @author Yotam Mann + * @license http://opensource.org/licenses/MIT MIT License + * @copyright 2016 Yotam Mann + */ +(function (root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { + module.exports = factory(); + } else { + root.StartAudioContext = factory(); + } +})(undefined, function () { + /** + * The StartAudioContext object + */ + var StartAudioContext = { + /** + * The audio context passed in by the user + * @type {AudioContext} + */ + context: null, + /** + * The TapListeners bound to the elements + * @type {Array} + * @private + */ + _tapListeners: [], + /** + * Callbacks to invoke when the audio context is started + * @type {Array} + * @private + */ + _onStarted: [] + }; -var getBuiltIn = __webpack_require__(43); -var hasOwn = __webpack_require__(45); -var createNonEnumerableProperty = __webpack_require__(59); -var isPrototypeOf = __webpack_require__(68); -var setPrototypeOf = __webpack_require__(81); -var copyConstructorProperties = __webpack_require__(110); -var proxyAccessor = __webpack_require__(264); -var inheritIfRequired = __webpack_require__(101); -var normalizeStringArgument = __webpack_require__(118); -var installErrorCause = __webpack_require__(243); -var installErrorStack = __webpack_require__(185); -var DESCRIPTORS = __webpack_require__(38); -var IS_PURE = __webpack_require__(48); + /** + * Set the context + * @param {AudioContext} ctx + * @returns {StartAudioContext} + */ + StartAudioContext.setContext = function (ctx) { + StartAudioContext.context = ctx; + return StartAudioContext; + }; -module.exports = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) { - var STACK_TRACE_LIMIT = 'stackTraceLimit'; - var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1; - var path = FULL_NAME.split('.'); - var ERROR_NAME = path[path.length - 1]; - var OriginalError = getBuiltIn.apply(null, path); + /** + * Add a tap listener to the audio context + * @param {Array|Element|String|jQuery} element + * @returns {StartAudioContext} + */ + StartAudioContext.on = function (element) { + if (Array.isArray(element) || NodeList && element instanceof NodeList) { + for (var i = 0; i < element.length; i++) { + StartAudioContext.on(element[i]); + } + } else if (typeof element === "string") { + StartAudioContext.on(document.querySelectorAll(element)); + } else if (element.jquery && typeof element.toArray === "function") { + StartAudioContext.on(element.toArray()); + } else if (Element && element instanceof Element) { + //if it's an element, create a TapListener + var tap = new TapListener(element, onTap); + StartAudioContext._tapListeners.push(tap); + } + return StartAudioContext; + }; - if (!OriginalError) return; + /** + * Bind a callback to when the audio context is started. + * @param {Function} cb + * @return {StartAudioContext} + */ + StartAudioContext.onStarted = function (cb) { + //if it's already started, invoke the callback + if (StartAudioContext.isStarted()) { + cb(); + } else { + StartAudioContext._onStarted.push(cb); + } + return StartAudioContext; + }; - var OriginalErrorPrototype = OriginalError.prototype; + /** + * returns true if the context is started + * @return {Boolean} + */ + StartAudioContext.isStarted = function () { + return StartAudioContext.context !== null && StartAudioContext.context.state === "running"; + }; - // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006 - if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause; + /** + * @class Listens for non-dragging tap ends on the given element + * @param {Element} element + * @internal + */ + var TapListener = function TapListener(element) { + this._dragged = false; - if (!FORCED) return OriginalError; + this._element = element; - var BaseError = getBuiltIn('Error'); + this._bindedMove = this._moved.bind(this); + this._bindedEnd = this._ended.bind(this); - var WrappedError = wrapper(function (a, b) { - var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined); - var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError(); - if (message !== undefined) createNonEnumerableProperty(result, 'message', message); - installErrorStack(result, WrappedError, result.stack, 2); - if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError); - if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]); - return result; - }); + element.addEventListener("touchmove", this._bindedMove); + element.addEventListener("touchend", this._bindedEnd); + element.addEventListener("mouseup", this._bindedEnd); + }; - WrappedError.prototype = OriginalErrorPrototype; + /** + * drag move event + */ + TapListener.prototype._moved = function (e) { + this._dragged = true; + }; - if (ERROR_NAME !== 'Error') { - if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError); - else copyConstructorProperties(WrappedError, BaseError, { name: true }); - } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) { - proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT); - proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace'); - } + /** + * tap ended listener + */ + TapListener.prototype._ended = function (e) { + if (!this._dragged) { + onTap(); + } + this._dragged = false; + }; - copyConstructorProperties(WrappedError, OriginalError); + /** + * remove all the bound events + */ + TapListener.prototype.dispose = function () { + this._element.removeEventListener("touchmove", this._bindedMove); + this._element.removeEventListener("touchend", this._bindedEnd); + this._element.removeEventListener("mouseup", this._bindedEnd); + this._bindedMove = null; + this._bindedEnd = null; + this._element = null; + }; - if (!IS_PURE) try { - // Safari 13- bug: WebAssembly errors does not have a proper `.name` - if (OriginalErrorPrototype.name !== ERROR_NAME) { - createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME); + /** + * Invoked the first time of the elements is tapped. + * Creates a silent oscillator when a non-dragging touchend + * event has been triggered. + */ + function onTap() { + //start the audio context with a silent oscillator + if (StartAudioContext.context && !StartAudioContext.isStarted()) { + var osc = StartAudioContext.context.createOscillator(); + var silent = StartAudioContext.context.createGain(); + silent.gain.value = 0; + osc.connect(silent); + silent.connect(StartAudioContext.context.destination); + var now = StartAudioContext.context.currentTime; + osc.start(now); + osc.stop(now + 0.5); } - OriginalErrorPrototype.constructor = WrappedError; - } catch (error) { /* empty */ } - return WrappedError; -}; + //dispose all the tap listeners + if (StartAudioContext._tapListeners) { + for (var i = 0; i < StartAudioContext._tapListeners.length; i++) { + StartAudioContext._tapListeners[i].dispose(); + } + StartAudioContext._tapListeners = null; + } + //the onstarted callbacks + if (StartAudioContext._onStarted) { + for (var j = 0; j < StartAudioContext._onStarted.length; j++) { + StartAudioContext._onStarted[j](); + } + StartAudioContext._onStarted = null; + } + } + return StartAudioContext; +}); /***/ }), -/* 283 */ +/* 272 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var apply = __webpack_require__(74); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var isCallable = __webpack_require__(46); -var isSymbol = __webpack_require__(104); -var arraySlice = __webpack_require__(78); -var getReplacerFunction = __webpack_require__(299); -var NATIVE_SYMBOL = __webpack_require__(125); - -var $String = String; -var $stringify = getBuiltIn('JSON', 'stringify'); -var exec = uncurryThis(/./.exec); -var charAt = uncurryThis(''.charAt); -var charCodeAt = uncurryThis(''.charCodeAt); -var replace = uncurryThis(''.replace); -var numberToString = uncurryThis(1.1.toString); - -var tester = /[\uD800-\uDFFF]/g; -var low = /^[\uD800-\uDBFF]$/; -var hi = /^[\uDC00-\uDFFF]$/; - -var WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails(function () { - var symbol = getBuiltIn('Symbol')('stringify detection'); - // MS Edge converts symbol values to JSON as {} - return $stringify([symbol]) !== '[null]' - // WebKit converts symbol values to JSON as null - || $stringify({ a: symbol }) !== '{}' - // V8 throws on boxed symbols - || $stringify(Object(symbol)) !== '{}'; -}); -// https://github.com/tc39/proposal-well-formed-stringify -var ILL_FORMED_UNICODE = fails(function () { - return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"' - || $stringify('\uDEAD') !== '"\\udead"'; -}); +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -var stringifyWithSymbolsFix = function (it, replacer) { - var args = arraySlice(arguments); - var $replacer = getReplacerFunction(replacer); - if (!isCallable($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined - args[1] = function (key, value) { - // some old implementations (like WebKit) could pass numbers as keys - if (isCallable($replacer)) value = call($replacer, this, $String(key), value); - if (!isSymbol(value)) return value; - }; - return apply($stringify, null, args); +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Arithmetic + * + * @param {*} start The number to start at + * @param {*} commonDifference The number to increment by each time + * + * Produces an arithmetic number sequence. Arithmetic number + * sequences are sequences which add or subtract a certain amount + * for each iteration. + */ +// Public API +exports.default = function (start, commonDifference) { + return (0, immutable_1.Seq)(generator(start, commonDifference)); }; +// Generator +function generator() { + var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var commonDifference = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -var fixIllFormed = function (match, offset, string) { - var prev = charAt(string, offset - 1); - var next = charAt(string, offset + 1); - if ((exec(low, match) && !exec(hi, next)) || (exec(hi, match) && !exec(low, prev))) { - return '\\u' + numberToString(charCodeAt(match, 0), 16); - } return match; -}; + case 2: + return _context.delegateYield(generator(current + commonDifference, commonDifference), "t0", 3); -if ($stringify) { - // `JSON.stringify` method - // https://tc39.es/ecma262/#sec-json.stringify - $({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE }, { - // eslint-disable-next-line no-unused-vars -- required for `.length` - stringify: function stringify(it, replacer, space) { - var args = arraySlice(arguments); - var result = apply(WRONG_SYMBOLS_CONVERSION ? stringifyWithSymbolsFix : $stringify, null, args); - return ILL_FORMED_UNICODE && typeof result == 'string' ? replace(result, tester, fixIllFormed) : result; + case 3: + case "end": + return _context.stop(); + } } - }); + }, _marked, this); } - +//# sourceMappingURL=arithmetic.js.map /***/ }), -/* 284 */ +/* 273 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toAbsoluteIndex = __webpack_require__(91); -var $RangeError = RangeError; -var fromCharCode = String.fromCharCode; -// eslint-disable-next-line es/no-string-fromcodepoint -- required for testing -var $fromCodePoint = String.fromCodePoint; -var join = uncurryThis([].join); +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -// length should be 1, old FF problem -var INCORRECT_LENGTH = !!$fromCodePoint && $fromCodePoint.length !== 1; +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Collatz + * + * @param {*} start The number to start at + * + * Produces the Collatz sequence for a given start number + * After (presumably) hitting 1, will loop infinitely on 1 -> 4 -> 2 -> 1 etc + */ +// Public API +exports.default = function (start) { + return (0, immutable_1.Seq)(generator(start)); +}; +// Generator +function generator(current) { + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -// `String.fromCodePoint` method -// https://tc39.es/ecma262/#sec-string.fromcodepoint -$({ target: 'String', stat: true, arity: 1, forced: INCORRECT_LENGTH }, { - // eslint-disable-next-line no-unused-vars -- required for `.length` - fromCodePoint: function fromCodePoint(x) { - var elements = []; - var length = arguments.length; - var i = 0; - var code; - while (length > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw new $RangeError(code + ' is not a valid code point'); - elements[i] = code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00); - } return join(elements, ''); - } -}); + case 2: + return _context.delegateYield(generator(current % 2 === 0 ? current / 2 : 3 * current + 1), "t0", 3); + case 3: + case "end": + return _context.stop(); + } + } + }, _marked, this); +} +//# sourceMappingURL=collatz.js.map /***/ }), -/* 285 */ +/* 274 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var charAt = __webpack_require__(164).charAt; -var toString = __webpack_require__(41); -var InternalStateModule = __webpack_require__(53); -var defineIterator = __webpack_require__(190); -var createIterResultObject = __webpack_require__(96); -var STRING_ITERATOR = 'String Iterator'; -var setInternalState = InternalStateModule.set; -var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -// `String.prototype[@@iterator]` method -// https://tc39.es/ecma262/#sec-string.prototype-@@iterator -defineIterator(String, 'String', function (iterated) { - setInternalState(this, { - type: STRING_ITERATOR, - string: toString(iterated), - index: 0 - }); -// `%StringIteratorPrototype%.next` method -// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next -}, function next() { - var state = getInternalState(this); - var string = state.string; - var index = state.index; - var point; - if (index >= string.length) return createIterResultObject(undefined, true); - point = charAt(string, index); - state.index += point.length; - return createIterResultObject(point, false); -}); +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Fibonacci + * + * Produces an Fibonacci number sequence. In Fibonacci number + * sequences, each number is the sum of the two preceding + * ones, starting from 0 and 1. + */ +// Public API +exports.default = function () { + return (0, immutable_1.Seq)(generator()); +}; +// Generator +function generator() { + var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var next = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; + + case 2: + return _context.delegateYield(generator(next, current + next), "t0", 3); + case 3: + case "end": + return _context.stop(); + } + } + }, _marked, this); +} +//# sourceMappingURL=fibonacci.js.map /***/ }), -/* 286 */ +/* 275 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` -__webpack_require__(172); -__webpack_require__(284); -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var safeGetBuiltIn = __webpack_require__(268); -var getBuiltIn = __webpack_require__(43); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var DESCRIPTORS = __webpack_require__(38); -var USE_NATIVE_URL = __webpack_require__(171); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltInAccessor = __webpack_require__(55); -var defineBuiltIns = __webpack_require__(88); -var setToStringTag = __webpack_require__(70); -var createIteratorConstructor = __webpack_require__(189); -var InternalStateModule = __webpack_require__(53); -var anInstance = __webpack_require__(71); -var isCallable = __webpack_require__(46); -var hasOwn = __webpack_require__(45); -var bind = __webpack_require__(75); -var classof = __webpack_require__(79); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var $toString = __webpack_require__(41); -var create = __webpack_require__(62); -var createPropertyDescriptor = __webpack_require__(73); -var getIterator = __webpack_require__(114); -var getIteratorMethod = __webpack_require__(99); -var createIterResultObject = __webpack_require__(96); -var validateArgumentsLength = __webpack_require__(80); -var wellKnownSymbol = __webpack_require__(39); -var arraySort = __webpack_require__(177); - -var ITERATOR = wellKnownSymbol('iterator'); -var URL_SEARCH_PARAMS = 'URLSearchParams'; -var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; -var setInternalState = InternalStateModule.set; -var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS); -var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR); - -var nativeFetch = safeGetBuiltIn('fetch'); -var NativeRequest = safeGetBuiltIn('Request'); -var Headers = safeGetBuiltIn('Headers'); -var RequestPrototype = NativeRequest && NativeRequest.prototype; -var HeadersPrototype = Headers && Headers.prototype; -var TypeError = globalThis.TypeError; -var encodeURIComponent = globalThis.encodeURIComponent; -var fromCharCode = String.fromCharCode; -var fromCodePoint = getBuiltIn('String', 'fromCodePoint'); -var $parseInt = parseInt; -var charAt = uncurryThis(''.charAt); -var join = uncurryThis([].join); -var push = uncurryThis([].push); -var replace = uncurryThis(''.replace); -var shift = uncurryThis([].shift); -var splice = uncurryThis([].splice); -var split = uncurryThis(''.split); -var stringSlice = uncurryThis(''.slice); -var exec = uncurryThis(/./.exec); - -var plus = /\+/g; -var FALLBACK_REPLACER = '\uFFFD'; -var VALID_HEX = /^[0-9a-f]+$/i; - -var parseHexOctet = function (string, start) { - var substr = stringSlice(string, start, start + 2); - if (!exec(VALID_HEX, substr)) return NaN; - - return $parseInt(substr, 16); -}; - -var getLeadingOnes = function (octet) { - var count = 0; - for (var mask = 0x80; mask > 0 && (octet & mask) !== 0; mask >>= 1) { - count++; - } - return count; -}; - -var utf8Decode = function (octets) { - var codePoint = null; - switch (octets.length) { - case 1: - codePoint = octets[0]; - break; - case 2: - codePoint = (octets[0] & 0x1F) << 6 | (octets[1] & 0x3F); - break; - case 3: - codePoint = (octets[0] & 0x0F) << 12 | (octets[1] & 0x3F) << 6 | (octets[2] & 0x3F); - break; - case 4: - codePoint = (octets[0] & 0x07) << 18 | (octets[1] & 0x3F) << 12 | (octets[2] & 0x3F) << 6 | (octets[3] & 0x3F); - break; - } +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); - return codePoint > 0x10FFFF ? null : codePoint; +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Geometric + * + * @param {*} start The number to start at + * @param {*} commonRatio The number to multiply by each time + * + * Produces a geometric number sequence. Geometric number + * sequences are sequences which multiply or divide by a certain + * amount for each iteration. + */ +// Public API +exports.default = function (start, commonRatio) { + return (0, immutable_1.Seq)(generator(start, commonRatio)); }; +// Generator +function generator() { + var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var commonRatio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -var decode = function (input) { - input = replace(input, plus, ' '); - var length = input.length; - var result = ''; - var i = 0; - - while (i < length) { - var decodedChar = charAt(input, i); + case 2: + return _context.delegateYield(generator(current * commonRatio, commonRatio), "t0", 3); - if (decodedChar === '%') { - if (charAt(input, i + 1) === '%' || i + 3 > length) { - result += '%'; - i++; - continue; + case 3: + case "end": + return _context.stop(); } + } + }, _marked, this); +} +//# sourceMappingURL=geometric.js.map - var octet = parseHexOctet(input, i + 1); +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { - // eslint-disable-next-line no-self-compare -- NaN check - if (octet !== octet) { - result += decodedChar; - i++; - continue; - } +"use strict"; - i += 2; - var byteSequenceLength = getLeadingOnes(octet); - if (byteSequenceLength === 0) { - decodedChar = fromCharCode(octet); - } else { - if (byteSequenceLength === 1 || byteSequenceLength > 4) { - result += FALLBACK_REPLACER; - i++; - continue; - } +var __importDefault = undefined && undefined.__importDefault || function (mod) { + return mod && mod.__esModule ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NthPower = exports.Twin = exports.Triangle = exports.Prime = exports.Power = exports.Geometric = exports.Fibonacci = exports.Collatz = exports.Arithmetic = void 0; +var arithmetic_1 = __webpack_require__(272); +Object.defineProperty(exports, "Arithmetic", { enumerable: true, get: function get() { + return __importDefault(arithmetic_1).default; + } }); +var collatz_1 = __webpack_require__(273); +Object.defineProperty(exports, "Collatz", { enumerable: true, get: function get() { + return __importDefault(collatz_1).default; + } }); +var fibonacci_1 = __webpack_require__(274); +Object.defineProperty(exports, "Fibonacci", { enumerable: true, get: function get() { + return __importDefault(fibonacci_1).default; + } }); +var geometric_1 = __webpack_require__(275); +Object.defineProperty(exports, "Geometric", { enumerable: true, get: function get() { + return __importDefault(geometric_1).default; + } }); +var power_1 = __webpack_require__(278); +Object.defineProperty(exports, "Power", { enumerable: true, get: function get() { + return __importDefault(power_1).default; + } }); +var prime_1 = __webpack_require__(279); +Object.defineProperty(exports, "Prime", { enumerable: true, get: function get() { + return __importDefault(prime_1).default; + } }); +var triangle_1 = __webpack_require__(280); +Object.defineProperty(exports, "Triangle", { enumerable: true, get: function get() { + return __importDefault(triangle_1).default; + } }); +var twin_1 = __webpack_require__(281); +Object.defineProperty(exports, "Twin", { enumerable: true, get: function get() { + return __importDefault(twin_1).default; + } }); +var nthpower_1 = __webpack_require__(277); +Object.defineProperty(exports, "NthPower", { enumerable: true, get: function get() { + return __importDefault(nthpower_1).default; + } }); +//# sourceMappingURL=index.js.map - var octets = [octet]; - var sequenceIndex = 1; +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { - while (sequenceIndex < byteSequenceLength) { - i++; - if (i + 3 > length || charAt(input, i) !== '%') break; +"use strict"; - var nextByte = parseHexOctet(input, i + 1); - // eslint-disable-next-line no-self-compare -- NaN check - if (nextByte !== nextByte) { - i += 3; - break; - } - if (nextByte > 191 || nextByte < 128) break; +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); - push(octets, nextByte); - i += 2; - sequenceIndex++; - } +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Power + * + * Generate all the nth powers - e.g. all squares, all cubes etc + */ +// Public API +exports.default = function (n) { + return (0, immutable_1.Seq)(generator(n)); +}; +// Generator +function generator(n) { + var current = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var x; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; - if (octets.length !== byteSequenceLength) { - result += FALLBACK_REPLACER; - continue; - } + case 2: + x = Math.pow(Math.pow(current, 1 / n) + 1, n); + return _context.delegateYield(generator(n, x), "t0", 4); - var codePoint = utf8Decode(octets); - if (codePoint === null) { - result += FALLBACK_REPLACER; - } else { - decodedChar = fromCodePoint(codePoint); - } + case 4: + case "end": + return _context.stop(); } } + }, _marked, this); +} +//# sourceMappingURL=nthpower.js.map - result += decodedChar; - i++; - } +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { - return result; -}; +"use strict"; -var find = /[!'()~]|%20/g; -var replacements = { - '!': '%21', - "'": '%27', - '(': '%28', - ')': '%29', - '~': '%7E', - '%20': '+' -}; +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -var replacer = function (match) { - return replacements[match]; +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Power + * + * Given a number, find all it's positive powers. + * e.g. for 2 it would be 2, 4, 8, 16.... + * for 3 it would be 3, 9, 27, 81.... + */ +// Public API +exports.default = function (start) { + return (0, immutable_1.Seq)(generator(start)); }; +// Generator +function generator(current, initial) { + var x; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -var serialize = function (it) { - return replace(encodeURIComponent(it), find, replacer); -}; + case 2: + x = initial || current; + return _context.delegateYield(generator(current * x, x), "t0", 4); -var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { - setInternalState(this, { - type: URL_SEARCH_PARAMS_ITERATOR, - target: getInternalParamsState(params).entries, - index: 0, - kind: kind - }); -}, URL_SEARCH_PARAMS, function next() { - var state = getInternalIteratorState(this); - var target = state.target; - var index = state.index++; - if (!target || index >= target.length) { - state.target = null; - return createIterResultObject(undefined, true); - } - var entry = target[index]; - switch (state.kind) { - case 'keys': return createIterResultObject(entry.key, false); - case 'values': return createIterResultObject(entry.value, false); - } return createIterResultObject([entry.key, entry.value], false); -}, true); + case 4: + case "end": + return _context.stop(); + } + } + }, _marked, this); +} +//# sourceMappingURL=power.js.map -var URLSearchParamsState = function (init) { - this.entries = []; - this.url = null; +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { - if (init !== undefined) { - if (isObject(init)) this.parseObject(init); - else this.parseQuery(typeof init == 'string' ? charAt(init, 0) === '?' ? stringSlice(init, 1) : init : $toString(init)); - } -}; +"use strict"; -URLSearchParamsState.prototype = { - type: URL_SEARCH_PARAMS, - bindURL: function (url) { - this.url = url; - this.update(); - }, - parseObject: function (object) { - var entries = this.entries; - var iteratorMethod = getIteratorMethod(object); - var iterator, next, step, entryIterator, entryNext, first, second; - if (iteratorMethod) { - iterator = getIterator(object, iteratorMethod); - next = iterator.next; - while (!(step = call(next, iterator)).done) { - entryIterator = getIterator(anObject(step.value)); - entryNext = entryIterator.next; - if ( - (first = call(entryNext, entryIterator)).done || - (second = call(entryNext, entryIterator)).done || - !call(entryNext, entryIterator).done - ) throw new TypeError('Expected sequence with length 2'); - push(entries, { key: $toString(first.value), value: $toString(second.value) }); - } - } else for (var key in object) if (hasOwn(object, key)) { - push(entries, { key: key, value: $toString(object[key]) }); - } - }, - parseQuery: function (query) { - if (query) { - var entries = this.entries; - var attributes = split(query, '&'); - var index = 0; - var attribute, entry; - while (index < attributes.length) { - attribute = attributes[index++]; - if (attribute.length) { - entry = split(attribute, '='); - push(entries, { - key: decode(shift(entry)), - value: decode(join(entry, '=')) - }); - } - } - } - }, - serialize: function () { - var entries = this.entries; - var result = []; - var index = 0; - var entry; - while (index < entries.length) { - entry = entries[index++]; - push(result, serialize(entry.key) + '=' + serialize(entry.value)); - } return join(result, '&'); - }, - update: function () { - this.entries.length = 0; - this.parseQuery(this.url.query); - }, - updateURL: function () { - if (this.url) this.url.update(); - } +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); + +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Prime + * + * List of all primes starting from 2 + */ +// Check if any of the primes found so far are factors of n. If not, then n is prime, so return that, else repeat for next candidate +var findNextPrime = function findNextPrime(n, knownPrimes) { + var f = knownPrimes.find(function (p) { + return n % p === 0; + }); + return f ? findNextPrime(nextCandidate(n), knownPrimes) : n; }; - -// `URLSearchParams` constructor -// https://url.spec.whatwg.org/#interface-urlsearchparams -var URLSearchParamsConstructor = function URLSearchParams(/* init */) { - anInstance(this, URLSearchParamsPrototype); - var init = arguments.length > 0 ? arguments[0] : undefined; - var state = setInternalState(this, new URLSearchParamsState(init)); - if (!DESCRIPTORS) this.size = state.entries.length; +// Reduce computation time by only checking odd numbers - and therefore incrementing by 2 each time +// Only exception is the very first increment, because the first prime is 2, the only even prime +var nextCandidate = function nextCandidate(n) { + return n + (n === 2 ? 1 : 2); }; +// Public API +exports.default = function () { + return (0, immutable_1.Seq)(generator(2, (0, immutable_1.List)([2]))); +}; +// Generator +function generator(current) { + var prev = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, immutable_1.List)(); + var knownPrimes, nextPrime; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; + case 2: + knownPrimes = prev.push(current); + nextPrime = findNextPrime(nextCandidate(current), knownPrimes); + return _context.delegateYield(generator(nextPrime, knownPrimes), "t0", 5); -defineBuiltIns(URLSearchParamsPrototype, { - // `URLSearchParams.prototype.append` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-append - append: function append(name, value) { - var state = getInternalParamsState(this); - validateArgumentsLength(arguments.length, 2); - push(state.entries, { key: $toString(name), value: $toString(value) }); - if (!DESCRIPTORS) this.length++; - state.updateURL(); - }, - // `URLSearchParams.prototype.delete` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-delete - 'delete': function (name /* , value */) { - var state = getInternalParamsState(this); - var length = validateArgumentsLength(arguments.length, 1); - var entries = state.entries; - var key = $toString(name); - var $value = length < 2 ? undefined : arguments[1]; - var value = $value === undefined ? $value : $toString($value); - var index = 0; - while (index < entries.length) { - var entry = entries[index]; - if (entry.key === key && (value === undefined || entry.value === value)) { - splice(entries, index, 1); - if (value !== undefined) break; - } else index++; - } - if (!DESCRIPTORS) this.size = entries.length; - state.updateURL(); - }, - // `URLSearchParams.prototype.get` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-get - get: function get(name) { - var entries = getInternalParamsState(this).entries; - validateArgumentsLength(arguments.length, 1); - var key = $toString(name); - var index = 0; - for (; index < entries.length; index++) { - if (entries[index].key === key) return entries[index].value; - } - return null; - }, - // `URLSearchParams.prototype.getAll` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-getall - getAll: function getAll(name) { - var entries = getInternalParamsState(this).entries; - validateArgumentsLength(arguments.length, 1); - var key = $toString(name); - var result = []; - var index = 0; - for (; index < entries.length; index++) { - if (entries[index].key === key) push(result, entries[index].value); - } - return result; - }, - // `URLSearchParams.prototype.has` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-has - has: function has(name /* , value */) { - var entries = getInternalParamsState(this).entries; - var length = validateArgumentsLength(arguments.length, 1); - var key = $toString(name); - var $value = length < 2 ? undefined : arguments[1]; - var value = $value === undefined ? $value : $toString($value); - var index = 0; - while (index < entries.length) { - var entry = entries[index++]; - if (entry.key === key && (value === undefined || entry.value === value)) return true; - } - return false; - }, - // `URLSearchParams.prototype.set` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-set - set: function set(name, value) { - var state = getInternalParamsState(this); - validateArgumentsLength(arguments.length, 1); - var entries = state.entries; - var found = false; - var key = $toString(name); - var val = $toString(value); - var index = 0; - var entry; - for (; index < entries.length; index++) { - entry = entries[index]; - if (entry.key === key) { - if (found) splice(entries, index--, 1); - else { - found = true; - entry.value = val; + case 5: + case "end": + return _context.stop(); + } } - } - } - if (!found) push(entries, { key: key, value: val }); - if (!DESCRIPTORS) this.size = entries.length; - state.updateURL(); - }, - // `URLSearchParams.prototype.sort` method - // https://url.spec.whatwg.org/#dom-urlsearchparams-sort - sort: function sort() { - var state = getInternalParamsState(this); - arraySort(state.entries, function (a, b) { - return a.key > b.key ? 1 : -1; - }); - state.updateURL(); - }, - // `URLSearchParams.prototype.forEach` method - forEach: function forEach(callback /* , thisArg */) { - var entries = getInternalParamsState(this).entries; - var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined); - var index = 0; - var entry; - while (index < entries.length) { - entry = entries[index++]; - boundFunction(entry.value, entry.key, this); - } - }, - // `URLSearchParams.prototype.keys` method - keys: function keys() { - return new URLSearchParamsIterator(this, 'keys'); - }, - // `URLSearchParams.prototype.values` method - values: function values() { - return new URLSearchParamsIterator(this, 'values'); - }, - // `URLSearchParams.prototype.entries` method - entries: function entries() { - return new URLSearchParamsIterator(this, 'entries'); - } -}, { enumerable: true }); + }, _marked, this); +} +//# sourceMappingURL=prime.js.map -// `URLSearchParams.prototype[@@iterator]` method -defineBuiltIn(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries, { name: 'entries' }); +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { -// `URLSearchParams.prototype.toString` method -// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior -defineBuiltIn(URLSearchParamsPrototype, 'toString', function toString() { - return getInternalParamsState(this).serialize(); -}, { enumerable: true }); +"use strict"; -// `URLSearchParams.prototype.size` getter -// https://github.com/whatwg/url/pull/734 -if (DESCRIPTORS) defineBuiltInAccessor(URLSearchParamsPrototype, 'size', { - get: function size() { - return getInternalParamsState(this).entries.length; - }, - configurable: true, - enumerable: true -}); -setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -$({ global: true, constructor: true, forced: !USE_NATIVE_URL }, { - URLSearchParams: URLSearchParamsConstructor -}); +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Triangle + * + * The triangle number sequence - 1, 3, 6, 10, 15, 21 + * = 1, (1 + 2), (1 + 2 + 3) etc + */ +// Public API +exports.default = function () { + return (0, immutable_1.Seq)(generator(1)); +}; +// Generator +// The general formula for the nth triangle number is n*(n + 1)/2 +// If the current number is x, then x = n*(n + 1)/2 +// and so with a bit of algebra and the quadratic formula (only taking the positive answer) +// n = (1 + 8*x)^(1/2)/2 +// So we can work out from the current value that it's the nth value, and then just +// add n + 1 to get the next term +// e.g. if current term is 10, then the above formula tells us it's the 4th term, +// so we add 5 to get the 5th term = 15 +function generator(current) { + var n; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return current; -// Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams` -if (!USE_NATIVE_URL && isCallable(Headers)) { - var headersHas = uncurryThis(HeadersPrototype.has); - var headersSet = uncurryThis(HeadersPrototype.set); + case 2: + n = (Math.sqrt(1 + 8 * current) - 1) / 2; + return _context.delegateYield(generator(current + n + 1), "t0", 4); - var wrapRequestOptions = function (init) { - if (isObject(init)) { - var body = init.body; - var headers; - if (classof(body) === URL_SEARCH_PARAMS) { - headers = init.headers ? new Headers(init.headers) : new Headers(); - if (!headersHas(headers, 'content-type')) { - headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); - } - return create(init, { - body: createPropertyDescriptor(0, $toString(body)), - headers: createPropertyDescriptor(0, headers) - }); + case 4: + case "end": + return _context.stop(); } - } return init; - }; + } + }, _marked, this); +} +//# sourceMappingURL=triangle.js.map - if (isCallable(nativeFetch)) { - $({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, { - fetch: function fetch(input /* , init */) { - return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); - } - }); - } +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { - if (isCallable(NativeRequest)) { - var RequestConstructor = function Request(input /* , init */) { - anInstance(this, RequestPrototype); - return new NativeRequest(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {}); - }; +"use strict"; - RequestPrototype.constructor = RequestConstructor; - RequestConstructor.prototype = RequestPrototype; - $({ global: true, constructor: true, dontCallGetSet: true, forced: true }, { - Request: RequestConstructor - }); - } -} +var _marked = /*#__PURE__*/regeneratorRuntime.mark(generator); -module.exports = { - URLSearchParams: URLSearchParamsConstructor, - getState: getInternalParamsState +Object.defineProperty(exports, "__esModule", { value: true }); +var immutable_1 = __webpack_require__(61); +/** + * Twin + * + * Given two sequences, interweave them, alternating terms + */ +// Public API +exports.default = function (a, b) { + return (0, immutable_1.Seq)(generator(a, b)); }; +// Generator +function generator(a, b) { + var counter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + return regeneratorRuntime.wrap(function generator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return counter % 2 === 0 ? a.first() : b.first(); + case 2: + return _context.delegateYield(generator(a, b, counter + 1), "t0", 3); + + case 3: + case "end": + return _context.stop(); + } + } + }, _marked, this); +} +//# sourceMappingURL=twin.js.map /***/ }), -/* 287 */ +/* 282 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var classof = __webpack_require__(79); +var classof = __webpack_require__(47); var $TypeError = TypeError; @@ -40423,7 +39716,7 @@ module.exports = function (argument) { /***/ }), -/* 288 */ +/* 283 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -40437,12 +39730,12 @@ module.exports = function (argument) { /***/ }), -/* 289 */ +/* 284 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isDetached = __webpack_require__(213); +var isDetached = __webpack_require__(184); var $TypeError = TypeError; @@ -40453,25 +39746,25 @@ module.exports = function (it) { /***/ }), -/* 290 */ +/* 285 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var bind = __webpack_require__(75); -var uncurryThis = __webpack_require__(34); -var toObject = __webpack_require__(47); -var isConstructor = __webpack_require__(103); -var getAsyncIterator = __webpack_require__(298); -var getIterator = __webpack_require__(114); -var getIteratorDirect = __webpack_require__(65); -var getIteratorMethod = __webpack_require__(99); -var getMethod = __webpack_require__(60); -var getBuiltIn = __webpack_require__(43); -var getBuiltInPrototypeMethod = __webpack_require__(238); -var wellKnownSymbol = __webpack_require__(39); -var AsyncFromSyncIterator = __webpack_require__(221); -var toArray = __webpack_require__(293).toArray; +var bind = __webpack_require__(43); +var uncurryThis = __webpack_require__(2); +var toObject = __webpack_require__(15); +var isConstructor = __webpack_require__(72); +var getAsyncIterator = __webpack_require__(293); +var getIterator = __webpack_require__(83); +var getIteratorDirect = __webpack_require__(33); +var getIteratorMethod = __webpack_require__(68); +var getMethod = __webpack_require__(28); +var getBuiltIn = __webpack_require__(11); +var getBuiltInPrototypeMethod = __webpack_require__(209); +var wellKnownSymbol = __webpack_require__(7); +var AsyncFromSyncIterator = __webpack_require__(192); +var toArray = __webpack_require__(288).toArray; var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); var arrayIterator = uncurryThis(getBuiltInPrototypeMethod('Array', 'values')); @@ -40511,15 +39804,15 @@ module.exports = function fromAsync(asyncItems /* , mapfn = undefined, thisArg = /***/ }), -/* 291 */ +/* 286 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isArray = __webpack_require__(93); -var isConstructor = __webpack_require__(103); -var isObject = __webpack_require__(40); -var wellKnownSymbol = __webpack_require__(39); +var isArray = __webpack_require__(62); +var isConstructor = __webpack_require__(72); +var isObject = __webpack_require__(8); +var wellKnownSymbol = __webpack_require__(7); var SPECIES = wellKnownSymbol('species'); var $Array = Array; @@ -40541,14 +39834,14 @@ module.exports = function (originalArray) { /***/ }), -/* 292 */ +/* 287 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var getBuiltIn = __webpack_require__(43); -var getMethod = __webpack_require__(60); +var call = __webpack_require__(4); +var getBuiltIn = __webpack_require__(11); +var getMethod = __webpack_require__(28); module.exports = function (iterator, method, argument, reject) { try { @@ -40567,21 +39860,21 @@ module.exports = function (iterator, method, argument, reject) { /***/ }), -/* 293 */ +/* 288 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-iterator-helpers // https://github.com/tc39/proposal-array-from-async -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var doesNotExceedSafeInteger = __webpack_require__(97); -var getBuiltIn = __webpack_require__(43); -var getIteratorDirect = __webpack_require__(65); -var closeAsyncIteration = __webpack_require__(292); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var doesNotExceedSafeInteger = __webpack_require__(66); +var getBuiltIn = __webpack_require__(11); +var getIteratorDirect = __webpack_require__(33); +var closeAsyncIteration = __webpack_require__(287); var createMethod = function (TYPE) { var IS_TO_ARRAY = TYPE === 0; @@ -40664,14 +39957,14 @@ module.exports = { /***/ }), -/* 294 */ +/* 289 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var padStart = __webpack_require__(165).start; +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var padStart = __webpack_require__(135).start; var $RangeError = RangeError; var $isFinite = isFinite; @@ -40712,13 +40005,13 @@ module.exports = (fails(function () { /***/ }), -/* 295 */ +/* 290 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var anObject = __webpack_require__(37); -var ordinaryToPrimitive = __webpack_require__(262); +var anObject = __webpack_require__(5); +var ordinaryToPrimitive = __webpack_require__(233); var $TypeError = TypeError; @@ -40733,40 +40026,40 @@ module.exports = function (hint) { /***/ }), -/* 296 */ +/* 291 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var userAgent = __webpack_require__(83); +var userAgent = __webpack_require__(51); module.exports = /ipad|iphone|ipod/i.test(userAgent) && typeof Pebble != 'undefined'; /***/ }), -/* 297 */ +/* 292 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var userAgent = __webpack_require__(83); +var userAgent = __webpack_require__(51); module.exports = /web0s(?!.*chrome)/i.test(userAgent); /***/ }), -/* 298 */ +/* 293 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var AsyncFromSyncIterator = __webpack_require__(221); -var anObject = __webpack_require__(37); -var getIterator = __webpack_require__(114); -var getIteratorDirect = __webpack_require__(65); -var getMethod = __webpack_require__(60); -var wellKnownSymbol = __webpack_require__(39); +var call = __webpack_require__(4); +var AsyncFromSyncIterator = __webpack_require__(192); +var anObject = __webpack_require__(5); +var getIterator = __webpack_require__(83); +var getIteratorDirect = __webpack_require__(33); +var getMethod = __webpack_require__(28); +var wellKnownSymbol = __webpack_require__(7); var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); @@ -40777,16 +40070,16 @@ module.exports = function (it, usingIterator) { /***/ }), -/* 299 */ +/* 294 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var isArray = __webpack_require__(93); -var isCallable = __webpack_require__(46); -var classof = __webpack_require__(64); -var toString = __webpack_require__(41); +var uncurryThis = __webpack_require__(2); +var isArray = __webpack_require__(62); +var isCallable = __webpack_require__(14); +var classof = __webpack_require__(32); +var toString = __webpack_require__(9); var push = uncurryThis([].push); @@ -40814,7 +40107,7 @@ module.exports = function (replacer) { /***/ }), -/* 300 */ +/* 295 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -40828,7 +40121,7 @@ module.exports = function (a, b) { /***/ }), -/* 301 */ +/* 296 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -40938,12 +40231,12 @@ module.exports = { /***/ }), -/* 302 */ +/* 297 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var iteratorClose = __webpack_require__(61); +var iteratorClose = __webpack_require__(29); module.exports = function (iters, kind, value) { for (var i = iters.length - 1; i >= 0; i--) { @@ -40961,12 +40254,12 @@ module.exports = function (iters, kind, value) { /***/ }), -/* 303 */ +/* 298 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); +var globalThis = __webpack_require__(3); var globalIsFinite = globalThis.isFinite; @@ -40979,13 +40272,13 @@ module.exports = Number.isFinite || function isFinite(it) { /***/ }), -/* 304 */ +/* 299 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var TO_STRING_TAG_SUPPORT = __webpack_require__(207); -var classof = __webpack_require__(79); +var TO_STRING_TAG_SUPPORT = __webpack_require__(178); +var classof = __webpack_require__(47); // `Object.prototype.toString` method implementation // https://tc39.es/ecma262/#sec-object.prototype.tostring @@ -40995,18 +40288,18 @@ module.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() { /***/ }), -/* 305 */ +/* 300 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var SetHelpers = __webpack_require__(82); -var clone = __webpack_require__(202); -var size = __webpack_require__(137); -var getSetRecord = __webpack_require__(100); -var iterateSet = __webpack_require__(121); -var iterateSimple = __webpack_require__(105); +var aSet = __webpack_require__(64); +var SetHelpers = __webpack_require__(50); +var clone = __webpack_require__(173); +var size = __webpack_require__(106); +var getSetRecord = __webpack_require__(69); +var iterateSet = __webpack_require__(90); +var iterateSimple = __webpack_require__(74); var has = SetHelpers.has; var remove = SetHelpers.remove; @@ -41028,17 +40321,17 @@ module.exports = function difference(other) { /***/ }), -/* 306 */ +/* 301 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var SetHelpers = __webpack_require__(82); -var size = __webpack_require__(137); -var getSetRecord = __webpack_require__(100); -var iterateSet = __webpack_require__(121); -var iterateSimple = __webpack_require__(105); +var aSet = __webpack_require__(64); +var SetHelpers = __webpack_require__(50); +var size = __webpack_require__(106); +var getSetRecord = __webpack_require__(69); +var iterateSet = __webpack_require__(90); +var iterateSimple = __webpack_require__(74); var Set = SetHelpers.Set; var add = SetHelpers.add; @@ -41066,18 +40359,18 @@ module.exports = function intersection(other) { /***/ }), -/* 307 */ +/* 302 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var has = __webpack_require__(82).has; -var size = __webpack_require__(137); -var getSetRecord = __webpack_require__(100); -var iterateSet = __webpack_require__(121); -var iterateSimple = __webpack_require__(105); -var iteratorClose = __webpack_require__(61); +var aSet = __webpack_require__(64); +var has = __webpack_require__(50).has; +var size = __webpack_require__(106); +var getSetRecord = __webpack_require__(69); +var iterateSet = __webpack_require__(90); +var iterateSimple = __webpack_require__(74); +var iteratorClose = __webpack_require__(29); // `Set.prototype.isDisjointFrom` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom @@ -41095,15 +40388,15 @@ module.exports = function isDisjointFrom(other) { /***/ }), -/* 308 */ +/* 303 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var size = __webpack_require__(137); -var iterate = __webpack_require__(121); -var getSetRecord = __webpack_require__(100); +var aSet = __webpack_require__(64); +var size = __webpack_require__(106); +var iterate = __webpack_require__(90); +var getSetRecord = __webpack_require__(69); // `Set.prototype.isSubsetOf` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf @@ -41118,17 +40411,17 @@ module.exports = function isSubsetOf(other) { /***/ }), -/* 309 */ +/* 304 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var has = __webpack_require__(82).has; -var size = __webpack_require__(137); -var getSetRecord = __webpack_require__(100); -var iterateSimple = __webpack_require__(105); -var iteratorClose = __webpack_require__(61); +var aSet = __webpack_require__(64); +var has = __webpack_require__(50).has; +var size = __webpack_require__(106); +var getSetRecord = __webpack_require__(69); +var iterateSimple = __webpack_require__(74); +var iteratorClose = __webpack_require__(29); // `Set.prototype.isSupersetOf` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf @@ -41144,16 +40437,16 @@ module.exports = function isSupersetOf(other) { /***/ }), -/* 310 */ +/* 305 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var SetHelpers = __webpack_require__(82); -var clone = __webpack_require__(202); -var getSetRecord = __webpack_require__(100); -var iterateSimple = __webpack_require__(105); +var aSet = __webpack_require__(64); +var SetHelpers = __webpack_require__(50); +var clone = __webpack_require__(173); +var getSetRecord = __webpack_require__(69); +var iterateSimple = __webpack_require__(74); var add = SetHelpers.add; var has = SetHelpers.has; @@ -41174,16 +40467,16 @@ module.exports = function symmetricDifference(other) { /***/ }), -/* 311 */ +/* 306 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var aSet = __webpack_require__(95); -var add = __webpack_require__(82).add; -var clone = __webpack_require__(202); -var getSetRecord = __webpack_require__(100); -var iterateSimple = __webpack_require__(105); +var aSet = __webpack_require__(64); +var add = __webpack_require__(50).add; +var clone = __webpack_require__(173); +var getSetRecord = __webpack_require__(69); +var iterateSimple = __webpack_require__(74); // `Set.prototype.union` method // https://github.com/tc39/proposal-set-methods @@ -41199,13 +40492,13 @@ module.exports = function union(other) { /***/ }), -/* 312 */ +/* 307 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js -var uncurryThis = __webpack_require__(34); +var uncurryThis = __webpack_require__(2); var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 var base = 36; @@ -41387,7 +40680,7 @@ module.exports = function (input) { /***/ }), -/* 313 */ +/* 308 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -41401,13 +40694,13 @@ module.exports = function (it) { /***/ }), -/* 314 */ +/* 309 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayFromConstructorAndList = __webpack_require__(142); -var getTypedArrayConstructor = __webpack_require__(44).getTypedArrayConstructor; +var arrayFromConstructorAndList = __webpack_require__(112); +var getTypedArrayConstructor = __webpack_require__(12).getTypedArrayConstructor; module.exports = function (instance, list) { return arrayFromConstructorAndList(getTypedArrayConstructor(instance), list); @@ -41415,16 +40708,16 @@ module.exports = function (instance, list) { /***/ }), -/* 315 */ +/* 310 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var apply = __webpack_require__(74); -var fails = __webpack_require__(33); -var wrapErrorConstructorWithCause = __webpack_require__(282); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var apply = __webpack_require__(42); +var fails = __webpack_require__(1); +var wrapErrorConstructorWithCause = __webpack_require__(253); var AGGREGATE_ERROR = 'AggregateError'; var $AggregateError = getBuiltIn(AGGREGATE_ERROR); @@ -41445,24 +40738,24 @@ $({ global: true, constructor: true, arity: 2, forced: FORCED }, { /***/ }), -/* 316 */ +/* 311 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isPrototypeOf = __webpack_require__(68); -var getPrototypeOf = __webpack_require__(67); -var setPrototypeOf = __webpack_require__(81); -var copyConstructorProperties = __webpack_require__(110); -var create = __webpack_require__(62); -var createNonEnumerableProperty = __webpack_require__(59); -var createPropertyDescriptor = __webpack_require__(73); -var installErrorCause = __webpack_require__(243); -var installErrorStack = __webpack_require__(185); -var iterate = __webpack_require__(56); -var normalizeStringArgument = __webpack_require__(118); -var wellKnownSymbol = __webpack_require__(39); +var $ = __webpack_require__(0); +var isPrototypeOf = __webpack_require__(36); +var getPrototypeOf = __webpack_require__(35); +var setPrototypeOf = __webpack_require__(49); +var copyConstructorProperties = __webpack_require__(79); +var create = __webpack_require__(30); +var createNonEnumerableProperty = __webpack_require__(27); +var createPropertyDescriptor = __webpack_require__(41); +var installErrorCause = __webpack_require__(214); +var installErrorStack = __webpack_require__(156); +var iterate = __webpack_require__(24); +var normalizeStringArgument = __webpack_require__(87); +var wellKnownSymbol = __webpack_require__(7); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var $Error = Error; @@ -41503,25 +40796,25 @@ $({ global: true, constructor: true, arity: 2 }, { /***/ }), -/* 317 */ +/* 312 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(316); +__webpack_require__(311); /***/ }), -/* 318 */ +/* 313 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var arrayBufferModule = __webpack_require__(141); -var setSpecies = __webpack_require__(122); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var arrayBufferModule = __webpack_require__(111); +var setSpecies = __webpack_require__(91); var ARRAY_BUFFER = 'ArrayBuffer'; var ArrayBuffer = arrayBufferModule[ARRAY_BUFFER]; @@ -41537,14 +40830,14 @@ setSpecies(ARRAY_BUFFER); /***/ }), -/* 319 */ +/* 314 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var defineBuiltInAccessor = __webpack_require__(55); -var isDetached = __webpack_require__(213); +var DESCRIPTORS = __webpack_require__(6); +var defineBuiltInAccessor = __webpack_require__(23); +var isDetached = __webpack_require__(184); var ArrayBufferPrototype = ArrayBuffer.prototype; @@ -41561,13 +40854,13 @@ if (DESCRIPTORS && !('detached' in ArrayBufferPrototype)) { /***/ }), -/* 320 */ +/* 315 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var ArrayBufferViewCore = __webpack_require__(44); +var $ = __webpack_require__(0); +var ArrayBufferViewCore = __webpack_require__(12); var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; @@ -41579,18 +40872,18 @@ $({ target: 'ArrayBuffer', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { /***/ }), -/* 321 */ +/* 316 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(98); -var fails = __webpack_require__(33); -var ArrayBufferModule = __webpack_require__(141); -var anObject = __webpack_require__(37); -var toAbsoluteIndex = __webpack_require__(91); -var toLength = __webpack_require__(77); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(67); +var fails = __webpack_require__(1); +var ArrayBufferModule = __webpack_require__(111); +var anObject = __webpack_require__(5); +var toAbsoluteIndex = __webpack_require__(59); +var toLength = __webpack_require__(45); var ArrayBuffer = ArrayBufferModule.ArrayBuffer; var DataView = ArrayBufferModule.DataView; @@ -41625,13 +40918,13 @@ $({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, /***/ }), -/* 322 */ +/* 317 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $transfer = __webpack_require__(214); +var $ = __webpack_require__(0); +var $transfer = __webpack_require__(185); // `ArrayBuffer.prototype.transferToFixedLength` method // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength @@ -41643,13 +40936,13 @@ if ($transfer) $({ target: 'ArrayBuffer', proto: true }, { /***/ }), -/* 323 */ +/* 318 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $transfer = __webpack_require__(214); +var $ = __webpack_require__(0); +var $transfer = __webpack_require__(185); // `ArrayBuffer.prototype.transfer` method // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer @@ -41661,16 +40954,16 @@ if ($transfer) $({ target: 'ArrayBuffer', proto: true }, { /***/ }), -/* 324 */ +/* 319 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var toIntegerOrInfinity = __webpack_require__(54); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var toIntegerOrInfinity = __webpack_require__(22); +var addToUnscopables = __webpack_require__(37); // `Array.prototype.at` method // https://tc39.es/ecma262/#sec-array.prototype.at @@ -41688,23 +40981,23 @@ addToUnscopables('at'); /***/ }), -/* 325 */ +/* 320 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var isArray = __webpack_require__(93); -var isObject = __webpack_require__(40); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var doesNotExceedSafeInteger = __webpack_require__(97); -var createProperty = __webpack_require__(87); -var arraySpeciesCreate = __webpack_require__(129); -var arrayMethodHasSpeciesSupport = __webpack_require__(128); -var wellKnownSymbol = __webpack_require__(39); -var V8_VERSION = __webpack_require__(84); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var isArray = __webpack_require__(62); +var isObject = __webpack_require__(8); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var doesNotExceedSafeInteger = __webpack_require__(66); +var createProperty = __webpack_require__(55); +var arraySpeciesCreate = __webpack_require__(98); +var arrayMethodHasSpeciesSupport = __webpack_require__(97); +var wellKnownSymbol = __webpack_require__(7); +var V8_VERSION = __webpack_require__(52); var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); @@ -41753,14 +41046,14 @@ $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, { /***/ }), -/* 326 */ +/* 321 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var copyWithin = __webpack_require__(215); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var copyWithin = __webpack_require__(186); +var addToUnscopables = __webpack_require__(37); // `Array.prototype.copyWithin` method // https://tc39.es/ecma262/#sec-array.prototype.copywithin @@ -41773,14 +41066,14 @@ addToUnscopables('copyWithin'); /***/ }), -/* 327 */ +/* 322 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $every = __webpack_require__(58).every; -var arrayMethodIsStrict = __webpack_require__(86); +var $ = __webpack_require__(0); +var $every = __webpack_require__(26).every; +var arrayMethodIsStrict = __webpack_require__(54); var STRICT_METHOD = arrayMethodIsStrict('every'); @@ -41794,14 +41087,14 @@ $({ target: 'Array', proto: true, forced: !STRICT_METHOD }, { /***/ }), -/* 328 */ +/* 323 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fill = __webpack_require__(175); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var fill = __webpack_require__(146); +var addToUnscopables = __webpack_require__(37); // `Array.prototype.fill` method // https://tc39.es/ecma262/#sec-array.prototype.fill @@ -41814,14 +41107,14 @@ addToUnscopables('fill'); /***/ }), -/* 329 */ +/* 324 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $filter = __webpack_require__(58).filter; -var arrayMethodHasSpeciesSupport = __webpack_require__(128); +var $ = __webpack_require__(0); +var $filter = __webpack_require__(26).filter; +var arrayMethodHasSpeciesSupport = __webpack_require__(97); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); @@ -41836,14 +41129,14 @@ $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { /***/ }), -/* 330 */ +/* 325 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $findIndex = __webpack_require__(58).findIndex; -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var $findIndex = __webpack_require__(26).findIndex; +var addToUnscopables = __webpack_require__(37); var FIND_INDEX = 'findIndex'; var SKIPS_HOLES = true; @@ -41865,14 +41158,14 @@ addToUnscopables(FIND_INDEX); /***/ }), -/* 331 */ +/* 326 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $findLastIndex = __webpack_require__(143).findLastIndex; -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var $findLastIndex = __webpack_require__(113).findLastIndex; +var addToUnscopables = __webpack_require__(37); // `Array.prototype.findLastIndex` method // https://tc39.es/ecma262/#sec-array.prototype.findlastindex @@ -41886,14 +41179,14 @@ addToUnscopables('findLastIndex'); /***/ }), -/* 332 */ +/* 327 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $findLast = __webpack_require__(143).findLast; -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var $findLast = __webpack_require__(113).findLast; +var addToUnscopables = __webpack_require__(37); // `Array.prototype.findLast` method // https://tc39.es/ecma262/#sec-array.prototype.findlast @@ -41907,14 +41200,14 @@ addToUnscopables('findLast'); /***/ }), -/* 333 */ +/* 328 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $find = __webpack_require__(58).find; -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var $find = __webpack_require__(26).find; +var addToUnscopables = __webpack_require__(37); var FIND = 'find'; var SKIPS_HOLES = true; @@ -41936,17 +41229,17 @@ addToUnscopables(FIND); /***/ }), -/* 334 */ +/* 329 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var flattenIntoArray = __webpack_require__(235); -var aCallable = __webpack_require__(42); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var arraySpeciesCreate = __webpack_require__(129); +var $ = __webpack_require__(0); +var flattenIntoArray = __webpack_require__(206); +var aCallable = __webpack_require__(10); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var arraySpeciesCreate = __webpack_require__(98); // `Array.prototype.flatMap` method // https://tc39.es/ecma262/#sec-array.prototype.flatmap @@ -41964,17 +41257,17 @@ $({ target: 'Array', proto: true }, { /***/ }), -/* 335 */ +/* 330 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var flattenIntoArray = __webpack_require__(235); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var toIntegerOrInfinity = __webpack_require__(54); -var arraySpeciesCreate = __webpack_require__(129); +var $ = __webpack_require__(0); +var flattenIntoArray = __webpack_require__(206); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var toIntegerOrInfinity = __webpack_require__(22); +var arraySpeciesCreate = __webpack_require__(98); // `Array.prototype.flat` method // https://tc39.es/ecma262/#sec-array.prototype.flat @@ -41991,13 +41284,13 @@ $({ target: 'Array', proto: true }, { /***/ }), -/* 336 */ +/* 331 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var forEach = __webpack_require__(216); +var $ = __webpack_require__(0); +var forEach = __webpack_require__(187); // `Array.prototype.forEach` method // https://tc39.es/ecma262/#sec-array.prototype.foreach @@ -42008,14 +41301,14 @@ $({ target: 'Array', proto: true, forced: [].forEach !== forEach }, { /***/ }), -/* 337 */ +/* 332 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fromAsync = __webpack_require__(290); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var fromAsync = __webpack_require__(285); +var fails = __webpack_require__(1); // eslint-disable-next-line es/no-array-fromasync -- safe var nativeFromAsync = Array.fromAsync; @@ -42037,14 +41330,14 @@ $({ target: 'Array', stat: true, forced: INCORRECT_CONSTRUCTURING }, { /***/ }), -/* 338 */ +/* 333 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var from = __webpack_require__(217); -var checkCorrectnessOfIteration = __webpack_require__(145); +var $ = __webpack_require__(0); +var from = __webpack_require__(188); +var checkCorrectnessOfIteration = __webpack_require__(115); var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { // eslint-disable-next-line es/no-array-from -- required for testing @@ -42059,15 +41352,15 @@ $({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { /***/ }), -/* 339 */ +/* 334 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $includes = __webpack_require__(127).includes; -var fails = __webpack_require__(33); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var $includes = __webpack_require__(96).includes; +var fails = __webpack_require__(1); +var addToUnscopables = __webpack_require__(37); // FF99+ bug var BROKEN_ON_SPARSE = fails(function () { @@ -42088,16 +41381,16 @@ addToUnscopables('includes'); /***/ }), -/* 340 */ +/* 335 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable es/no-array-prototype-indexof -- required for testing */ -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(98); -var $indexOf = __webpack_require__(127).indexOf; -var arrayMethodIsStrict = __webpack_require__(86); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(67); +var $indexOf = __webpack_require__(96).indexOf; +var arrayMethodIsStrict = __webpack_require__(54); var nativeIndexOf = uncurryThis([].indexOf); @@ -42118,13 +41411,13 @@ $({ target: 'Array', proto: true, forced: FORCED }, { /***/ }), -/* 341 */ +/* 336 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isArray = __webpack_require__(93); +var $ = __webpack_require__(0); +var isArray = __webpack_require__(62); // `Array.isArray` method // https://tc39.es/ecma262/#sec-array.isarray @@ -42134,16 +41427,16 @@ $({ target: 'Array', stat: true }, { /***/ }), -/* 342 */ +/* 337 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var IndexedObject = __webpack_require__(115); -var toIndexedObject = __webpack_require__(57); -var arrayMethodIsStrict = __webpack_require__(86); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var IndexedObject = __webpack_require__(84); +var toIndexedObject = __webpack_require__(25); +var arrayMethodIsStrict = __webpack_require__(54); var nativeJoin = uncurryThis([].join); @@ -42160,13 +41453,13 @@ $({ target: 'Array', proto: true, forced: FORCED }, { /***/ }), -/* 343 */ +/* 338 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var lastIndexOf = __webpack_require__(218); +var $ = __webpack_require__(0); +var lastIndexOf = __webpack_require__(189); // `Array.prototype.lastIndexOf` method // https://tc39.es/ecma262/#sec-array.prototype.lastindexof @@ -42177,14 +41470,14 @@ $({ target: 'Array', proto: true, forced: lastIndexOf !== [].lastIndexOf }, { /***/ }), -/* 344 */ +/* 339 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $map = __webpack_require__(58).map; -var arrayMethodHasSpeciesSupport = __webpack_require__(128); +var $ = __webpack_require__(0); +var $map = __webpack_require__(26).map; +var arrayMethodHasSpeciesSupport = __webpack_require__(97); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); @@ -42199,15 +41492,15 @@ $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { /***/ }), -/* 345 */ +/* 340 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var isConstructor = __webpack_require__(103); -var createProperty = __webpack_require__(87); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var isConstructor = __webpack_require__(72); +var createProperty = __webpack_require__(55); var $Array = Array; @@ -42233,17 +41526,17 @@ $({ target: 'Array', stat: true, forced: ISNT_GENERIC }, { /***/ }), -/* 346 */ +/* 341 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var setArrayLength = __webpack_require__(176); -var doesNotExceedSafeInteger = __webpack_require__(97); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var setArrayLength = __webpack_require__(147); +var doesNotExceedSafeInteger = __webpack_require__(66); +var fails = __webpack_require__(1); var INCORRECT_TO_LENGTH = fails(function () { return [].push.call({ length: 0x100000000 }, 1) !== 4294967297; @@ -42282,16 +41575,16 @@ $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, { /***/ }), -/* 347 */ +/* 342 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $reduceRight = __webpack_require__(144).right; -var arrayMethodIsStrict = __webpack_require__(86); -var CHROME_VERSION = __webpack_require__(84); -var IS_NODE = __webpack_require__(111); +var $ = __webpack_require__(0); +var $reduceRight = __webpack_require__(114).right; +var arrayMethodIsStrict = __webpack_require__(54); +var CHROME_VERSION = __webpack_require__(52); +var IS_NODE = __webpack_require__(80); // Chrome 80-82 has a critical bug // https://bugs.chromium.org/p/chromium/issues/detail?id=1049982 @@ -42308,16 +41601,16 @@ $({ target: 'Array', proto: true, forced: FORCED }, { /***/ }), -/* 348 */ +/* 343 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $reduce = __webpack_require__(144).left; -var arrayMethodIsStrict = __webpack_require__(86); -var CHROME_VERSION = __webpack_require__(84); -var IS_NODE = __webpack_require__(111); +var $ = __webpack_require__(0); +var $reduce = __webpack_require__(114).left; +var arrayMethodIsStrict = __webpack_require__(54); +var CHROME_VERSION = __webpack_require__(52); +var IS_NODE = __webpack_require__(80); // Chrome 80-82 has a critical bug // https://bugs.chromium.org/p/chromium/issues/detail?id=1049982 @@ -42335,14 +41628,14 @@ $({ target: 'Array', proto: true, forced: FORCED }, { /***/ }), -/* 349 */ +/* 344 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var isArray = __webpack_require__(93); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var isArray = __webpack_require__(62); var nativeReverse = uncurryThis([].reverse); var test = [1, 2]; @@ -42361,22 +41654,22 @@ $({ target: 'Array', proto: true, forced: String(test) === String(test.reverse() /***/ }), -/* 350 */ +/* 345 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isArray = __webpack_require__(93); -var isConstructor = __webpack_require__(103); -var isObject = __webpack_require__(40); -var toAbsoluteIndex = __webpack_require__(91); -var lengthOfArrayLike = __webpack_require__(50); -var toIndexedObject = __webpack_require__(57); -var createProperty = __webpack_require__(87); -var wellKnownSymbol = __webpack_require__(39); -var arrayMethodHasSpeciesSupport = __webpack_require__(128); -var nativeSlice = __webpack_require__(78); +var $ = __webpack_require__(0); +var isArray = __webpack_require__(62); +var isConstructor = __webpack_require__(72); +var isObject = __webpack_require__(8); +var toAbsoluteIndex = __webpack_require__(59); +var lengthOfArrayLike = __webpack_require__(18); +var toIndexedObject = __webpack_require__(25); +var createProperty = __webpack_require__(55); +var wellKnownSymbol = __webpack_require__(7); +var arrayMethodHasSpeciesSupport = __webpack_require__(97); +var nativeSlice = __webpack_require__(46); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice'); @@ -42417,14 +41710,14 @@ $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { /***/ }), -/* 351 */ +/* 346 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $some = __webpack_require__(58).some; -var arrayMethodIsStrict = __webpack_require__(86); +var $ = __webpack_require__(0); +var $some = __webpack_require__(26).some; +var arrayMethodIsStrict = __webpack_require__(54); var STRICT_METHOD = arrayMethodIsStrict('some'); @@ -42438,25 +41731,25 @@ $({ target: 'Array', proto: true, forced: !STRICT_METHOD }, { /***/ }), -/* 352 */ +/* 347 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var deletePropertyOrThrow = __webpack_require__(147); -var toString = __webpack_require__(41); -var fails = __webpack_require__(33); -var internalSort = __webpack_require__(177); -var arrayMethodIsStrict = __webpack_require__(86); -var FF = __webpack_require__(230); -var IE_OR_EDGE = __webpack_require__(231); -var V8 = __webpack_require__(84); -var WEBKIT = __webpack_require__(183); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var deletePropertyOrThrow = __webpack_require__(117); +var toString = __webpack_require__(9); +var fails = __webpack_require__(1); +var internalSort = __webpack_require__(148); +var arrayMethodIsStrict = __webpack_require__(54); +var FF = __webpack_require__(201); +var IE_OR_EDGE = __webpack_require__(202); +var V8 = __webpack_require__(52); +var WEBKIT = __webpack_require__(154); var test = []; var nativeSort = uncurryThis(test.sort); @@ -42551,12 +41844,12 @@ $({ target: 'Array', proto: true, forced: FORCED }, { /***/ }), -/* 353 */ +/* 348 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var setSpecies = __webpack_require__(122); +var setSpecies = __webpack_require__(91); // `Array[@@species]` getter // https://tc39.es/ecma262/#sec-get-array-@@species @@ -42564,22 +41857,22 @@ setSpecies('Array'); /***/ }), -/* 354 */ +/* 349 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toObject = __webpack_require__(47); -var toAbsoluteIndex = __webpack_require__(91); -var toIntegerOrInfinity = __webpack_require__(54); -var lengthOfArrayLike = __webpack_require__(50); -var setArrayLength = __webpack_require__(176); -var doesNotExceedSafeInteger = __webpack_require__(97); -var arraySpeciesCreate = __webpack_require__(129); -var createProperty = __webpack_require__(87); -var deletePropertyOrThrow = __webpack_require__(147); -var arrayMethodHasSpeciesSupport = __webpack_require__(128); +var $ = __webpack_require__(0); +var toObject = __webpack_require__(15); +var toAbsoluteIndex = __webpack_require__(59); +var toIntegerOrInfinity = __webpack_require__(22); +var lengthOfArrayLike = __webpack_require__(18); +var setArrayLength = __webpack_require__(147); +var doesNotExceedSafeInteger = __webpack_require__(66); +var arraySpeciesCreate = __webpack_require__(98); +var createProperty = __webpack_require__(55); +var deletePropertyOrThrow = __webpack_require__(117); +var arrayMethodHasSpeciesSupport = __webpack_require__(97); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice'); @@ -42638,15 +41931,15 @@ $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { /***/ }), -/* 355 */ +/* 350 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var arrayToReversed = __webpack_require__(219); -var toIndexedObject = __webpack_require__(57); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var arrayToReversed = __webpack_require__(190); +var toIndexedObject = __webpack_require__(25); +var addToUnscopables = __webpack_require__(37); var $Array = Array; @@ -42662,18 +41955,18 @@ addToUnscopables('toReversed'); /***/ }), -/* 356 */ +/* 351 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var toIndexedObject = __webpack_require__(57); -var arrayFromConstructorAndList = __webpack_require__(142); -var getBuiltInPrototypeMethod = __webpack_require__(238); -var addToUnscopables = __webpack_require__(69); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var toIndexedObject = __webpack_require__(25); +var arrayFromConstructorAndList = __webpack_require__(112); +var getBuiltInPrototypeMethod = __webpack_require__(209); +var addToUnscopables = __webpack_require__(37); var $Array = Array; var sort = uncurryThis(getBuiltInPrototypeMethod('Array', 'sort')); @@ -42693,18 +41986,18 @@ addToUnscopables('toSorted'); /***/ }), -/* 357 */ +/* 352 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var addToUnscopables = __webpack_require__(69); -var doesNotExceedSafeInteger = __webpack_require__(97); -var lengthOfArrayLike = __webpack_require__(50); -var toAbsoluteIndex = __webpack_require__(91); -var toIndexedObject = __webpack_require__(57); -var toIntegerOrInfinity = __webpack_require__(54); +var $ = __webpack_require__(0); +var addToUnscopables = __webpack_require__(37); +var doesNotExceedSafeInteger = __webpack_require__(66); +var lengthOfArrayLike = __webpack_require__(18); +var toAbsoluteIndex = __webpack_require__(59); +var toIndexedObject = __webpack_require__(25); +var toIntegerOrInfinity = __webpack_require__(22); var $Array = Array; var max = Math.max; @@ -42744,45 +42037,45 @@ addToUnscopables('toSpliced'); /***/ }), -/* 358 */ +/* 353 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // this method was added to unscopables after implementation // in popular engines, so it's moved to a separate module -var addToUnscopables = __webpack_require__(69); +var addToUnscopables = __webpack_require__(37); // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('flatMap'); /***/ }), -/* 359 */ +/* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // this method was added to unscopables after implementation // in popular engines, so it's moved to a separate module -var addToUnscopables = __webpack_require__(69); +var addToUnscopables = __webpack_require__(37); // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('flat'); /***/ }), -/* 360 */ +/* 355 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toObject = __webpack_require__(47); -var lengthOfArrayLike = __webpack_require__(50); -var setArrayLength = __webpack_require__(176); -var deletePropertyOrThrow = __webpack_require__(147); -var doesNotExceedSafeInteger = __webpack_require__(97); +var $ = __webpack_require__(0); +var toObject = __webpack_require__(15); +var lengthOfArrayLike = __webpack_require__(18); +var setArrayLength = __webpack_require__(147); +var deletePropertyOrThrow = __webpack_require__(117); +var doesNotExceedSafeInteger = __webpack_require__(66); // IE8- var INCORRECT_RESULT = [].unshift(0) !== 1; @@ -42824,14 +42117,14 @@ $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, { /***/ }), -/* 361 */ +/* 356 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var arrayWith = __webpack_require__(220); -var toIndexedObject = __webpack_require__(57); +var $ = __webpack_require__(0); +var arrayWith = __webpack_require__(191); +var toIndexedObject = __webpack_require__(25); var $Array = Array; @@ -42855,24 +42148,24 @@ $({ target: 'Array', proto: true, forced: INCORRECT_EXCEPTION_ON_COERCION_FAIL } /***/ }), -/* 362 */ +/* 357 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-async-explicit-resource-management -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var getBuiltIn = __webpack_require__(43); -var aCallable = __webpack_require__(42); -var anInstance = __webpack_require__(71); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltIns = __webpack_require__(88); -var defineBuiltInAccessor = __webpack_require__(55); -var wellKnownSymbol = __webpack_require__(39); -var InternalStateModule = __webpack_require__(53); -var addDisposableResource = __webpack_require__(211); -var V8_VERSION = __webpack_require__(84); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var getBuiltIn = __webpack_require__(11); +var aCallable = __webpack_require__(10); +var anInstance = __webpack_require__(39); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltIns = __webpack_require__(56); +var defineBuiltInAccessor = __webpack_require__(23); +var wellKnownSymbol = __webpack_require__(7); +var InternalStateModule = __webpack_require__(21); +var addDisposableResource = __webpack_require__(182); +var V8_VERSION = __webpack_require__(52); var Promise = getBuiltIn('Promise'); var SuppressedError = getBuiltIn('SuppressedError'); @@ -42997,19 +42290,19 @@ $({ global: true, constructor: true, forced: SYNC_DISPOSE_RETURNING_PROMISE_RESO /***/ }), -/* 363 */ +/* 358 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-async-explicit-resource-management -var call = __webpack_require__(36); -var defineBuiltIn = __webpack_require__(49); -var getBuiltIn = __webpack_require__(43); -var getMethod = __webpack_require__(60); -var hasOwn = __webpack_require__(45); -var wellKnownSymbol = __webpack_require__(39); -var AsyncIteratorPrototype = __webpack_require__(222); +var call = __webpack_require__(4); +var defineBuiltIn = __webpack_require__(17); +var getBuiltIn = __webpack_require__(11); +var getMethod = __webpack_require__(28); +var hasOwn = __webpack_require__(13); +var wellKnownSymbol = __webpack_require__(7); +var AsyncIteratorPrototype = __webpack_require__(193); var ASYNC_DISPOSE = wellKnownSymbol('asyncDispose'); var Promise = getBuiltIn('Promise'); @@ -43030,14 +42323,14 @@ if (!hasOwn(AsyncIteratorPrototype, ASYNC_DISPOSE)) { /***/ }), -/* 364 */ +/* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var ArrayBufferModule = __webpack_require__(141); -var NATIVE_ARRAY_BUFFER = __webpack_require__(140); +var $ = __webpack_require__(0); +var ArrayBufferModule = __webpack_require__(111); +var NATIVE_ARRAY_BUFFER = __webpack_require__(110); // `DataView` constructor // https://tc39.es/ecma262/#sec-dataview-constructor @@ -43047,13 +42340,13 @@ $({ global: true, constructor: true, forced: !NATIVE_ARRAY_BUFFER }, { /***/ }), -/* 365 */ +/* 360 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); var pow = Math.pow; @@ -43084,28 +42377,28 @@ $({ target: 'DataView', proto: true }, { /***/ }), -/* 366 */ +/* 361 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(364); +__webpack_require__(359); /***/ }), -/* 367 */ +/* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var aDataView = __webpack_require__(287); -var toIndex = __webpack_require__(169); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var aDataView = __webpack_require__(282); +var toIndex = __webpack_require__(139); // TODO: Replace with module dependency in `core-js@4` -var log2 = __webpack_require__(252); -var roundTiesToEven = __webpack_require__(253); +var log2 = __webpack_require__(223); +var roundTiesToEven = __webpack_require__(224); var pow = Math.pow; @@ -43157,14 +42450,14 @@ $({ target: 'DataView', proto: true }, { /***/ }), -/* 368 */ +/* 363 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); // IE8- non-standard case var FORCED = fails(function () { @@ -43184,14 +42477,14 @@ $({ target: 'Date', proto: true, forced: FORCED }, { /***/ }), -/* 369 */ +/* 364 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove from `core-js@4` -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); var $Date = Date; var thisTimeValue = uncurryThis($Date.prototype.getTime); @@ -43206,14 +42499,14 @@ $({ target: 'Date', stat: true }, { /***/ }), -/* 370 */ +/* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toIntegerOrInfinity = __webpack_require__(54); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toIntegerOrInfinity = __webpack_require__(22); var DatePrototype = Date.prototype; var thisTimeValue = uncurryThis(DatePrototype.getTime); @@ -43233,12 +42526,12 @@ $({ target: 'Date', proto: true }, { /***/ }), -/* 371 */ +/* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Date.prototype.toGMTString` method // https://tc39.es/ecma262/#sec-date.prototype.togmtstring @@ -43248,13 +42541,13 @@ $({ target: 'Date', proto: true }, { /***/ }), -/* 372 */ +/* 367 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toISOString = __webpack_require__(294); +var $ = __webpack_require__(0); +var toISOString = __webpack_require__(289); // `Date.prototype.toISOString` method // https://tc39.es/ecma262/#sec-date.prototype.toisostring @@ -43265,15 +42558,15 @@ $({ target: 'Date', proto: true, forced: Date.prototype.toISOString !== toISOStr /***/ }), -/* 373 */ +/* 368 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var toObject = __webpack_require__(47); -var toPrimitive = __webpack_require__(170); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var toObject = __webpack_require__(15); +var toPrimitive = __webpack_require__(140); var FORCED = fails(function () { return new Date(NaN).toJSON() !== null @@ -43293,15 +42586,15 @@ $({ target: 'Date', proto: true, arity: 1, forced: FORCED }, { /***/ }), -/* 374 */ +/* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var hasOwn = __webpack_require__(45); -var defineBuiltIn = __webpack_require__(49); -var dateToPrimitive = __webpack_require__(295); -var wellKnownSymbol = __webpack_require__(39); +var hasOwn = __webpack_require__(13); +var defineBuiltIn = __webpack_require__(17); +var dateToPrimitive = __webpack_require__(290); +var wellKnownSymbol = __webpack_require__(7); var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); var DatePrototype = Date.prototype; @@ -43314,14 +42607,14 @@ if (!hasOwn(DatePrototype, TO_PRIMITIVE)) { /***/ }), -/* 375 */ +/* 370 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove from `core-js@4` -var uncurryThis = __webpack_require__(34); -var defineBuiltIn = __webpack_require__(49); +var uncurryThis = __webpack_require__(2); +var defineBuiltIn = __webpack_require__(17); var DatePrototype = Date.prototype; var INVALID_DATE = 'Invalid Date'; @@ -43341,23 +42634,23 @@ if (String(new Date(NaN)) !== INVALID_DATE) { /***/ }), -/* 376 */ +/* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-explicit-resource-management -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var getBuiltIn = __webpack_require__(43); -var aCallable = __webpack_require__(42); -var anInstance = __webpack_require__(71); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltIns = __webpack_require__(88); -var defineBuiltInAccessor = __webpack_require__(55); -var wellKnownSymbol = __webpack_require__(39); -var InternalStateModule = __webpack_require__(53); -var addDisposableResource = __webpack_require__(211); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var getBuiltIn = __webpack_require__(11); +var aCallable = __webpack_require__(10); +var anInstance = __webpack_require__(39); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltIns = __webpack_require__(56); +var defineBuiltInAccessor = __webpack_require__(23); +var wellKnownSymbol = __webpack_require__(7); +var InternalStateModule = __webpack_require__(21); +var addDisposableResource = __webpack_require__(182); var SuppressedError = getBuiltIn('SuppressedError'); var $ReferenceError = ReferenceError; @@ -43462,16 +42755,16 @@ $({ global: true, constructor: true }, { /***/ }), -/* 377 */ +/* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable no-unused-vars -- required for functions `.length` */ -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var apply = __webpack_require__(74); -var wrapErrorConstructorWithCause = __webpack_require__(282); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var apply = __webpack_require__(42); +var wrapErrorConstructorWithCause = __webpack_require__(253); var WEB_ASSEMBLY = 'WebAssembly'; var WebAssembly = globalThis[WEB_ASSEMBLY]; @@ -43527,16 +42820,16 @@ exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) { /***/ }), -/* 378 */ +/* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var isObject = __webpack_require__(40); -var classof = __webpack_require__(79); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var isObject = __webpack_require__(8); +var classof = __webpack_require__(47); +var fails = __webpack_require__(1); var ERROR = 'Error'; var DOM_EXCEPTION = 'DOMException'; @@ -43571,13 +42864,13 @@ $({ target: 'Error', stat: true, sham: true, forced: FORCED }, { /***/ }), -/* 379 */ +/* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineBuiltIn = __webpack_require__(49); -var errorToString = __webpack_require__(234); +var defineBuiltIn = __webpack_require__(17); +var errorToString = __webpack_require__(205); var ErrorPrototype = Error.prototype; @@ -43589,14 +42882,14 @@ if (ErrorPrototype.toString !== errorToString) { /***/ }), -/* 380 */ +/* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); var charAt = uncurryThis(''.charAt); var charCodeAt = uncurryThis(''.charCodeAt); @@ -43639,14 +42932,14 @@ $({ global: true }, { /***/ }), -/* 381 */ +/* 376 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove from `core-js@4` -var $ = __webpack_require__(32); -var bind = __webpack_require__(236); +var $ = __webpack_require__(0); +var bind = __webpack_require__(207); // `Function.prototype.bind` method // https://tc39.es/ecma262/#sec-function.prototype.bind @@ -43657,17 +42950,17 @@ $({ target: 'Function', proto: true, forced: Function.bind !== bind }, { /***/ }), -/* 382 */ +/* 377 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var definePropertyModule = __webpack_require__(51); -var isPrototypeOf = __webpack_require__(68); -var wellKnownSymbol = __webpack_require__(39); -var makeBuiltIn = __webpack_require__(191); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var definePropertyModule = __webpack_require__(19); +var isPrototypeOf = __webpack_require__(36); +var wellKnownSymbol = __webpack_require__(7); +var makeBuiltIn = __webpack_require__(162); var HAS_INSTANCE = wellKnownSymbol('hasInstance'); var FunctionPrototype = Function.prototype; @@ -43684,15 +42977,15 @@ if (!(HAS_INSTANCE in FunctionPrototype)) { /***/ }), -/* 383 */ +/* 378 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var FUNCTION_NAME_EXISTS = __webpack_require__(113).EXISTS; -var uncurryThis = __webpack_require__(34); -var defineBuiltInAccessor = __webpack_require__(55); +var DESCRIPTORS = __webpack_require__(6); +var FUNCTION_NAME_EXISTS = __webpack_require__(82).EXISTS; +var uncurryThis = __webpack_require__(2); +var defineBuiltInAccessor = __webpack_require__(23); var FunctionPrototype = Function.prototype; var functionToString = uncurryThis(FunctionPrototype.toString); @@ -43717,13 +43010,13 @@ if (DESCRIPTORS && !FUNCTION_NAME_EXISTS) { /***/ }), -/* 384 */ +/* 379 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); // `globalThis` object // https://tc39.es/ecma262/#sec-globalthis @@ -43733,25 +43026,25 @@ $({ global: true, forced: globalThis.globalThis !== globalThis }, { /***/ }), -/* 385 */ +/* 380 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var anInstance = __webpack_require__(71); -var anObject = __webpack_require__(37); -var isCallable = __webpack_require__(46); -var getPrototypeOf = __webpack_require__(67); -var defineBuiltInAccessor = __webpack_require__(55); -var createProperty = __webpack_require__(87); -var fails = __webpack_require__(33); -var hasOwn = __webpack_require__(45); -var wellKnownSymbol = __webpack_require__(39); -var IteratorPrototype = __webpack_require__(117).IteratorPrototype; -var DESCRIPTORS = __webpack_require__(38); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var anInstance = __webpack_require__(39); +var anObject = __webpack_require__(5); +var isCallable = __webpack_require__(14); +var getPrototypeOf = __webpack_require__(35); +var defineBuiltInAccessor = __webpack_require__(23); +var createProperty = __webpack_require__(55); +var fails = __webpack_require__(1); +var hasOwn = __webpack_require__(13); +var wellKnownSymbol = __webpack_require__(7); +var IteratorPrototype = __webpack_require__(86).IteratorPrototype; +var DESCRIPTORS = __webpack_require__(6); +var IS_PURE = __webpack_require__(16); var CONSTRUCTOR = 'constructor'; var ITERATOR = 'Iterator'; @@ -43805,18 +43098,18 @@ $({ global: true, constructor: true, forced: FORCED }, { /***/ }), -/* 386 */ +/* 381 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-explicit-resource-management -var call = __webpack_require__(36); -var defineBuiltIn = __webpack_require__(49); -var getMethod = __webpack_require__(60); -var hasOwn = __webpack_require__(45); -var wellKnownSymbol = __webpack_require__(39); -var IteratorPrototype = __webpack_require__(117).IteratorPrototype; +var call = __webpack_require__(4); +var defineBuiltIn = __webpack_require__(17); +var getMethod = __webpack_require__(28); +var hasOwn = __webpack_require__(13); +var wellKnownSymbol = __webpack_require__(7); +var IteratorPrototype = __webpack_require__(86).IteratorPrototype; var DISPOSE = wellKnownSymbol('dispose'); @@ -43829,22 +43122,22 @@ if (!hasOwn(IteratorPrototype, DISPOSE)) { /***/ }), -/* 387 */ +/* 382 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var notANaN = __webpack_require__(256); -var toPositiveInteger = __webpack_require__(206); -var iteratorClose = __webpack_require__(61); -var createIteratorProxy = __webpack_require__(116); -var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(153); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var notANaN = __webpack_require__(227); +var toPositiveInteger = __webpack_require__(177); +var iteratorClose = __webpack_require__(29); +var createIteratorProxy = __webpack_require__(85); +var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(123); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); +var IS_PURE = __webpack_require__(16); var DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('drop', 0); var dropWithoutClosingOnEarlyError = !IS_PURE && !DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR @@ -43889,19 +43182,19 @@ $({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 388 */ +/* 383 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var iterate = __webpack_require__(56); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var iterate = __webpack_require__(24); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var everyWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('every', TypeError); @@ -43928,22 +43221,22 @@ $({ target: 'Iterator', proto: true, real: true, forced: everyWithoutClosingOnEa /***/ }), -/* 389 */ +/* 384 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var createIteratorProxy = __webpack_require__(116); -var callWithSafeIterationClosing = __webpack_require__(178); -var IS_PURE = __webpack_require__(48); -var iteratorClose = __webpack_require__(61); -var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(153); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var createIteratorProxy = __webpack_require__(85); +var callWithSafeIterationClosing = __webpack_require__(149); +var IS_PURE = __webpack_require__(16); +var iteratorClose = __webpack_require__(29); +var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(123); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('filter', function () { /* empty */ }); var filterWithoutClosingOnEarlyError = !IS_PURE && !FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR @@ -43986,19 +43279,19 @@ $({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 390 */ +/* 385 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var iterate = __webpack_require__(56); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var iterate = __webpack_require__(24); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var findWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('find', TypeError); @@ -44025,22 +43318,22 @@ $({ target: 'Iterator', proto: true, real: true, forced: findWithoutClosingOnEar /***/ }), -/* 391 */ +/* 386 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var getIteratorFlattenable = __webpack_require__(239); -var createIteratorProxy = __webpack_require__(116); -var iteratorClose = __webpack_require__(61); -var IS_PURE = __webpack_require__(48); -var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(153); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var getIteratorFlattenable = __webpack_require__(210); +var createIteratorProxy = __webpack_require__(85); +var iteratorClose = __webpack_require__(29); +var IS_PURE = __webpack_require__(16); +var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(123); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('flatMap', function () { /* empty */ }); @@ -44093,19 +43386,19 @@ $({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 392 */ +/* 387 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var iterate = __webpack_require__(56); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var iterate = __webpack_require__(24); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var forEachWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('forEach', TypeError); @@ -44132,19 +43425,19 @@ $({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosingOn /***/ }), -/* 393 */ +/* 388 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var toObject = __webpack_require__(47); -var isPrototypeOf = __webpack_require__(68); -var IteratorPrototype = __webpack_require__(117).IteratorPrototype; -var createIteratorProxy = __webpack_require__(116); -var getIteratorFlattenable = __webpack_require__(239); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var toObject = __webpack_require__(15); +var isPrototypeOf = __webpack_require__(36); +var IteratorPrototype = __webpack_require__(86).IteratorPrototype; +var createIteratorProxy = __webpack_require__(85); +var getIteratorFlattenable = __webpack_require__(210); +var IS_PURE = __webpack_require__(16); var FORCED = IS_PURE || function () { // Should not throw when an underlying iterator's `return` method is null @@ -44174,22 +43467,22 @@ $({ target: 'Iterator', stat: true, forced: FORCED }, { /***/ }), -/* 394 */ +/* 389 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var createIteratorProxy = __webpack_require__(116); -var callWithSafeIterationClosing = __webpack_require__(178); -var iteratorClose = __webpack_require__(61); -var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(153); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var createIteratorProxy = __webpack_require__(85); +var callWithSafeIterationClosing = __webpack_require__(149); +var iteratorClose = __webpack_require__(29); +var iteratorHelperThrowsOnInvalidIterator = __webpack_require__(123); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); +var IS_PURE = __webpack_require__(16); var MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('map', function () { /* empty */ }); var mapWithoutClosingOnEarlyError = !IS_PURE && !MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR @@ -44225,20 +43518,20 @@ $({ target: 'Iterator', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 395 */ +/* 390 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var iterate = __webpack_require__(56); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); -var apply = __webpack_require__(74); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var iterate = __webpack_require__(24); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); +var apply = __webpack_require__(42); +var fails = __webpack_require__(1); var $TypeError = TypeError; @@ -44284,19 +43577,19 @@ $({ target: 'Iterator', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFI /***/ }), -/* 396 */ +/* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var iterate = __webpack_require__(56); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var iterate = __webpack_require__(24); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); var someWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('some', TypeError); @@ -44323,21 +43616,21 @@ $({ target: 'Iterator', proto: true, real: true, forced: someWithoutClosingOnEar /***/ }), -/* 397 */ +/* 392 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var getIteratorDirect = __webpack_require__(65); -var notANaN = __webpack_require__(256); -var toPositiveInteger = __webpack_require__(206); -var createIteratorProxy = __webpack_require__(116); -var iteratorClose = __webpack_require__(61); -var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(85); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var getIteratorDirect = __webpack_require__(33); +var notANaN = __webpack_require__(227); +var toPositiveInteger = __webpack_require__(177); +var createIteratorProxy = __webpack_require__(85); +var iteratorClose = __webpack_require__(29); +var iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(53); +var IS_PURE = __webpack_require__(16); var takeWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('take', RangeError); @@ -44374,15 +43667,15 @@ $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || takeWithoutC /***/ }), -/* 398 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var anObject = __webpack_require__(37); -var iterate = __webpack_require__(56); -var getIteratorDirect = __webpack_require__(65); +var $ = __webpack_require__(0); +var anObject = __webpack_require__(5); +var iterate = __webpack_require__(24); +var getIteratorDirect = __webpack_require__(33); var push = [].push; @@ -44398,13 +43691,13 @@ $({ target: 'Iterator', proto: true, real: true }, { /***/ }), -/* 399 */ +/* 394 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var setToStringTag = __webpack_require__(70); +var globalThis = __webpack_require__(3); +var setToStringTag = __webpack_require__(38); // JSON[@@toStringTag] property // https://tc39.es/ecma262/#sec-json-@@tostringtag @@ -44412,13 +43705,13 @@ setToStringTag(globalThis.JSON, 'JSON', true); /***/ }), -/* 400 */ +/* 395 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var collection = __webpack_require__(146); -var collectionStrong = __webpack_require__(224); +var collection = __webpack_require__(116); +var collectionStrong = __webpack_require__(195); // `Map` constructor // https://tc39.es/ecma262/#sec-map-objects @@ -44428,19 +43721,19 @@ collection('Map', function (init) { /***/ }), -/* 401 */ +/* 396 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var requireObjectCoercible = __webpack_require__(52); -var iterate = __webpack_require__(56); -var MapHelpers = __webpack_require__(247); -var IS_PURE = __webpack_require__(48); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var requireObjectCoercible = __webpack_require__(20); +var iterate = __webpack_require__(24); +var MapHelpers = __webpack_require__(218); +var IS_PURE = __webpack_require__(16); +var fails = __webpack_require__(1); var Map = MapHelpers.Map; var has = MapHelpers.has; @@ -44474,23 +43767,23 @@ $({ target: 'Map', stat: true, forced: IS_PURE || DOES_NOT_WORK_WITH_PRIMITIVES /***/ }), -/* 402 */ +/* 397 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(400); +__webpack_require__(395); /***/ }), -/* 403 */ +/* 398 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var log1p = __webpack_require__(251); +var $ = __webpack_require__(0); +var log1p = __webpack_require__(222); // eslint-disable-next-line es/no-math-acosh -- required for testing var $acosh = Math.acosh; @@ -44517,12 +43810,12 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 404 */ +/* 399 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // eslint-disable-next-line es/no-math-asinh -- required for testing var $asinh = Math.asinh; @@ -44545,12 +43838,12 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 405 */ +/* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // eslint-disable-next-line es/no-math-atanh -- required for testing var $atanh = Math.atanh; @@ -44570,13 +43863,13 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 406 */ +/* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var sign = __webpack_require__(192); +var $ = __webpack_require__(0); +var sign = __webpack_require__(163); var abs = Math.abs; var pow = Math.pow; @@ -44592,12 +43885,12 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 407 */ +/* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); var floor = Math.floor; var log = Math.log; @@ -44614,13 +43907,13 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 408 */ +/* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var expm1 = __webpack_require__(154); +var $ = __webpack_require__(0); +var expm1 = __webpack_require__(124); // eslint-disable-next-line es/no-math-cosh -- required for testing var $cosh = Math.cosh; @@ -44640,13 +43933,13 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 409 */ +/* 404 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var expm1 = __webpack_require__(154); +var $ = __webpack_require__(0); +var expm1 = __webpack_require__(124); // `Math.expm1` method // https://tc39.es/ecma262/#sec-math.expm1 @@ -44655,13 +43948,13 @@ $({ target: 'Math', stat: true, forced: expm1 !== Math.expm1 }, { expm1: expm1 } /***/ }), -/* 410 */ +/* 405 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var floatRound = __webpack_require__(248); +var $ = __webpack_require__(0); +var floatRound = __webpack_require__(219); var FLOAT16_EPSILON = 0.0009765625; var FLOAT16_MAX_VALUE = 65504; @@ -44677,13 +43970,13 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 411 */ +/* 406 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fround = __webpack_require__(249); +var $ = __webpack_require__(0); +var fround = __webpack_require__(220); // `Math.fround` method // https://tc39.es/ecma262/#sec-math.fround @@ -44691,12 +43984,12 @@ $({ target: 'Math', stat: true }, { fround: fround }); /***/ }), -/* 412 */ +/* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // eslint-disable-next-line es/no-math-hypot -- required for testing var $hypot = Math.hypot; @@ -44734,13 +44027,13 @@ $({ target: 'Math', stat: true, arity: 2, forced: FORCED }, { /***/ }), -/* 413 */ +/* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); // eslint-disable-next-line es/no-math-imul -- required for testing var $imul = Math.imul; @@ -44765,13 +44058,13 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 414 */ +/* 409 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var log10 = __webpack_require__(250); +var $ = __webpack_require__(0); +var log10 = __webpack_require__(221); // `Math.log10` method // https://tc39.es/ecma262/#sec-math.log10 @@ -44781,13 +44074,13 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 415 */ +/* 410 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var log1p = __webpack_require__(251); +var $ = __webpack_require__(0); +var log1p = __webpack_require__(222); // `Math.log1p` method // https://tc39.es/ecma262/#sec-math.log1p @@ -44795,13 +44088,13 @@ $({ target: 'Math', stat: true }, { log1p: log1p }); /***/ }), -/* 416 */ +/* 411 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var log2 = __webpack_require__(252); +var $ = __webpack_require__(0); +var log2 = __webpack_require__(223); // `Math.log2` method // https://tc39.es/ecma262/#sec-math.log2 @@ -44811,13 +44104,13 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 417 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var sign = __webpack_require__(192); +var $ = __webpack_require__(0); +var sign = __webpack_require__(163); // `Math.sign` method // https://tc39.es/ecma262/#sec-math.sign @@ -44827,14 +44120,14 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 418 */ +/* 413 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var expm1 = __webpack_require__(154); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var expm1 = __webpack_require__(124); var abs = Math.abs; var exp = Math.exp; @@ -44857,13 +44150,13 @@ $({ target: 'Math', stat: true, forced: FORCED }, { /***/ }), -/* 419 */ +/* 414 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var expm1 = __webpack_require__(154); +var $ = __webpack_require__(0); +var expm1 = __webpack_require__(124); var exp = Math.exp; @@ -44880,12 +44173,12 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 420 */ +/* 415 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var setToStringTag = __webpack_require__(70); +var setToStringTag = __webpack_require__(38); // Math[@@toStringTag] property // https://tc39.es/ecma262/#sec-math-@@tostringtag @@ -44893,13 +44186,13 @@ setToStringTag(Math, 'Math', true); /***/ }), -/* 421 */ +/* 416 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var trunc = __webpack_require__(254); +var $ = __webpack_require__(0); +var trunc = __webpack_require__(225); // `Math.trunc` method // https://tc39.es/ecma262/#sec-math.trunc @@ -44909,29 +44202,29 @@ $({ target: 'Math', stat: true }, { /***/ }), -/* 422 */ +/* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var IS_PURE = __webpack_require__(48); -var DESCRIPTORS = __webpack_require__(38); -var globalThis = __webpack_require__(35); -var path = __webpack_require__(158); -var uncurryThis = __webpack_require__(34); -var isForced = __webpack_require__(132); -var hasOwn = __webpack_require__(45); -var inheritIfRequired = __webpack_require__(101); -var isPrototypeOf = __webpack_require__(68); -var isSymbol = __webpack_require__(104); -var toPrimitive = __webpack_require__(170); -var fails = __webpack_require__(33); -var getOwnPropertyNames = __webpack_require__(106).f; -var getOwnPropertyDescriptor = __webpack_require__(63).f; -var defineProperty = __webpack_require__(51).f; -var thisNumberValue = __webpack_require__(168); -var trim = __webpack_require__(124).trim; +var $ = __webpack_require__(0); +var IS_PURE = __webpack_require__(16); +var DESCRIPTORS = __webpack_require__(6); +var globalThis = __webpack_require__(3); +var path = __webpack_require__(128); +var uncurryThis = __webpack_require__(2); +var isForced = __webpack_require__(101); +var hasOwn = __webpack_require__(13); +var inheritIfRequired = __webpack_require__(70); +var isPrototypeOf = __webpack_require__(36); +var isSymbol = __webpack_require__(73); +var toPrimitive = __webpack_require__(140); +var fails = __webpack_require__(1); +var getOwnPropertyNames = __webpack_require__(75).f; +var getOwnPropertyDescriptor = __webpack_require__(31).f; +var defineProperty = __webpack_require__(19).f; +var thisNumberValue = __webpack_require__(138); +var trim = __webpack_require__(93).trim; var NUMBER = 'Number'; var NativeNumber = globalThis[NUMBER]; @@ -45031,12 +44324,12 @@ if (FORCED || IS_PURE) copyConstructorProperties(path[NUMBER], NativeNumber); /***/ }), -/* 423 */ +/* 418 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Number.EPSILON` constant // https://tc39.es/ecma262/#sec-number.epsilon @@ -45046,13 +44339,13 @@ $({ target: 'Number', stat: true, nonConfigurable: true, nonWritable: true }, { /***/ }), -/* 424 */ +/* 419 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var numberIsFinite = __webpack_require__(303); +var $ = __webpack_require__(0); +var numberIsFinite = __webpack_require__(298); // `Number.isFinite` method // https://tc39.es/ecma262/#sec-number.isfinite @@ -45060,13 +44353,13 @@ $({ target: 'Number', stat: true }, { isFinite: numberIsFinite }); /***/ }), -/* 425 */ +/* 420 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isIntegralNumber = __webpack_require__(188); +var $ = __webpack_require__(0); +var isIntegralNumber = __webpack_require__(159); // `Number.isInteger` method // https://tc39.es/ecma262/#sec-number.isinteger @@ -45076,12 +44369,12 @@ $({ target: 'Number', stat: true }, { /***/ }), -/* 426 */ +/* 421 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Number.isNaN` method // https://tc39.es/ecma262/#sec-number.isnan @@ -45094,13 +44387,13 @@ $({ target: 'Number', stat: true }, { /***/ }), -/* 427 */ +/* 422 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isIntegralNumber = __webpack_require__(188); +var $ = __webpack_require__(0); +var isIntegralNumber = __webpack_require__(159); var abs = Math.abs; @@ -45114,12 +44407,12 @@ $({ target: 'Number', stat: true }, { /***/ }), -/* 428 */ +/* 423 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Number.MAX_SAFE_INTEGER` constant // https://tc39.es/ecma262/#sec-number.max_safe_integer @@ -45129,12 +44422,12 @@ $({ target: 'Number', stat: true, nonConfigurable: true, nonWritable: true }, { /***/ }), -/* 429 */ +/* 424 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Number.MIN_SAFE_INTEGER` constant // https://tc39.es/ecma262/#sec-number.min_safe_integer @@ -45144,13 +44437,13 @@ $({ target: 'Number', stat: true, nonConfigurable: true, nonWritable: true }, { /***/ }), -/* 430 */ +/* 425 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var parseFloat = __webpack_require__(257); +var $ = __webpack_require__(0); +var parseFloat = __webpack_require__(228); // `Number.parseFloat` method // https://tc39.es/ecma262/#sec-number.parseFloat @@ -45161,13 +44454,13 @@ $({ target: 'Number', stat: true, forced: Number.parseFloat !== parseFloat }, { /***/ }), -/* 431 */ +/* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var parseInt = __webpack_require__(258); +var $ = __webpack_require__(0); +var parseInt = __webpack_require__(229); // `Number.parseInt` method // https://tc39.es/ecma262/#sec-number.parseint @@ -45178,18 +44471,18 @@ $({ target: 'Number', stat: true, forced: Number.parseInt !== parseInt }, { /***/ }), -/* 432 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toIntegerOrInfinity = __webpack_require__(54); -var thisNumberValue = __webpack_require__(168); -var $repeat = __webpack_require__(166); -var log10 = __webpack_require__(250); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toIntegerOrInfinity = __webpack_require__(22); +var thisNumberValue = __webpack_require__(138); +var $repeat = __webpack_require__(136); +var log10 = __webpack_require__(221); +var fails = __webpack_require__(1); var $RangeError = RangeError; var $String = String; @@ -45283,17 +44576,17 @@ $({ target: 'Number', proto: true, forced: FORCED }, { /***/ }), -/* 433 */ +/* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toIntegerOrInfinity = __webpack_require__(54); -var thisNumberValue = __webpack_require__(168); -var $repeat = __webpack_require__(166); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toIntegerOrInfinity = __webpack_require__(22); +var thisNumberValue = __webpack_require__(138); +var $repeat = __webpack_require__(136); +var fails = __webpack_require__(1); var $RangeError = RangeError; var $String = String; @@ -45421,15 +44714,15 @@ $({ target: 'Number', proto: true, forced: FORCED }, { /***/ }), -/* 434 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var thisNumberValue = __webpack_require__(168); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var thisNumberValue = __webpack_require__(138); var nativeToPrecision = uncurryThis(1.1.toPrecision); @@ -45453,13 +44746,13 @@ $({ target: 'Number', proto: true, forced: FORCED }, { /***/ }), -/* 435 */ +/* 430 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var assign = __webpack_require__(259); +var $ = __webpack_require__(0); +var assign = __webpack_require__(230); // `Object.assign` method // https://tc39.es/ecma262/#sec-object.assign @@ -45470,15 +44763,15 @@ $({ target: 'Object', stat: true, arity: 2, forced: Object.assign !== assign }, /***/ }), -/* 436 */ +/* 431 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove from `core-js@4` -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var create = __webpack_require__(62); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var create = __webpack_require__(30); // `Object.create` method // https://tc39.es/ecma262/#sec-object.create @@ -45488,17 +44781,17 @@ $({ target: 'Object', stat: true, sham: !DESCRIPTORS }, { /***/ }), -/* 437 */ +/* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var FORCED = __webpack_require__(157); -var aCallable = __webpack_require__(42); -var toObject = __webpack_require__(47); -var definePropertyModule = __webpack_require__(51); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var FORCED = __webpack_require__(127); +var aCallable = __webpack_require__(10); +var toObject = __webpack_require__(15); +var definePropertyModule = __webpack_require__(19); // `Object.prototype.__defineGetter__` method // https://tc39.es/ecma262/#sec-object.prototype.__defineGetter__ @@ -45512,14 +44805,14 @@ if (DESCRIPTORS) { /***/ }), -/* 438 */ +/* 433 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var defineProperties = __webpack_require__(194).f; +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var defineProperties = __webpack_require__(165).f; // `Object.defineProperties` method // https://tc39.es/ecma262/#sec-object.defineproperties @@ -45530,14 +44823,14 @@ $({ target: 'Object', stat: true, forced: Object.defineProperties !== defineProp /***/ }), -/* 439 */ +/* 434 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var defineProperty = __webpack_require__(51).f; +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var defineProperty = __webpack_require__(19).f; // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty @@ -45548,17 +44841,17 @@ $({ target: 'Object', stat: true, forced: Object.defineProperty !== defineProper /***/ }), -/* 440 */ +/* 435 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var FORCED = __webpack_require__(157); -var aCallable = __webpack_require__(42); -var toObject = __webpack_require__(47); -var definePropertyModule = __webpack_require__(51); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var FORCED = __webpack_require__(127); +var aCallable = __webpack_require__(10); +var toObject = __webpack_require__(15); +var definePropertyModule = __webpack_require__(19); // `Object.prototype.__defineSetter__` method // https://tc39.es/ecma262/#sec-object.prototype.__defineSetter__ @@ -45572,13 +44865,13 @@ if (DESCRIPTORS) { /***/ }), -/* 441 */ +/* 436 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $entries = __webpack_require__(261).entries; +var $ = __webpack_require__(0); +var $entries = __webpack_require__(232).entries; // `Object.entries` method // https://tc39.es/ecma262/#sec-object.entries @@ -45590,16 +44883,16 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 442 */ +/* 437 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var FREEZING = __webpack_require__(112); -var fails = __webpack_require__(33); -var isObject = __webpack_require__(40); -var onFreeze = __webpack_require__(102).onFreeze; +var $ = __webpack_require__(0); +var FREEZING = __webpack_require__(81); +var fails = __webpack_require__(1); +var isObject = __webpack_require__(8); +var onFreeze = __webpack_require__(71).onFreeze; // eslint-disable-next-line es/no-object-freeze -- safe var $freeze = Object.freeze; @@ -45615,14 +44908,14 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING } /***/ }), -/* 443 */ +/* 438 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var iterate = __webpack_require__(56); -var createProperty = __webpack_require__(87); +var $ = __webpack_require__(0); +var iterate = __webpack_require__(24); +var createProperty = __webpack_require__(55); // `Object.fromEntries` method // https://tc39.es/ecma262/#sec-object.fromentries @@ -45638,16 +44931,16 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 444 */ +/* 439 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var toIndexedObject = __webpack_require__(57); -var nativeGetOwnPropertyDescriptor = __webpack_require__(63).f; -var DESCRIPTORS = __webpack_require__(38); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var toIndexedObject = __webpack_require__(25); +var nativeGetOwnPropertyDescriptor = __webpack_require__(31).f; +var DESCRIPTORS = __webpack_require__(6); var FORCED = !DESCRIPTORS || fails(function () { nativeGetOwnPropertyDescriptor(1); }); @@ -45661,17 +44954,17 @@ $({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, { /***/ }), -/* 445 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var ownKeys = __webpack_require__(197); -var toIndexedObject = __webpack_require__(57); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var createProperty = __webpack_require__(87); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var ownKeys = __webpack_require__(168); +var toIndexedObject = __webpack_require__(25); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var createProperty = __webpack_require__(55); // `Object.getOwnPropertyDescriptors` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors @@ -45693,14 +44986,14 @@ $({ target: 'Object', stat: true, sham: !DESCRIPTORS }, { /***/ }), -/* 446 */ +/* 441 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var getOwnPropertyNames = __webpack_require__(195).f; +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var getOwnPropertyNames = __webpack_require__(166).f; // eslint-disable-next-line es/no-object-getownpropertynames -- required for testing var FAILS_ON_PRIMITIVES = fails(function () { return !Object.getOwnPropertyNames(1); }); @@ -45713,16 +45006,16 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { /***/ }), -/* 447 */ +/* 442 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var NATIVE_SYMBOL = __webpack_require__(125); -var fails = __webpack_require__(33); -var getOwnPropertySymbolsModule = __webpack_require__(155); -var toObject = __webpack_require__(47); +var $ = __webpack_require__(0); +var NATIVE_SYMBOL = __webpack_require__(94); +var fails = __webpack_require__(1); +var getOwnPropertySymbolsModule = __webpack_require__(125); +var toObject = __webpack_require__(15); // V8 ~ Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 @@ -45739,16 +45032,16 @@ $({ target: 'Object', stat: true, forced: FORCED }, { /***/ }), -/* 448 */ +/* 443 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var toObject = __webpack_require__(47); -var nativeGetPrototypeOf = __webpack_require__(67); -var CORRECT_PROTOTYPE_GETTER = __webpack_require__(180); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var toObject = __webpack_require__(15); +var nativeGetPrototypeOf = __webpack_require__(35); +var CORRECT_PROTOTYPE_GETTER = __webpack_require__(151); var FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); }); @@ -45763,19 +45056,19 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PR /***/ }), -/* 449 */ +/* 444 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var requireObjectCoercible = __webpack_require__(52); -var toPropertyKey = __webpack_require__(94); -var iterate = __webpack_require__(56); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var requireObjectCoercible = __webpack_require__(20); +var toPropertyKey = __webpack_require__(63); +var iterate = __webpack_require__(24); +var fails = __webpack_require__(1); // eslint-disable-next-line es/no-object-groupby -- testing var nativeGroupBy = Object.groupBy; @@ -45810,13 +45103,13 @@ $({ target: 'Object', stat: true, forced: DOES_NOT_WORK_WITH_PRIMITIVES }, { /***/ }), -/* 450 */ +/* 445 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var hasOwn = __webpack_require__(45); +var $ = __webpack_require__(0); +var hasOwn = __webpack_require__(13); // `Object.hasOwn` method // https://tc39.es/ecma262/#sec-object.hasown @@ -45826,13 +45119,13 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 451 */ +/* 446 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $isExtensible = __webpack_require__(196); +var $ = __webpack_require__(0); +var $isExtensible = __webpack_require__(167); // `Object.isExtensible` method // https://tc39.es/ecma262/#sec-object.isextensible @@ -45843,16 +45136,16 @@ $({ target: 'Object', stat: true, forced: Object.isExtensible !== $isExtensible /***/ }), -/* 452 */ +/* 447 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var isObject = __webpack_require__(40); -var classof = __webpack_require__(64); -var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(174); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var isObject = __webpack_require__(8); +var classof = __webpack_require__(32); +var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(145); // eslint-disable-next-line es/no-object-isfrozen -- safe var $isFrozen = Object.isFrozen; @@ -45871,16 +45164,16 @@ $({ target: 'Object', stat: true, forced: FORCED }, { /***/ }), -/* 453 */ +/* 448 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var isObject = __webpack_require__(40); -var classof = __webpack_require__(64); -var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(174); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var isObject = __webpack_require__(8); +var classof = __webpack_require__(32); +var ARRAY_BUFFER_NON_EXTENSIBLE = __webpack_require__(145); // eslint-disable-next-line es/no-object-issealed -- safe var $isSealed = Object.isSealed; @@ -45899,13 +45192,13 @@ $({ target: 'Object', stat: true, forced: FORCED }, { /***/ }), -/* 454 */ +/* 449 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var is = __webpack_require__(269); +var $ = __webpack_require__(0); +var is = __webpack_require__(240); // `Object.is` method // https://tc39.es/ecma262/#sec-object.is @@ -45915,15 +45208,15 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 455 */ +/* 450 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var toObject = __webpack_require__(47); -var nativeKeys = __webpack_require__(134); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var toObject = __webpack_require__(15); +var nativeKeys = __webpack_require__(103); +var fails = __webpack_require__(1); var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); }); @@ -45937,18 +45230,18 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { /***/ }), -/* 456 */ +/* 451 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var FORCED = __webpack_require__(157); -var toObject = __webpack_require__(47); -var toPropertyKey = __webpack_require__(94); -var getPrototypeOf = __webpack_require__(67); -var getOwnPropertyDescriptor = __webpack_require__(63).f; +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var FORCED = __webpack_require__(127); +var toObject = __webpack_require__(15); +var toPropertyKey = __webpack_require__(63); +var getPrototypeOf = __webpack_require__(35); +var getOwnPropertyDescriptor = __webpack_require__(31).f; // `Object.prototype.__lookupGetter__` method // https://tc39.es/ecma262/#sec-object.prototype.__lookupGetter__ @@ -45967,18 +45260,18 @@ if (DESCRIPTORS) { /***/ }), -/* 457 */ +/* 452 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var FORCED = __webpack_require__(157); -var toObject = __webpack_require__(47); -var toPropertyKey = __webpack_require__(94); -var getPrototypeOf = __webpack_require__(67); -var getOwnPropertyDescriptor = __webpack_require__(63).f; +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var FORCED = __webpack_require__(127); +var toObject = __webpack_require__(15); +var toPropertyKey = __webpack_require__(63); +var getPrototypeOf = __webpack_require__(35); +var getOwnPropertyDescriptor = __webpack_require__(31).f; // `Object.prototype.__lookupSetter__` method // https://tc39.es/ecma262/#sec-object.prototype.__lookupSetter__ @@ -45997,16 +45290,16 @@ if (DESCRIPTORS) { /***/ }), -/* 458 */ +/* 453 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isObject = __webpack_require__(40); -var onFreeze = __webpack_require__(102).onFreeze; -var FREEZING = __webpack_require__(112); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var isObject = __webpack_require__(8); +var onFreeze = __webpack_require__(71).onFreeze; +var FREEZING = __webpack_require__(81); +var fails = __webpack_require__(1); // eslint-disable-next-line es/no-object-preventextensions -- safe var $preventExtensions = Object.preventExtensions; @@ -46022,17 +45315,17 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING } /***/ }), -/* 459 */ +/* 454 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var defineBuiltInAccessor = __webpack_require__(55); -var isObject = __webpack_require__(40); -var isPossiblePrototype = __webpack_require__(246); -var toObject = __webpack_require__(47); -var requireObjectCoercible = __webpack_require__(52); +var DESCRIPTORS = __webpack_require__(6); +var defineBuiltInAccessor = __webpack_require__(23); +var isObject = __webpack_require__(8); +var isPossiblePrototype = __webpack_require__(217); +var toObject = __webpack_require__(15); +var requireObjectCoercible = __webpack_require__(20); // eslint-disable-next-line es/no-object-getprototypeof -- safe var getPrototypeOf = Object.getPrototypeOf; @@ -46060,16 +45353,16 @@ if (DESCRIPTORS && getPrototypeOf && setPrototypeOf && !(PROTO in ObjectPrototyp /***/ }), -/* 460 */ +/* 455 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isObject = __webpack_require__(40); -var onFreeze = __webpack_require__(102).onFreeze; -var FREEZING = __webpack_require__(112); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var isObject = __webpack_require__(8); +var onFreeze = __webpack_require__(71).onFreeze; +var FREEZING = __webpack_require__(81); +var fails = __webpack_require__(1); // eslint-disable-next-line es/no-object-seal -- safe var $seal = Object.seal; @@ -46085,13 +45378,13 @@ $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING } /***/ }), -/* 461 */ +/* 456 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var setPrototypeOf = __webpack_require__(81); +var $ = __webpack_require__(0); +var setPrototypeOf = __webpack_require__(49); // `Object.setPrototypeOf` method // https://tc39.es/ecma262/#sec-object.setprototypeof @@ -46101,14 +45394,14 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 462 */ +/* 457 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var TO_STRING_TAG_SUPPORT = __webpack_require__(207); -var defineBuiltIn = __webpack_require__(49); -var toString = __webpack_require__(304); +var TO_STRING_TAG_SUPPORT = __webpack_require__(178); +var defineBuiltIn = __webpack_require__(17); +var toString = __webpack_require__(299); // `Object.prototype.toString` method // https://tc39.es/ecma262/#sec-object.prototype.tostring @@ -46118,13 +45411,13 @@ if (!TO_STRING_TAG_SUPPORT) { /***/ }), -/* 463 */ +/* 458 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $values = __webpack_require__(261).values; +var $ = __webpack_require__(0); +var $values = __webpack_require__(232).values; // `Object.values` method // https://tc39.es/ecma262/#sec-object.values @@ -46136,13 +45429,13 @@ $({ target: 'Object', stat: true }, { /***/ }), -/* 464 */ +/* 459 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $parseFloat = __webpack_require__(257); +var $ = __webpack_require__(0); +var $parseFloat = __webpack_require__(228); // `parseFloat` method // https://tc39.es/ecma262/#sec-parsefloat-string @@ -46152,13 +45445,13 @@ $({ global: true, forced: parseFloat !== $parseFloat }, { /***/ }), -/* 465 */ +/* 460 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $parseInt = __webpack_require__(258); +var $ = __webpack_require__(0); +var $parseInt = __webpack_require__(229); // `parseInt` method // https://tc39.es/ecma262/#sec-parseint-string-radix @@ -46168,18 +45461,18 @@ $({ global: true, forced: parseInt !== $parseInt }, { /***/ }), -/* 466 */ +/* 461 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var newPromiseCapabilityModule = __webpack_require__(90); -var perform = __webpack_require__(119); -var iterate = __webpack_require__(56); -var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(159); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var newPromiseCapabilityModule = __webpack_require__(58); +var perform = __webpack_require__(88); +var iterate = __webpack_require__(24); +var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(129); // `Promise.allSettled` method // https://tc39.es/ecma262/#sec-promise.allsettled @@ -46219,18 +45512,18 @@ $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION } /***/ }), -/* 467 */ +/* 462 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var newPromiseCapabilityModule = __webpack_require__(90); -var perform = __webpack_require__(119); -var iterate = __webpack_require__(56); -var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(159); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var newPromiseCapabilityModule = __webpack_require__(58); +var perform = __webpack_require__(88); +var iterate = __webpack_require__(24); +var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(129); // `Promise.all` method // https://tc39.es/ecma262/#sec-promise.all @@ -46265,19 +45558,19 @@ $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION } /***/ }), -/* 468 */ +/* 463 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var getBuiltIn = __webpack_require__(43); -var newPromiseCapabilityModule = __webpack_require__(90); -var perform = __webpack_require__(119); -var iterate = __webpack_require__(56); -var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(159); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var getBuiltIn = __webpack_require__(11); +var newPromiseCapabilityModule = __webpack_require__(58); +var perform = __webpack_require__(88); +var iterate = __webpack_require__(24); +var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(129); var PROMISE_ANY_ERROR = 'No one promise resolved'; @@ -46320,18 +45613,18 @@ $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION } /***/ }), -/* 469 */ +/* 464 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var IS_PURE = __webpack_require__(48); -var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(135).CONSTRUCTOR; -var NativePromiseConstructor = __webpack_require__(120); -var getBuiltIn = __webpack_require__(43); -var isCallable = __webpack_require__(46); -var defineBuiltIn = __webpack_require__(49); +var $ = __webpack_require__(0); +var IS_PURE = __webpack_require__(16); +var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(104).CONSTRUCTOR; +var NativePromiseConstructor = __webpack_require__(89); +var getBuiltIn = __webpack_require__(11); +var isCallable = __webpack_require__(14); +var defineBuiltIn = __webpack_require__(17); var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype; @@ -46353,35 +45646,35 @@ if (!IS_PURE && isCallable(NativePromiseConstructor)) { /***/ }), -/* 470 */ +/* 465 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var IS_PURE = __webpack_require__(48); -var IS_NODE = __webpack_require__(111); -var globalThis = __webpack_require__(35); -var path = __webpack_require__(158); -var call = __webpack_require__(36); -var defineBuiltIn = __webpack_require__(49); -var setPrototypeOf = __webpack_require__(81); -var setToStringTag = __webpack_require__(70); -var setSpecies = __webpack_require__(122); -var aCallable = __webpack_require__(42); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var anInstance = __webpack_require__(71); -var speciesConstructor = __webpack_require__(163); -var task = __webpack_require__(167).set; -var microtask = __webpack_require__(255); -var hostReportErrors = __webpack_require__(300); -var perform = __webpack_require__(119); -var Queue = __webpack_require__(265); -var InternalStateModule = __webpack_require__(53); -var NativePromiseConstructor = __webpack_require__(120); -var PromiseConstructorDetection = __webpack_require__(135); -var newPromiseCapabilityModule = __webpack_require__(90); +var $ = __webpack_require__(0); +var IS_PURE = __webpack_require__(16); +var IS_NODE = __webpack_require__(80); +var globalThis = __webpack_require__(3); +var path = __webpack_require__(128); +var call = __webpack_require__(4); +var defineBuiltIn = __webpack_require__(17); +var setPrototypeOf = __webpack_require__(49); +var setToStringTag = __webpack_require__(38); +var setSpecies = __webpack_require__(91); +var aCallable = __webpack_require__(10); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var anInstance = __webpack_require__(39); +var speciesConstructor = __webpack_require__(133); +var task = __webpack_require__(137).set; +var microtask = __webpack_require__(226); +var hostReportErrors = __webpack_require__(295); +var perform = __webpack_require__(88); +var Queue = __webpack_require__(236); +var InternalStateModule = __webpack_require__(21); +var NativePromiseConstructor = __webpack_require__(89); +var PromiseConstructorDetection = __webpack_require__(104); +var newPromiseCapabilityModule = __webpack_require__(58); var PROMISE = 'Promise'; var FORCED_PROMISE_CONSTRUCTOR = PromiseConstructorDetection.CONSTRUCTOR; @@ -46653,20 +45946,20 @@ setSpecies(PROMISE); /***/ }), -/* 471 */ +/* 466 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var IS_PURE = __webpack_require__(48); -var NativePromiseConstructor = __webpack_require__(120); -var fails = __webpack_require__(33); -var getBuiltIn = __webpack_require__(43); -var isCallable = __webpack_require__(46); -var speciesConstructor = __webpack_require__(163); -var promiseResolve = __webpack_require__(263); -var defineBuiltIn = __webpack_require__(49); +var $ = __webpack_require__(0); +var IS_PURE = __webpack_require__(16); +var NativePromiseConstructor = __webpack_require__(89); +var fails = __webpack_require__(1); +var getBuiltIn = __webpack_require__(11); +var isCallable = __webpack_require__(14); +var speciesConstructor = __webpack_require__(133); +var promiseResolve = __webpack_require__(234); +var defineBuiltIn = __webpack_require__(17); var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype; @@ -46703,33 +45996,33 @@ if (!IS_PURE && isCallable(NativePromiseConstructor)) { /***/ }), -/* 472 */ +/* 467 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's split to modules listed below -__webpack_require__(470); -__webpack_require__(467); +__webpack_require__(465); +__webpack_require__(462); +__webpack_require__(464); +__webpack_require__(468); __webpack_require__(469); -__webpack_require__(473); -__webpack_require__(474); -__webpack_require__(475); +__webpack_require__(470); /***/ }), -/* 473 */ +/* 468 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var aCallable = __webpack_require__(42); -var newPromiseCapabilityModule = __webpack_require__(90); -var perform = __webpack_require__(119); -var iterate = __webpack_require__(56); -var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(159); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var aCallable = __webpack_require__(10); +var newPromiseCapabilityModule = __webpack_require__(58); +var perform = __webpack_require__(88); +var iterate = __webpack_require__(24); +var PROMISE_STATICS_INCORRECT_ITERATION = __webpack_require__(129); // `Promise.race` method // https://tc39.es/ecma262/#sec-promise.race @@ -46751,14 +46044,14 @@ $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION } /***/ }), -/* 474 */ +/* 469 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var newPromiseCapabilityModule = __webpack_require__(90); -var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(135).CONSTRUCTOR; +var $ = __webpack_require__(0); +var newPromiseCapabilityModule = __webpack_require__(58); +var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(104).CONSTRUCTOR; // `Promise.reject` method // https://tc39.es/ecma262/#sec-promise.reject @@ -46773,17 +46066,17 @@ $({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR }, { /***/ }), -/* 475 */ +/* 470 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var IS_PURE = __webpack_require__(48); -var NativePromiseConstructor = __webpack_require__(120); -var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(135).CONSTRUCTOR; -var promiseResolve = __webpack_require__(263); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var IS_PURE = __webpack_require__(16); +var NativePromiseConstructor = __webpack_require__(89); +var FORCED_PROMISE_CONSTRUCTOR = __webpack_require__(104).CONSTRUCTOR; +var promiseResolve = __webpack_require__(234); var PromiseConstructorWrapper = getBuiltIn('Promise'); var CHECK_WRAPPER = IS_PURE && !FORCED_PROMISE_CONSTRUCTOR; @@ -46798,18 +46091,18 @@ $({ target: 'Promise', stat: true, forced: IS_PURE || FORCED_PROMISE_CONSTRUCTOR /***/ }), -/* 476 */ +/* 471 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var apply = __webpack_require__(74); -var slice = __webpack_require__(78); -var newPromiseCapabilityModule = __webpack_require__(90); -var aCallable = __webpack_require__(42); -var perform = __webpack_require__(119); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var apply = __webpack_require__(42); +var slice = __webpack_require__(46); +var newPromiseCapabilityModule = __webpack_require__(58); +var aCallable = __webpack_require__(10); +var perform = __webpack_require__(88); var Promise = globalThis.Promise; @@ -46838,13 +46131,13 @@ $({ target: 'Promise', stat: true, forced: FORCED }, { /***/ }), -/* 477 */ +/* 472 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var newPromiseCapabilityModule = __webpack_require__(90); +var $ = __webpack_require__(0); +var newPromiseCapabilityModule = __webpack_require__(58); // `Promise.withResolvers` method // https://tc39.es/ecma262/#sec-promise.withResolvers @@ -46861,16 +46154,16 @@ $({ target: 'Promise', stat: true }, { /***/ }), -/* 478 */ +/* 473 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var functionApply = __webpack_require__(74); -var aCallable = __webpack_require__(42); -var anObject = __webpack_require__(37); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var functionApply = __webpack_require__(42); +var aCallable = __webpack_require__(10); +var anObject = __webpack_require__(5); +var fails = __webpack_require__(1); // MS Edge argumentsList argument is optional var OPTIONAL_ARGUMENTS_LIST = !fails(function () { @@ -46888,20 +46181,20 @@ $({ target: 'Reflect', stat: true, forced: OPTIONAL_ARGUMENTS_LIST }, { /***/ }), -/* 479 */ +/* 474 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var apply = __webpack_require__(74); -var bind = __webpack_require__(236); -var aConstructor = __webpack_require__(173); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var create = __webpack_require__(62); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var apply = __webpack_require__(42); +var bind = __webpack_require__(207); +var aConstructor = __webpack_require__(144); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var create = __webpack_require__(30); +var fails = __webpack_require__(1); var nativeConstruct = getBuiltIn('Reflect', 'construct'); var ObjectPrototype = Object.prototype; @@ -46952,17 +46245,17 @@ $({ target: 'Reflect', stat: true, forced: FORCED, sham: FORCED }, { /***/ }), -/* 480 */ +/* 475 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var anObject = __webpack_require__(37); -var toPropertyKey = __webpack_require__(94); -var definePropertyModule = __webpack_require__(51); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var anObject = __webpack_require__(5); +var toPropertyKey = __webpack_require__(63); +var definePropertyModule = __webpack_require__(19); +var fails = __webpack_require__(1); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false var ERROR_INSTEAD_OF_FALSE = fails(function () { @@ -46988,14 +46281,14 @@ $({ target: 'Reflect', stat: true, forced: ERROR_INSTEAD_OF_FALSE, sham: !DESCRI /***/ }), -/* 481 */ +/* 476 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var anObject = __webpack_require__(37); -var getOwnPropertyDescriptor = __webpack_require__(63).f; +var $ = __webpack_require__(0); +var anObject = __webpack_require__(5); +var getOwnPropertyDescriptor = __webpack_require__(31).f; // `Reflect.deleteProperty` method // https://tc39.es/ecma262/#sec-reflect.deleteproperty @@ -47008,15 +46301,15 @@ $({ target: 'Reflect', stat: true }, { /***/ }), -/* 482 */ +/* 477 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var anObject = __webpack_require__(37); -var getOwnPropertyDescriptorModule = __webpack_require__(63); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var anObject = __webpack_require__(5); +var getOwnPropertyDescriptorModule = __webpack_require__(31); // `Reflect.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-reflect.getownpropertydescriptor @@ -47028,15 +46321,15 @@ $({ target: 'Reflect', stat: true, sham: !DESCRIPTORS }, { /***/ }), -/* 483 */ +/* 478 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var anObject = __webpack_require__(37); -var objectGetPrototypeOf = __webpack_require__(67); -var CORRECT_PROTOTYPE_GETTER = __webpack_require__(180); +var $ = __webpack_require__(0); +var anObject = __webpack_require__(5); +var objectGetPrototypeOf = __webpack_require__(35); +var CORRECT_PROTOTYPE_GETTER = __webpack_require__(151); // `Reflect.getPrototypeOf` method // https://tc39.es/ecma262/#sec-reflect.getprototypeof @@ -47048,18 +46341,18 @@ $({ target: 'Reflect', stat: true, sham: !CORRECT_PROTOTYPE_GETTER }, { /***/ }), -/* 484 */ +/* 479 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var isObject = __webpack_require__(40); -var anObject = __webpack_require__(37); -var isDataDescriptor = __webpack_require__(245); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var getPrototypeOf = __webpack_require__(67); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var isObject = __webpack_require__(8); +var anObject = __webpack_require__(5); +var isDataDescriptor = __webpack_require__(216); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var getPrototypeOf = __webpack_require__(35); // `Reflect.get` method // https://tc39.es/ecma262/#sec-reflect.get @@ -47080,12 +46373,12 @@ $({ target: 'Reflect', stat: true }, { /***/ }), -/* 485 */ +/* 480 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); +var $ = __webpack_require__(0); // `Reflect.has` method // https://tc39.es/ecma262/#sec-reflect.has @@ -47097,14 +46390,14 @@ $({ target: 'Reflect', stat: true }, { /***/ }), -/* 486 */ +/* 481 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var anObject = __webpack_require__(37); -var $isExtensible = __webpack_require__(196); +var $ = __webpack_require__(0); +var anObject = __webpack_require__(5); +var $isExtensible = __webpack_require__(167); // `Reflect.isExtensible` method // https://tc39.es/ecma262/#sec-reflect.isextensible @@ -47117,13 +46410,13 @@ $({ target: 'Reflect', stat: true }, { /***/ }), -/* 487 */ +/* 482 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var ownKeys = __webpack_require__(197); +var $ = __webpack_require__(0); +var ownKeys = __webpack_require__(168); // `Reflect.ownKeys` method // https://tc39.es/ecma262/#sec-reflect.ownkeys @@ -47133,15 +46426,15 @@ $({ target: 'Reflect', stat: true }, { /***/ }), -/* 488 */ +/* 483 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var anObject = __webpack_require__(37); -var FREEZING = __webpack_require__(112); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var anObject = __webpack_require__(5); +var FREEZING = __webpack_require__(81); // `Reflect.preventExtensions` method // https://tc39.es/ecma262/#sec-reflect.preventextensions @@ -47160,15 +46453,15 @@ $({ target: 'Reflect', stat: true, sham: !FREEZING }, { /***/ }), -/* 489 */ +/* 484 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var anObject = __webpack_require__(37); -var aPossiblePrototype = __webpack_require__(210); -var objectSetPrototypeOf = __webpack_require__(81); +var $ = __webpack_require__(0); +var anObject = __webpack_require__(5); +var aPossiblePrototype = __webpack_require__(181); +var objectSetPrototypeOf = __webpack_require__(49); // `Reflect.setPrototypeOf` method // https://tc39.es/ecma262/#sec-reflect.setprototypeof @@ -47187,21 +46480,21 @@ if (objectSetPrototypeOf) $({ target: 'Reflect', stat: true }, { /***/ }), -/* 490 */ +/* 485 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var isDataDescriptor = __webpack_require__(245); -var fails = __webpack_require__(33); -var definePropertyModule = __webpack_require__(51); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var getPrototypeOf = __webpack_require__(67); -var createPropertyDescriptor = __webpack_require__(73); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var isDataDescriptor = __webpack_require__(216); +var fails = __webpack_require__(1); +var definePropertyModule = __webpack_require__(19); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var getPrototypeOf = __webpack_require__(35); +var createPropertyDescriptor = __webpack_require__(41); // `Reflect.set` method // https://tc39.es/ecma262/#sec-reflect.set @@ -47244,14 +46537,14 @@ $({ target: 'Reflect', stat: true, forced: MS_EDGE_BUG }, { /***/ }), -/* 491 */ +/* 486 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var setToStringTag = __webpack_require__(70); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var setToStringTag = __webpack_require__(38); $({ global: true }, { Reflect: {} }); @@ -47261,33 +46554,33 @@ setToStringTag(globalThis.Reflect, 'Reflect', true); /***/ }), -/* 492 */ +/* 487 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var isForced = __webpack_require__(132); -var inheritIfRequired = __webpack_require__(101); -var createNonEnumerableProperty = __webpack_require__(59); -var create = __webpack_require__(62); -var getOwnPropertyNames = __webpack_require__(106).f; -var isPrototypeOf = __webpack_require__(68); -var isRegExp = __webpack_require__(152); -var toString = __webpack_require__(41); -var getRegExpFlags = __webpack_require__(107); -var stickyHelpers = __webpack_require__(160); -var proxyAccessor = __webpack_require__(264); -var defineBuiltIn = __webpack_require__(49); -var fails = __webpack_require__(33); -var hasOwn = __webpack_require__(45); -var enforceInternalState = __webpack_require__(53).enforce; -var setSpecies = __webpack_require__(122); -var wellKnownSymbol = __webpack_require__(39); -var UNSUPPORTED_DOT_ALL = __webpack_require__(200); -var UNSUPPORTED_NCG = __webpack_require__(267); +var DESCRIPTORS = __webpack_require__(6); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var isForced = __webpack_require__(101); +var inheritIfRequired = __webpack_require__(70); +var createNonEnumerableProperty = __webpack_require__(27); +var create = __webpack_require__(30); +var getOwnPropertyNames = __webpack_require__(75).f; +var isPrototypeOf = __webpack_require__(36); +var isRegExp = __webpack_require__(122); +var toString = __webpack_require__(9); +var getRegExpFlags = __webpack_require__(76); +var stickyHelpers = __webpack_require__(130); +var proxyAccessor = __webpack_require__(235); +var defineBuiltIn = __webpack_require__(17); +var fails = __webpack_require__(1); +var hasOwn = __webpack_require__(13); +var enforceInternalState = __webpack_require__(21).enforce; +var setSpecies = __webpack_require__(91); +var wellKnownSymbol = __webpack_require__(7); +var UNSUPPORTED_DOT_ALL = __webpack_require__(171); +var UNSUPPORTED_NCG = __webpack_require__(238); var MATCH = wellKnownSymbol('match'); var NativeRegExp = globalThis.RegExp; @@ -47465,16 +46758,16 @@ setSpecies('RegExp'); /***/ }), -/* 493 */ +/* 488 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var UNSUPPORTED_DOT_ALL = __webpack_require__(200); -var classof = __webpack_require__(64); -var defineBuiltInAccessor = __webpack_require__(55); -var getInternalState = __webpack_require__(53).get; +var DESCRIPTORS = __webpack_require__(6); +var UNSUPPORTED_DOT_ALL = __webpack_require__(171); +var classof = __webpack_require__(32); +var defineBuiltInAccessor = __webpack_require__(23); +var getInternalState = __webpack_require__(21).get; var RegExpPrototype = RegExp.prototype; var $TypeError = TypeError; @@ -47498,17 +46791,17 @@ if (DESCRIPTORS && UNSUPPORTED_DOT_ALL) { /***/ }), -/* 494 */ +/* 489 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var aString = __webpack_require__(288); -var hasOwn = __webpack_require__(45); -var padStart = __webpack_require__(165).start; -var WHITESPACES = __webpack_require__(138); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var aString = __webpack_require__(283); +var hasOwn = __webpack_require__(13); +var padStart = __webpack_require__(135).start; +var WHITESPACES = __webpack_require__(107); var $Array = Array; var $escape = RegExp.escape; @@ -47575,15 +46868,15 @@ $({ target: 'RegExp', stat: true, forced: FORCED }, { /***/ }), -/* 495 */ +/* 490 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var defineBuiltInAccessor = __webpack_require__(55); -var regExpFlagsDetection = __webpack_require__(266); -var regExpFlagsGetterImplementation = __webpack_require__(199); +var DESCRIPTORS = __webpack_require__(6); +var defineBuiltInAccessor = __webpack_require__(23); +var regExpFlagsDetection = __webpack_require__(237); +var regExpFlagsGetterImplementation = __webpack_require__(170); // `RegExp.prototype.flags` getter // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags @@ -47598,16 +46891,16 @@ if (DESCRIPTORS && !regExpFlagsDetection.correct) { /***/ }), -/* 496 */ +/* 491 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var MISSED_STICKY = __webpack_require__(160).MISSED_STICKY; -var classof = __webpack_require__(64); -var defineBuiltInAccessor = __webpack_require__(55); -var getInternalState = __webpack_require__(53).get; +var DESCRIPTORS = __webpack_require__(6); +var MISSED_STICKY = __webpack_require__(130).MISSED_STICKY; +var classof = __webpack_require__(32); +var defineBuiltInAccessor = __webpack_require__(23); +var getInternalState = __webpack_require__(21).get; var RegExpPrototype = RegExp.prototype; var $TypeError = TypeError; @@ -47631,18 +46924,18 @@ if (DESCRIPTORS && MISSED_STICKY) { /***/ }), -/* 497 */ +/* 492 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove from `core-js@4` since it's moved to entry points -__webpack_require__(209); -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var isCallable = __webpack_require__(46); -var anObject = __webpack_require__(37); -var toString = __webpack_require__(41); +__webpack_require__(180); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var isCallable = __webpack_require__(14); +var anObject = __webpack_require__(5); +var toString = __webpack_require__(9); var DELEGATES_TO_EXEC = function () { var execCalled = false; @@ -47673,17 +46966,17 @@ $({ target: 'RegExp', proto: true, forced: !DELEGATES_TO_EXEC }, { /***/ }), -/* 498 */ +/* 493 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var PROPER_FUNCTION_NAME = __webpack_require__(113).PROPER; -var defineBuiltIn = __webpack_require__(49); -var anObject = __webpack_require__(37); -var $toString = __webpack_require__(41); -var fails = __webpack_require__(33); -var getRegExpFlags = __webpack_require__(107); +var PROPER_FUNCTION_NAME = __webpack_require__(82).PROPER; +var defineBuiltIn = __webpack_require__(17); +var anObject = __webpack_require__(5); +var $toString = __webpack_require__(9); +var fails = __webpack_require__(1); +var getRegExpFlags = __webpack_require__(76); var TO_STRING = 'toString'; var RegExpPrototype = RegExp.prototype; @@ -47706,13 +46999,13 @@ if (NOT_GENERIC || INCORRECT_NAME) { /***/ }), -/* 499 */ +/* 494 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var collection = __webpack_require__(146); -var collectionStrong = __webpack_require__(224); +var collection = __webpack_require__(116); +var collectionStrong = __webpack_require__(195); // `Set` constructor // https://tc39.es/ecma262/#sec-set-objects @@ -47722,15 +47015,15 @@ collection('Set', function (init) { /***/ }), -/* 500 */ +/* 495 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var difference = __webpack_require__(305); -var fails = __webpack_require__(33); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var difference = __webpack_require__(300); +var fails = __webpack_require__(1); +var setMethodAcceptSetLike = __webpack_require__(77); var SET_LIKE_INCORRECT_BEHAVIOR = !setMethodAcceptSetLike('difference', function (result) { return result.size === 0; @@ -47766,15 +47059,15 @@ $({ target: 'Set', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 501 */ +/* 496 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var fails = __webpack_require__(33); -var intersection = __webpack_require__(306); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var fails = __webpack_require__(1); +var intersection = __webpack_require__(301); +var setMethodAcceptSetLike = __webpack_require__(77); var INCORRECT = !setMethodAcceptSetLike('intersection', function (result) { return result.size === 2 && result.has(1) && result.has(2); @@ -47791,14 +47084,14 @@ $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { /***/ }), -/* 502 */ +/* 497 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isDisjointFrom = __webpack_require__(307); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var isDisjointFrom = __webpack_require__(302); +var setMethodAcceptSetLike = __webpack_require__(77); var INCORRECT = !setMethodAcceptSetLike('isDisjointFrom', function (result) { return !result; @@ -47812,14 +47105,14 @@ $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { /***/ }), -/* 503 */ +/* 498 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isSubsetOf = __webpack_require__(308); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var isSubsetOf = __webpack_require__(303); +var setMethodAcceptSetLike = __webpack_require__(77); var INCORRECT = !setMethodAcceptSetLike('isSubsetOf', function (result) { return result; @@ -47833,14 +47126,14 @@ $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { /***/ }), -/* 504 */ +/* 499 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var isSupersetOf = __webpack_require__(309); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var isSupersetOf = __webpack_require__(304); +var setMethodAcceptSetLike = __webpack_require__(77); var INCORRECT = !setMethodAcceptSetLike('isSupersetOf', function (result) { return !result; @@ -47854,25 +47147,25 @@ $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { /***/ }), -/* 505 */ +/* 500 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(499); +__webpack_require__(494); /***/ }), -/* 506 */ +/* 501 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var symmetricDifference = __webpack_require__(310); -var setMethodGetKeysBeforeCloning = __webpack_require__(270); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var symmetricDifference = __webpack_require__(305); +var setMethodGetKeysBeforeCloning = __webpack_require__(241); +var setMethodAcceptSetLike = __webpack_require__(77); var FORCED = !setMethodAcceptSetLike('symmetricDifference') || !setMethodGetKeysBeforeCloning('symmetricDifference'); @@ -47884,15 +47177,15 @@ $({ target: 'Set', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 507 */ +/* 502 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var union = __webpack_require__(311); -var setMethodGetKeysBeforeCloning = __webpack_require__(270); -var setMethodAcceptSetLike = __webpack_require__(108); +var $ = __webpack_require__(0); +var union = __webpack_require__(306); +var setMethodGetKeysBeforeCloning = __webpack_require__(241); +var setMethodAcceptSetLike = __webpack_require__(77); var FORCED = !setMethodAcceptSetLike('union') || !setMethodGetKeysBeforeCloning('union'); @@ -47904,14 +47197,14 @@ $({ target: 'Set', proto: true, real: true, forced: FORCED }, { /***/ }), -/* 508 */ +/* 503 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.anchor` method // https://tc39.es/ecma262/#sec-string.prototype.anchor @@ -47923,17 +47216,17 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('anchor') }, { /***/ }), -/* 509 */ +/* 504 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toIntegerOrInfinity = __webpack_require__(54); -var toString = __webpack_require__(41); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toIntegerOrInfinity = __webpack_require__(22); +var toString = __webpack_require__(9); +var fails = __webpack_require__(1); var charAt = uncurryThis(''.charAt); @@ -47956,14 +47249,14 @@ $({ target: 'String', proto: true, forced: FORCED }, { /***/ }), -/* 510 */ +/* 505 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.big` method // https://tc39.es/ecma262/#sec-string.prototype.big @@ -47975,14 +47268,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('big') }, { /***/ }), -/* 511 */ +/* 506 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.blink` method // https://tc39.es/ecma262/#sec-string.prototype.blink @@ -47994,14 +47287,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('blink') }, { /***/ }), -/* 512 */ +/* 507 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.bold` method // https://tc39.es/ecma262/#sec-string.prototype.bold @@ -48013,13 +47306,13 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('bold') }, { /***/ }), -/* 513 */ +/* 508 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var codeAt = __webpack_require__(164).codeAt; +var $ = __webpack_require__(0); +var codeAt = __webpack_require__(134).codeAt; // `String.prototype.codePointAt` method // https://tc39.es/ecma262/#sec-string.prototype.codepointat @@ -48031,20 +47324,20 @@ $({ target: 'String', proto: true }, { /***/ }), -/* 514 */ +/* 509 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(98); -var getOwnPropertyDescriptor = __webpack_require__(63).f; -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var notARegExp = __webpack_require__(193); -var requireObjectCoercible = __webpack_require__(52); -var correctIsRegExpLogic = __webpack_require__(179); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(67); +var getOwnPropertyDescriptor = __webpack_require__(31).f; +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var notARegExp = __webpack_require__(164); +var requireObjectCoercible = __webpack_require__(20); +var correctIsRegExpLogic = __webpack_require__(150); +var IS_PURE = __webpack_require__(16); var slice = uncurryThis(''.slice); var min = Math.min; @@ -48072,14 +47365,14 @@ $({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGE /***/ }), -/* 515 */ +/* 510 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.fixed` method // https://tc39.es/ecma262/#sec-string.prototype.fixed @@ -48091,14 +47384,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fixed') }, { /***/ }), -/* 516 */ +/* 511 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.fontcolor` method // https://tc39.es/ecma262/#sec-string.prototype.fontcolor @@ -48110,14 +47403,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fontcolor') } /***/ }), -/* 517 */ +/* 512 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.fontsize` method // https://tc39.es/ecma262/#sec-string.prototype.fontsize @@ -48129,17 +47422,17 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fontsize') }, /***/ }), -/* 518 */ +/* 513 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var notARegExp = __webpack_require__(193); -var requireObjectCoercible = __webpack_require__(52); -var toString = __webpack_require__(41); -var correctIsRegExpLogic = __webpack_require__(179); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var notARegExp = __webpack_require__(164); +var requireObjectCoercible = __webpack_require__(20); +var toString = __webpack_require__(9); +var correctIsRegExpLogic = __webpack_require__(150); var stringIndexOf = uncurryThis(''.indexOf); @@ -48157,15 +47450,15 @@ $({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, /***/ }), -/* 519 */ +/* 514 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toString = __webpack_require__(41); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toString = __webpack_require__(9); var charCodeAt = uncurryThis(''.charCodeAt); @@ -48187,14 +47480,14 @@ $({ target: 'String', proto: true }, { /***/ }), -/* 520 */ +/* 515 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.italics` method // https://tc39.es/ecma262/#sec-string.prototype.italics @@ -48206,14 +47499,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('italics') }, /***/ }), -/* 521 */ +/* 516 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.link` method // https://tc39.es/ecma262/#sec-string.prototype.link @@ -48225,34 +47518,34 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('link') }, { /***/ }), -/* 522 */ +/* 517 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable es/no-string-prototype-matchall -- safe */ -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(98); -var createIteratorConstructor = __webpack_require__(189); -var createIterResultObject = __webpack_require__(96); -var requireObjectCoercible = __webpack_require__(52); -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var classof = __webpack_require__(64); -var isRegExp = __webpack_require__(152); -var getRegExpFlags = __webpack_require__(107); -var getMethod = __webpack_require__(60); -var defineBuiltIn = __webpack_require__(49); -var fails = __webpack_require__(33); -var wellKnownSymbol = __webpack_require__(39); -var speciesConstructor = __webpack_require__(163); -var advanceStringIndex = __webpack_require__(139); -var regExpExec = __webpack_require__(136); -var InternalStateModule = __webpack_require__(53); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(67); +var createIteratorConstructor = __webpack_require__(160); +var createIterResultObject = __webpack_require__(65); +var requireObjectCoercible = __webpack_require__(20); +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var classof = __webpack_require__(32); +var isRegExp = __webpack_require__(122); +var getRegExpFlags = __webpack_require__(76); +var getMethod = __webpack_require__(28); +var defineBuiltIn = __webpack_require__(17); +var fails = __webpack_require__(1); +var wellKnownSymbol = __webpack_require__(7); +var speciesConstructor = __webpack_require__(133); +var advanceStringIndex = __webpack_require__(109); +var regExpExec = __webpack_require__(105); +var InternalStateModule = __webpack_require__(21); +var IS_PURE = __webpack_require__(16); var MATCH_ALL = wellKnownSymbol('matchAll'); var REGEXP_STRING = 'RegExp String'; @@ -48334,23 +47627,23 @@ IS_PURE || MATCH_ALL in RegExpPrototype || defineBuiltIn(RegExpPrototype, MATCH_ /***/ }), -/* 523 */ +/* 518 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var fixRegExpWellKnownSymbolLogic = __webpack_require__(150); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var requireObjectCoercible = __webpack_require__(52); -var getMethod = __webpack_require__(60); -var advanceStringIndex = __webpack_require__(139); -var getRegExpFlags = __webpack_require__(107); -var regExpExec = __webpack_require__(136); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var fixRegExpWellKnownSymbolLogic = __webpack_require__(120); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var requireObjectCoercible = __webpack_require__(20); +var getMethod = __webpack_require__(28); +var advanceStringIndex = __webpack_require__(109); +var getRegExpFlags = __webpack_require__(76); +var regExpExec = __webpack_require__(105); var stringIndexOf = uncurryThis(''.indexOf); @@ -48395,14 +47688,14 @@ fixRegExpWellKnownSymbolLogic('match', function (MATCH, nativeMatch, maybeCallNa /***/ }), -/* 524 */ +/* 519 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $padEnd = __webpack_require__(165).end; -var WEBKIT_BUG = __webpack_require__(271); +var $ = __webpack_require__(0); +var $padEnd = __webpack_require__(135).end; +var WEBKIT_BUG = __webpack_require__(242); // `String.prototype.padEnd` method // https://tc39.es/ecma262/#sec-string.prototype.padend @@ -48414,14 +47707,14 @@ $({ target: 'String', proto: true, forced: WEBKIT_BUG }, { /***/ }), -/* 525 */ +/* 520 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $padStart = __webpack_require__(165).start; -var WEBKIT_BUG = __webpack_require__(271); +var $ = __webpack_require__(0); +var $padStart = __webpack_require__(135).start; +var WEBKIT_BUG = __webpack_require__(242); // `String.prototype.padStart` method // https://tc39.es/ecma262/#sec-string.prototype.padstart @@ -48433,17 +47726,17 @@ $({ target: 'String', proto: true, forced: WEBKIT_BUG }, { /***/ }), -/* 526 */ +/* 521 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toIndexedObject = __webpack_require__(57); -var toObject = __webpack_require__(47); -var toString = __webpack_require__(41); -var lengthOfArrayLike = __webpack_require__(50); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toIndexedObject = __webpack_require__(25); +var toObject = __webpack_require__(15); +var toString = __webpack_require__(9); +var lengthOfArrayLike = __webpack_require__(18); var push = uncurryThis([].push); var join = uncurryThis([].join); @@ -48468,13 +47761,13 @@ $({ target: 'String', stat: true }, { /***/ }), -/* 527 */ +/* 522 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var repeat = __webpack_require__(166); +var $ = __webpack_require__(0); +var repeat = __webpack_require__(136); // `String.prototype.repeat` method // https://tc39.es/ecma262/#sec-string.prototype.repeat @@ -48484,24 +47777,24 @@ $({ target: 'String', proto: true }, { /***/ }), -/* 528 */ +/* 523 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var isRegExp = __webpack_require__(152); -var toString = __webpack_require__(41); -var getMethod = __webpack_require__(60); -var getRegExpFlags = __webpack_require__(107); -var getSubstitution = __webpack_require__(240); -var wellKnownSymbol = __webpack_require__(39); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var isRegExp = __webpack_require__(122); +var toString = __webpack_require__(9); +var getMethod = __webpack_require__(28); +var getRegExpFlags = __webpack_require__(76); +var getSubstitution = __webpack_require__(211); +var wellKnownSymbol = __webpack_require__(7); +var IS_PURE = __webpack_require__(16); var REPLACE = wellKnownSymbol('replace'); var $TypeError = TypeError; @@ -48552,29 +47845,29 @@ $({ target: 'String', proto: true }, { /***/ }), -/* 529 */ +/* 524 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var apply = __webpack_require__(74); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var fixRegExpWellKnownSymbolLogic = __webpack_require__(150); -var fails = __webpack_require__(33); -var anObject = __webpack_require__(37); -var isCallable = __webpack_require__(46); -var isObject = __webpack_require__(40); -var toIntegerOrInfinity = __webpack_require__(54); -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var requireObjectCoercible = __webpack_require__(52); -var advanceStringIndex = __webpack_require__(139); -var getMethod = __webpack_require__(60); -var getSubstitution = __webpack_require__(240); -var getRegExpFlags = __webpack_require__(107); -var regExpExec = __webpack_require__(136); -var wellKnownSymbol = __webpack_require__(39); +var apply = __webpack_require__(42); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var fixRegExpWellKnownSymbolLogic = __webpack_require__(120); +var fails = __webpack_require__(1); +var anObject = __webpack_require__(5); +var isCallable = __webpack_require__(14); +var isObject = __webpack_require__(8); +var toIntegerOrInfinity = __webpack_require__(22); +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var requireObjectCoercible = __webpack_require__(20); +var advanceStringIndex = __webpack_require__(109); +var getMethod = __webpack_require__(28); +var getSubstitution = __webpack_require__(211); +var getRegExpFlags = __webpack_require__(76); +var regExpExec = __webpack_require__(105); +var wellKnownSymbol = __webpack_require__(7); var REPLACE = wellKnownSymbol('replace'); var max = Math.max; @@ -48703,20 +47996,20 @@ fixRegExpWellKnownSymbolLogic('replace', function (_, nativeReplace, maybeCallNa /***/ }), -/* 530 */ +/* 525 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var fixRegExpWellKnownSymbolLogic = __webpack_require__(150); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var requireObjectCoercible = __webpack_require__(52); -var sameValue = __webpack_require__(269); -var toString = __webpack_require__(41); -var getMethod = __webpack_require__(60); -var regExpExec = __webpack_require__(136); +var call = __webpack_require__(4); +var fixRegExpWellKnownSymbolLogic = __webpack_require__(120); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var requireObjectCoercible = __webpack_require__(20); +var sameValue = __webpack_require__(240); +var toString = __webpack_require__(9); +var getMethod = __webpack_require__(28); +var regExpExec = __webpack_require__(105); // @@search logic fixRegExpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCallNative) { @@ -48748,14 +48041,14 @@ fixRegExpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCal /***/ }), -/* 531 */ +/* 526 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.small` method // https://tc39.es/ecma262/#sec-string.prototype.small @@ -48767,25 +48060,25 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('small') }, { /***/ }), -/* 532 */ +/* 527 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var fixRegExpWellKnownSymbolLogic = __webpack_require__(150); -var anObject = __webpack_require__(37); -var isObject = __webpack_require__(40); -var requireObjectCoercible = __webpack_require__(52); -var speciesConstructor = __webpack_require__(163); -var advanceStringIndex = __webpack_require__(139); -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var getMethod = __webpack_require__(60); -var regExpExec = __webpack_require__(136); -var stickyHelpers = __webpack_require__(160); -var fails = __webpack_require__(33); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var fixRegExpWellKnownSymbolLogic = __webpack_require__(120); +var anObject = __webpack_require__(5); +var isObject = __webpack_require__(8); +var requireObjectCoercible = __webpack_require__(20); +var speciesConstructor = __webpack_require__(133); +var advanceStringIndex = __webpack_require__(109); +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var getMethod = __webpack_require__(28); +var regExpExec = __webpack_require__(105); +var stickyHelpers = __webpack_require__(130); +var fails = __webpack_require__(1); var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y; var MAX_UINT32 = 0xFFFFFFFF; @@ -48885,20 +48178,20 @@ fixRegExpWellKnownSymbolLogic('split', function (SPLIT, nativeSplit, maybeCallNa /***/ }), -/* 533 */ +/* 528 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(98); -var getOwnPropertyDescriptor = __webpack_require__(63).f; -var toLength = __webpack_require__(77); -var toString = __webpack_require__(41); -var notARegExp = __webpack_require__(193); -var requireObjectCoercible = __webpack_require__(52); -var correctIsRegExpLogic = __webpack_require__(179); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(67); +var getOwnPropertyDescriptor = __webpack_require__(31).f; +var toLength = __webpack_require__(45); +var toString = __webpack_require__(9); +var notARegExp = __webpack_require__(164); +var requireObjectCoercible = __webpack_require__(20); +var correctIsRegExpLogic = __webpack_require__(150); +var IS_PURE = __webpack_require__(16); var stringSlice = uncurryThis(''.slice); var min = Math.min; @@ -48924,14 +48217,14 @@ $({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGE /***/ }), -/* 534 */ +/* 529 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.strike` method // https://tc39.es/ecma262/#sec-string.prototype.strike @@ -48943,14 +48236,14 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('strike') }, { /***/ }), -/* 535 */ +/* 530 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.sub` method // https://tc39.es/ecma262/#sec-string.prototype.sub @@ -48962,16 +48255,16 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('sub') }, { /***/ }), -/* 536 */ +/* 531 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toIntegerOrInfinity = __webpack_require__(54); -var toString = __webpack_require__(41); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toIntegerOrInfinity = __webpack_require__(22); +var toString = __webpack_require__(9); var stringSlice = uncurryThis(''.slice); var max = Math.max; @@ -48999,14 +48292,14 @@ $({ target: 'String', proto: true, forced: FORCED }, { /***/ }), -/* 537 */ +/* 532 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var createHTML = __webpack_require__(72); -var forcedStringHTMLMethod = __webpack_require__(76); +var $ = __webpack_require__(0); +var createHTML = __webpack_require__(40); +var forcedStringHTMLMethod = __webpack_require__(44); // `String.prototype.sup` method // https://tc39.es/ecma262/#sec-string.prototype.sup @@ -49018,17 +48311,17 @@ $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('sup') }, { /***/ }), -/* 538 */ +/* 533 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var requireObjectCoercible = __webpack_require__(52); -var toString = __webpack_require__(41); -var fails = __webpack_require__(33); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var requireObjectCoercible = __webpack_require__(20); +var toString = __webpack_require__(9); +var fails = __webpack_require__(1); var $Array = Array; var charAt = uncurryThis(''.charAt); @@ -49068,15 +48361,15 @@ $({ target: 'String', proto: true, forced: TO_STRING_CONVERSION_BUG }, { /***/ }), -/* 539 */ +/* 534 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this line from `core-js@4` -__webpack_require__(541); -var $ = __webpack_require__(32); -var trimEnd = __webpack_require__(272); +__webpack_require__(536); +var $ = __webpack_require__(0); +var trimEnd = __webpack_require__(243); // `String.prototype.trimEnd` method // https://tc39.es/ecma262/#sec-string.prototype.trimend @@ -49087,13 +48380,13 @@ $({ target: 'String', proto: true, name: 'trimEnd', forced: ''.trimEnd !== trimE /***/ }), -/* 540 */ +/* 535 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var trimStart = __webpack_require__(273); +var $ = __webpack_require__(0); +var trimStart = __webpack_require__(244); // `String.prototype.trimLeft` method // https://tc39.es/ecma262/#sec-string.prototype.trimleft @@ -49104,13 +48397,13 @@ $({ target: 'String', proto: true, name: 'trimStart', forced: ''.trimLeft !== tr /***/ }), -/* 541 */ +/* 536 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var trimEnd = __webpack_require__(272); +var $ = __webpack_require__(0); +var trimEnd = __webpack_require__(243); // `String.prototype.trimRight` method // https://tc39.es/ecma262/#sec-string.prototype.trimend @@ -49121,15 +48414,15 @@ $({ target: 'String', proto: true, name: 'trimEnd', forced: ''.trimRight !== tri /***/ }), -/* 542 */ +/* 537 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this line from `core-js@4` -__webpack_require__(540); -var $ = __webpack_require__(32); -var trimStart = __webpack_require__(273); +__webpack_require__(535); +var $ = __webpack_require__(0); +var trimStart = __webpack_require__(244); // `String.prototype.trimStart` method // https://tc39.es/ecma262/#sec-string.prototype.trimstart @@ -49140,14 +48433,14 @@ $({ target: 'String', proto: true, name: 'trimStart', forced: ''.trimStart !== t /***/ }), -/* 543 */ +/* 538 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var $trim = __webpack_require__(124).trim; -var forcedStringTrimMethod = __webpack_require__(203); +var $ = __webpack_require__(0); +var $trim = __webpack_require__(93).trim; +var forcedStringTrimMethod = __webpack_require__(174); // `String.prototype.trim` method // https://tc39.es/ecma262/#sec-string.prototype.trim @@ -49159,25 +48452,25 @@ $({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, { /***/ }), -/* 544 */ +/* 539 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var isPrototypeOf = __webpack_require__(68); -var getPrototypeOf = __webpack_require__(67); -var setPrototypeOf = __webpack_require__(81); -var copyConstructorProperties = __webpack_require__(110); -var create = __webpack_require__(62); -var createNonEnumerableProperty = __webpack_require__(59); -var createPropertyDescriptor = __webpack_require__(73); -var installErrorStack = __webpack_require__(185); -var normalizeStringArgument = __webpack_require__(118); -var wellKnownSymbol = __webpack_require__(39); -var fails = __webpack_require__(33); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var isPrototypeOf = __webpack_require__(36); +var getPrototypeOf = __webpack_require__(35); +var setPrototypeOf = __webpack_require__(49); +var copyConstructorProperties = __webpack_require__(79); +var create = __webpack_require__(30); +var createNonEnumerableProperty = __webpack_require__(27); +var createPropertyDescriptor = __webpack_require__(41); +var installErrorStack = __webpack_require__(156); +var normalizeStringArgument = __webpack_require__(87); +var wellKnownSymbol = __webpack_require__(7); +var fails = __webpack_require__(1); +var IS_PURE = __webpack_require__(16); var NativeSuppressedError = globalThis.SuppressedError; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); @@ -49230,15 +48523,15 @@ $({ global: true, constructor: true, arity: 3, forced: PATCH }, { /***/ }), -/* 545 */ +/* 540 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var defineWellKnownSymbol = __webpack_require__(66); -var defineProperty = __webpack_require__(51).f; -var getOwnPropertyDescriptor = __webpack_require__(63).f; +var globalThis = __webpack_require__(3); +var defineWellKnownSymbol = __webpack_require__(34); +var defineProperty = __webpack_require__(19).f; +var getOwnPropertyDescriptor = __webpack_require__(31).f; var Symbol = globalThis.Symbol; @@ -49258,12 +48551,12 @@ if (Symbol) { /***/ }), -/* 546 */ +/* 541 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.asyncIterator` well-known symbol // https://tc39.es/ecma262/#sec-symbol.asynciterator @@ -49271,48 +48564,48 @@ defineWellKnownSymbol('asyncIterator'); /***/ }), -/* 547 */ +/* 542 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var IS_PURE = __webpack_require__(48); -var DESCRIPTORS = __webpack_require__(38); -var NATIVE_SYMBOL = __webpack_require__(125); -var fails = __webpack_require__(33); -var hasOwn = __webpack_require__(45); -var isPrototypeOf = __webpack_require__(68); -var anObject = __webpack_require__(37); -var toIndexedObject = __webpack_require__(57); -var toPropertyKey = __webpack_require__(94); -var $toString = __webpack_require__(41); -var createPropertyDescriptor = __webpack_require__(73); -var nativeObjectCreate = __webpack_require__(62); -var objectKeys = __webpack_require__(134); -var getOwnPropertyNamesModule = __webpack_require__(106); -var getOwnPropertyNamesExternal = __webpack_require__(195); -var getOwnPropertySymbolsModule = __webpack_require__(155); -var getOwnPropertyDescriptorModule = __webpack_require__(63); -var definePropertyModule = __webpack_require__(51); -var definePropertiesModule = __webpack_require__(194); -var propertyIsEnumerableModule = __webpack_require__(156); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltInAccessor = __webpack_require__(55); -var shared = __webpack_require__(123); -var sharedKey = __webpack_require__(161); -var hiddenKeys = __webpack_require__(131); -var uid = __webpack_require__(126); -var wellKnownSymbol = __webpack_require__(39); -var wrappedWellKnownSymbolModule = __webpack_require__(281); -var defineWellKnownSymbol = __webpack_require__(66); -var defineSymbolToPrimitive = __webpack_require__(274); -var setToStringTag = __webpack_require__(70); -var InternalStateModule = __webpack_require__(53); -var $forEach = __webpack_require__(58).forEach; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var IS_PURE = __webpack_require__(16); +var DESCRIPTORS = __webpack_require__(6); +var NATIVE_SYMBOL = __webpack_require__(94); +var fails = __webpack_require__(1); +var hasOwn = __webpack_require__(13); +var isPrototypeOf = __webpack_require__(36); +var anObject = __webpack_require__(5); +var toIndexedObject = __webpack_require__(25); +var toPropertyKey = __webpack_require__(63); +var $toString = __webpack_require__(9); +var createPropertyDescriptor = __webpack_require__(41); +var nativeObjectCreate = __webpack_require__(30); +var objectKeys = __webpack_require__(103); +var getOwnPropertyNamesModule = __webpack_require__(75); +var getOwnPropertyNamesExternal = __webpack_require__(166); +var getOwnPropertySymbolsModule = __webpack_require__(125); +var getOwnPropertyDescriptorModule = __webpack_require__(31); +var definePropertyModule = __webpack_require__(19); +var definePropertiesModule = __webpack_require__(165); +var propertyIsEnumerableModule = __webpack_require__(126); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltInAccessor = __webpack_require__(23); +var shared = __webpack_require__(92); +var sharedKey = __webpack_require__(131); +var hiddenKeys = __webpack_require__(100); +var uid = __webpack_require__(95); +var wellKnownSymbol = __webpack_require__(7); +var wrappedWellKnownSymbolModule = __webpack_require__(252); +var defineWellKnownSymbol = __webpack_require__(34); +var defineSymbolToPrimitive = __webpack_require__(245); +var setToStringTag = __webpack_require__(38); +var InternalStateModule = __webpack_require__(21); +var $forEach = __webpack_require__(26).forEach; var HIDDEN = sharedKey('hidden'); var SYMBOL = 'Symbol'; @@ -49541,23 +48834,23 @@ hiddenKeys[HIDDEN] = true; /***/ }), -/* 548 */ +/* 543 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // `Symbol.prototype.description` getter // https://tc39.es/ecma262/#sec-symbol.prototype.description -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var hasOwn = __webpack_require__(45); -var isCallable = __webpack_require__(46); -var isPrototypeOf = __webpack_require__(68); -var toString = __webpack_require__(41); -var defineBuiltInAccessor = __webpack_require__(55); -var copyConstructorProperties = __webpack_require__(110); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var hasOwn = __webpack_require__(13); +var isCallable = __webpack_require__(14); +var isPrototypeOf = __webpack_require__(36); +var toString = __webpack_require__(9); +var defineBuiltInAccessor = __webpack_require__(23); +var copyConstructorProperties = __webpack_require__(79); var NativeSymbol = globalThis.Symbol; var SymbolPrototype = NativeSymbol && NativeSymbol.prototype; @@ -49608,15 +48901,15 @@ if (DESCRIPTORS && isCallable(NativeSymbol) && (!('description' in SymbolPrototy /***/ }), -/* 549 */ +/* 544 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var defineWellKnownSymbol = __webpack_require__(66); -var defineProperty = __webpack_require__(51).f; -var getOwnPropertyDescriptor = __webpack_require__(63).f; +var globalThis = __webpack_require__(3); +var defineWellKnownSymbol = __webpack_require__(34); +var defineProperty = __webpack_require__(19).f; +var getOwnPropertyDescriptor = __webpack_require__(31).f; var Symbol = globalThis.Symbol; @@ -49636,17 +48929,17 @@ if (Symbol) { /***/ }), -/* 550 */ +/* 545 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var hasOwn = __webpack_require__(45); -var toString = __webpack_require__(41); -var shared = __webpack_require__(123); -var NATIVE_SYMBOL_REGISTRY = __webpack_require__(275); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var hasOwn = __webpack_require__(13); +var toString = __webpack_require__(9); +var shared = __webpack_require__(92); +var NATIVE_SYMBOL_REGISTRY = __webpack_require__(246); var StringToSymbolRegistry = shared('string-to-symbol-registry'); var SymbolToStringRegistry = shared('symbol-to-string-registry'); @@ -49666,12 +48959,12 @@ $({ target: 'Symbol', stat: true, forced: !NATIVE_SYMBOL_REGISTRY }, { /***/ }), -/* 551 */ +/* 546 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.hasInstance` well-known symbol // https://tc39.es/ecma262/#sec-symbol.hasinstance @@ -49679,12 +48972,12 @@ defineWellKnownSymbol('hasInstance'); /***/ }), -/* 552 */ +/* 547 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.isConcatSpreadable` well-known symbol // https://tc39.es/ecma262/#sec-symbol.isconcatspreadable @@ -49692,12 +48985,12 @@ defineWellKnownSymbol('isConcatSpreadable'); /***/ }), -/* 553 */ +/* 548 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.iterator` well-known symbol // https://tc39.es/ecma262/#sec-symbol.iterator @@ -49705,31 +48998,31 @@ defineWellKnownSymbol('iterator'); /***/ }), -/* 554 */ +/* 549 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's split to modules listed below -__webpack_require__(547); +__webpack_require__(542); +__webpack_require__(545); __webpack_require__(550); -__webpack_require__(555); -__webpack_require__(283); -__webpack_require__(447); +__webpack_require__(254); +__webpack_require__(442); /***/ }), -/* 555 */ +/* 550 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var hasOwn = __webpack_require__(45); -var isSymbol = __webpack_require__(104); -var tryToString = __webpack_require__(109); -var shared = __webpack_require__(123); -var NATIVE_SYMBOL_REGISTRY = __webpack_require__(275); +var $ = __webpack_require__(0); +var hasOwn = __webpack_require__(13); +var isSymbol = __webpack_require__(73); +var tryToString = __webpack_require__(78); +var shared = __webpack_require__(92); +var NATIVE_SYMBOL_REGISTRY = __webpack_require__(246); var SymbolToStringRegistry = shared('symbol-to-string-registry'); @@ -49744,12 +49037,12 @@ $({ target: 'Symbol', stat: true, forced: !NATIVE_SYMBOL_REGISTRY }, { /***/ }), -/* 556 */ +/* 551 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.matchAll` well-known symbol // https://tc39.es/ecma262/#sec-symbol.matchall @@ -49757,12 +49050,12 @@ defineWellKnownSymbol('matchAll'); /***/ }), -/* 557 */ +/* 552 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.match` well-known symbol // https://tc39.es/ecma262/#sec-symbol.match @@ -49770,12 +49063,12 @@ defineWellKnownSymbol('match'); /***/ }), -/* 558 */ +/* 553 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.replace` well-known symbol // https://tc39.es/ecma262/#sec-symbol.replace @@ -49783,12 +49076,12 @@ defineWellKnownSymbol('replace'); /***/ }), -/* 559 */ +/* 554 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.search` well-known symbol // https://tc39.es/ecma262/#sec-symbol.search @@ -49796,12 +49089,12 @@ defineWellKnownSymbol('search'); /***/ }), -/* 560 */ +/* 555 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.species` well-known symbol // https://tc39.es/ecma262/#sec-symbol.species @@ -49809,12 +49102,12 @@ defineWellKnownSymbol('species'); /***/ }), -/* 561 */ +/* 556 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.split` well-known symbol // https://tc39.es/ecma262/#sec-symbol.split @@ -49822,13 +49115,13 @@ defineWellKnownSymbol('split'); /***/ }), -/* 562 */ +/* 557 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); -var defineSymbolToPrimitive = __webpack_require__(274); +var defineWellKnownSymbol = __webpack_require__(34); +var defineSymbolToPrimitive = __webpack_require__(245); // `Symbol.toPrimitive` well-known symbol // https://tc39.es/ecma262/#sec-symbol.toprimitive @@ -49840,14 +49133,14 @@ defineSymbolToPrimitive(); /***/ }), -/* 563 */ +/* 558 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); -var defineWellKnownSymbol = __webpack_require__(66); -var setToStringTag = __webpack_require__(70); +var getBuiltIn = __webpack_require__(11); +var defineWellKnownSymbol = __webpack_require__(34); +var setToStringTag = __webpack_require__(38); // `Symbol.toStringTag` well-known symbol // https://tc39.es/ecma262/#sec-symbol.tostringtag @@ -49859,12 +49152,12 @@ setToStringTag(getBuiltIn('Symbol'), 'Symbol'); /***/ }), -/* 564 */ +/* 559 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineWellKnownSymbol = __webpack_require__(66); +var defineWellKnownSymbol = __webpack_require__(34); // `Symbol.unscopables` well-known symbol // https://tc39.es/ecma262/#sec-symbol.unscopables @@ -49872,14 +49165,14 @@ defineWellKnownSymbol('unscopables'); /***/ }), -/* 565 */ +/* 560 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var lengthOfArrayLike = __webpack_require__(50); -var toIntegerOrInfinity = __webpack_require__(54); +var ArrayBufferViewCore = __webpack_require__(12); +var lengthOfArrayLike = __webpack_require__(18); +var toIntegerOrInfinity = __webpack_require__(22); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -49896,14 +49189,14 @@ exportTypedArrayMethod('at', function at(index) { /***/ }), -/* 566 */ +/* 561 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uncurryThis = __webpack_require__(34); -var ArrayBufferViewCore = __webpack_require__(44); -var $ArrayCopyWithin = __webpack_require__(215); +var uncurryThis = __webpack_require__(2); +var ArrayBufferViewCore = __webpack_require__(12); +var $ArrayCopyWithin = __webpack_require__(186); var u$ArrayCopyWithin = uncurryThis($ArrayCopyWithin); var aTypedArray = ArrayBufferViewCore.aTypedArray; @@ -49917,13 +49210,13 @@ exportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end /***/ }), -/* 567 */ +/* 562 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $every = __webpack_require__(58).every; +var ArrayBufferViewCore = __webpack_require__(12); +var $every = __webpack_require__(26).every; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -49936,18 +49229,18 @@ exportTypedArrayMethod('every', function every(callbackfn /* , thisArg */) { /***/ }), -/* 568 */ +/* 563 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $fill = __webpack_require__(175); -var toBigInt = __webpack_require__(205); -var classof = __webpack_require__(79); -var call = __webpack_require__(36); -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); +var ArrayBufferViewCore = __webpack_require__(12); +var $fill = __webpack_require__(146); +var toBigInt = __webpack_require__(176); +var classof = __webpack_require__(47); +var call = __webpack_require__(4); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -49972,14 +49265,14 @@ exportTypedArrayMethod('fill', function fill(value /* , start, end */) { /***/ }), -/* 569 */ +/* 564 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $filter = __webpack_require__(58).filter; -var fromSameTypeAndList = __webpack_require__(314); +var ArrayBufferViewCore = __webpack_require__(12); +var $filter = __webpack_require__(26).filter; +var fromSameTypeAndList = __webpack_require__(309); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -49993,13 +49286,13 @@ exportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */) { /***/ }), -/* 570 */ +/* 565 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $findIndex = __webpack_require__(58).findIndex; +var ArrayBufferViewCore = __webpack_require__(12); +var $findIndex = __webpack_require__(26).findIndex; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50012,13 +49305,13 @@ exportTypedArrayMethod('findIndex', function findIndex(predicate /* , thisArg */ /***/ }), -/* 571 */ +/* 566 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $findLastIndex = __webpack_require__(143).findLastIndex; +var ArrayBufferViewCore = __webpack_require__(12); +var $findLastIndex = __webpack_require__(113).findLastIndex; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50031,13 +49324,13 @@ exportTypedArrayMethod('findLastIndex', function findLastIndex(predicate /* , th /***/ }), -/* 572 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $findLast = __webpack_require__(143).findLast; +var ArrayBufferViewCore = __webpack_require__(12); +var $findLast = __webpack_require__(113).findLast; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50050,13 +49343,13 @@ exportTypedArrayMethod('findLast', function findLast(predicate /* , thisArg */) /***/ }), -/* 573 */ +/* 568 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $find = __webpack_require__(58).find; +var ArrayBufferViewCore = __webpack_require__(12); +var $find = __webpack_require__(26).find; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50069,12 +49362,12 @@ exportTypedArrayMethod('find', function find(predicate /* , thisArg */) { /***/ }), -/* 574 */ +/* 569 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Float32Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50086,12 +49379,12 @@ createTypedArrayConstructor('Float32', function (init) { /***/ }), -/* 575 */ +/* 570 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Float64Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50103,13 +49396,13 @@ createTypedArrayConstructor('Float64', function (init) { /***/ }), -/* 576 */ +/* 571 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $forEach = __webpack_require__(58).forEach; +var ArrayBufferViewCore = __webpack_require__(12); +var $forEach = __webpack_require__(26).forEach; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50122,14 +49415,14 @@ exportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */) { /***/ }), -/* 577 */ +/* 572 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(208); -var exportTypedArrayStaticMethod = __webpack_require__(44).exportTypedArrayStaticMethod; -var typedArrayFrom = __webpack_require__(277); +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(179); +var exportTypedArrayStaticMethod = __webpack_require__(12).exportTypedArrayStaticMethod; +var typedArrayFrom = __webpack_require__(248); // `%TypedArray%.from` method // https://tc39.es/ecma262/#sec-%typedarray%.from @@ -50137,13 +49430,13 @@ exportTypedArrayStaticMethod('from', typedArrayFrom, TYPED_ARRAYS_CONSTRUCTORS_R /***/ }), -/* 578 */ +/* 573 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $includes = __webpack_require__(127).includes; +var ArrayBufferViewCore = __webpack_require__(12); +var $includes = __webpack_require__(96).includes; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50156,13 +49449,13 @@ exportTypedArrayMethod('includes', function includes(searchElement /* , fromInde /***/ }), -/* 579 */ +/* 574 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $indexOf = __webpack_require__(127).indexOf; +var ArrayBufferViewCore = __webpack_require__(12); +var $indexOf = __webpack_require__(96).indexOf; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50175,12 +49468,12 @@ exportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex /***/ }), -/* 580 */ +/* 575 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Int16Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50192,12 +49485,12 @@ createTypedArrayConstructor('Int16', function (init) { /***/ }), -/* 581 */ +/* 576 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Int32Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50209,12 +49502,12 @@ createTypedArrayConstructor('Int32', function (init) { /***/ }), -/* 582 */ +/* 577 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Int8Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50226,17 +49519,17 @@ createTypedArrayConstructor('Int8', function (init) { /***/ }), -/* 583 */ +/* 578 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var fails = __webpack_require__(33); -var uncurryThis = __webpack_require__(34); -var ArrayBufferViewCore = __webpack_require__(44); -var ArrayIterators = __webpack_require__(172); -var wellKnownSymbol = __webpack_require__(39); +var globalThis = __webpack_require__(3); +var fails = __webpack_require__(1); +var uncurryThis = __webpack_require__(2); +var ArrayBufferViewCore = __webpack_require__(12); +var ArrayIterators = __webpack_require__(142); +var wellKnownSymbol = __webpack_require__(7); var ITERATOR = wellKnownSymbol('iterator'); var Uint8Array = globalThis.Uint8Array; @@ -50279,13 +49572,13 @@ exportTypedArrayMethod(ITERATOR, typedArrayValues, GENERIC || !ITERATOR_IS_VALUE /***/ }), -/* 584 */ +/* 579 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var uncurryThis = __webpack_require__(34); +var ArrayBufferViewCore = __webpack_require__(12); +var uncurryThis = __webpack_require__(2); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50299,14 +49592,14 @@ exportTypedArrayMethod('join', function join(separator) { /***/ }), -/* 585 */ +/* 580 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var apply = __webpack_require__(74); -var $lastIndexOf = __webpack_require__(218); +var ArrayBufferViewCore = __webpack_require__(12); +var apply = __webpack_require__(42); +var $lastIndexOf = __webpack_require__(189); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50320,13 +49613,13 @@ exportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement /* , fr /***/ }), -/* 586 */ +/* 581 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $map = __webpack_require__(58).map; +var ArrayBufferViewCore = __webpack_require__(12); +var $map = __webpack_require__(26).map; var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; @@ -50342,13 +49635,13 @@ exportTypedArrayMethod('map', function map(mapfn /* , thisArg */) { /***/ }), -/* 587 */ +/* 582 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(208); +var ArrayBufferViewCore = __webpack_require__(12); +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(179); var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; var exportTypedArrayStaticMethod = ArrayBufferViewCore.exportTypedArrayStaticMethod; @@ -50365,13 +49658,13 @@ exportTypedArrayStaticMethod('of', function of(/* ...items */) { /***/ }), -/* 588 */ +/* 583 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $reduceRight = __webpack_require__(144).right; +var ArrayBufferViewCore = __webpack_require__(12); +var $reduceRight = __webpack_require__(114).right; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50385,13 +49678,13 @@ exportTypedArrayMethod('reduceRight', function reduceRight(callbackfn /* , initi /***/ }), -/* 589 */ +/* 584 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $reduce = __webpack_require__(144).left; +var ArrayBufferViewCore = __webpack_require__(12); +var $reduce = __webpack_require__(114).left; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50405,12 +49698,12 @@ exportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */ /***/ }), -/* 590 */ +/* 585 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); +var ArrayBufferViewCore = __webpack_require__(12); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50433,18 +49726,18 @@ exportTypedArrayMethod('reverse', function reverse() { /***/ }), -/* 591 */ +/* 586 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var call = __webpack_require__(36); -var ArrayBufferViewCore = __webpack_require__(44); -var lengthOfArrayLike = __webpack_require__(50); -var toOffset = __webpack_require__(276); -var toIndexedObject = __webpack_require__(47); -var fails = __webpack_require__(33); +var globalThis = __webpack_require__(3); +var call = __webpack_require__(4); +var ArrayBufferViewCore = __webpack_require__(12); +var lengthOfArrayLike = __webpack_require__(18); +var toOffset = __webpack_require__(247); +var toIndexedObject = __webpack_require__(15); +var fails = __webpack_require__(1); var RangeError = globalThis.RangeError; var Int8Array = globalThis.Int8Array; @@ -50484,14 +49777,14 @@ exportTypedArrayMethod('set', function set(arrayLike /* , offset */) { /***/ }), -/* 592 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var fails = __webpack_require__(33); -var arraySlice = __webpack_require__(78); +var ArrayBufferViewCore = __webpack_require__(12); +var fails = __webpack_require__(1); +var arraySlice = __webpack_require__(46); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; @@ -50516,13 +49809,13 @@ exportTypedArrayMethod('slice', function slice(start, end) { /***/ }), -/* 593 */ +/* 588 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var $some = __webpack_require__(58).some; +var ArrayBufferViewCore = __webpack_require__(12); +var $some = __webpack_require__(26).some; var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50535,21 +49828,21 @@ exportTypedArrayMethod('some', function some(callbackfn /* , thisArg */) { /***/ }), -/* 594 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(98); -var fails = __webpack_require__(33); -var aCallable = __webpack_require__(42); -var internalSort = __webpack_require__(177); -var ArrayBufferViewCore = __webpack_require__(44); -var FF = __webpack_require__(230); -var IE_OR_EDGE = __webpack_require__(231); -var V8 = __webpack_require__(84); -var WEBKIT = __webpack_require__(183); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(67); +var fails = __webpack_require__(1); +var aCallable = __webpack_require__(10); +var internalSort = __webpack_require__(148); +var ArrayBufferViewCore = __webpack_require__(12); +var FF = __webpack_require__(201); +var IE_OR_EDGE = __webpack_require__(202); +var V8 = __webpack_require__(52); +var WEBKIT = __webpack_require__(154); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50612,14 +49905,14 @@ exportTypedArrayMethod('sort', function sort(comparefn) { /***/ }), -/* 595 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var toLength = __webpack_require__(77); -var toAbsoluteIndex = __webpack_require__(91); +var ArrayBufferViewCore = __webpack_require__(12); +var toLength = __webpack_require__(45); +var toAbsoluteIndex = __webpack_require__(59); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; @@ -50641,16 +49934,16 @@ exportTypedArrayMethod('subarray', function subarray(begin, end) { /***/ }), -/* 596 */ +/* 591 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var apply = __webpack_require__(74); -var ArrayBufferViewCore = __webpack_require__(44); -var fails = __webpack_require__(33); -var arraySlice = __webpack_require__(78); +var globalThis = __webpack_require__(3); +var apply = __webpack_require__(42); +var ArrayBufferViewCore = __webpack_require__(12); +var fails = __webpack_require__(1); +var arraySlice = __webpack_require__(46); var Int8Array = globalThis.Int8Array; var aTypedArray = ArrayBufferViewCore.aTypedArray; @@ -50680,13 +49973,13 @@ exportTypedArrayMethod('toLocaleString', function toLocaleString() { /***/ }), -/* 597 */ +/* 592 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayToReversed = __webpack_require__(219); -var ArrayBufferViewCore = __webpack_require__(44); +var arrayToReversed = __webpack_require__(190); +var ArrayBufferViewCore = __webpack_require__(12); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; @@ -50700,15 +49993,15 @@ exportTypedArrayMethod('toReversed', function toReversed() { /***/ }), -/* 598 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ArrayBufferViewCore = __webpack_require__(44); -var uncurryThis = __webpack_require__(34); -var aCallable = __webpack_require__(42); -var arrayFromConstructorAndList = __webpack_require__(142); +var ArrayBufferViewCore = __webpack_require__(12); +var uncurryThis = __webpack_require__(2); +var aCallable = __webpack_require__(10); +var arrayFromConstructorAndList = __webpack_require__(112); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; @@ -50726,15 +50019,15 @@ exportTypedArrayMethod('toSorted', function toSorted(compareFn) { /***/ }), -/* 599 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var exportTypedArrayMethod = __webpack_require__(44).exportTypedArrayMethod; -var fails = __webpack_require__(33); -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); +var exportTypedArrayMethod = __webpack_require__(12).exportTypedArrayMethod; +var fails = __webpack_require__(1); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); var Uint8Array = globalThis.Uint8Array; var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype || {}; @@ -50755,12 +50048,12 @@ exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD); /***/ }), -/* 600 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Uint16Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50772,12 +50065,12 @@ createTypedArrayConstructor('Uint16', function (init) { /***/ }), -/* 601 */ +/* 596 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Uint32Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50789,12 +50082,12 @@ createTypedArrayConstructor('Uint32', function (init) { /***/ }), -/* 602 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Uint8Array` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50806,12 +50099,12 @@ createTypedArrayConstructor('Uint8', function (init) { /***/ }), -/* 603 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createTypedArrayConstructor = __webpack_require__(92); +var createTypedArrayConstructor = __webpack_require__(60); // `Uint8ClampedArray` constructor // https://tc39.es/ecma262/#sec-typedarray-objects @@ -50823,16 +50116,16 @@ createTypedArrayConstructor('Uint8', function (init) { /***/ }), -/* 604 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayWith = __webpack_require__(220); -var ArrayBufferViewCore = __webpack_require__(44); -var isBigIntArray = __webpack_require__(244); -var toIntegerOrInfinity = __webpack_require__(54); -var toBigInt = __webpack_require__(205); +var arrayWith = __webpack_require__(191); +var ArrayBufferViewCore = __webpack_require__(12); +var isBigIntArray = __webpack_require__(215); +var toIntegerOrInfinity = __webpack_require__(22); +var toBigInt = __webpack_require__(176); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; @@ -50870,14 +50163,14 @@ exportTypedArrayMethod('with', { 'with': function (index, value) { /***/ }), -/* 605 */ +/* 600 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); +var $ = __webpack_require__(0); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); var fromCharCode = String.fromCharCode; var charAt = uncurryThis(''.charAt); @@ -50922,22 +50215,22 @@ $({ global: true }, { /***/ }), -/* 606 */ +/* 601 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var FREEZING = __webpack_require__(112); -var globalThis = __webpack_require__(35); -var uncurryThis = __webpack_require__(34); -var defineBuiltIns = __webpack_require__(88); -var InternalMetadataModule = __webpack_require__(102); -var collection = __webpack_require__(146); -var collectionWeak = __webpack_require__(225); -var isObject = __webpack_require__(40); -var enforceInternalState = __webpack_require__(53).enforce; -var fails = __webpack_require__(33); -var NATIVE_WEAK_MAP = __webpack_require__(280); +var FREEZING = __webpack_require__(81); +var globalThis = __webpack_require__(3); +var uncurryThis = __webpack_require__(2); +var defineBuiltIns = __webpack_require__(56); +var InternalMetadataModule = __webpack_require__(71); +var collection = __webpack_require__(116); +var collectionWeak = __webpack_require__(196); +var isObject = __webpack_require__(8); +var enforceInternalState = __webpack_require__(21).enforce; +var fails = __webpack_require__(1); +var NATIVE_WEAK_MAP = __webpack_require__(251); var $Object = Object; // eslint-disable-next-line es/no-array-isarray -- safe @@ -51035,23 +50328,23 @@ if (NATIVE_WEAK_MAP) if (IS_IE11) { /***/ }), -/* 607 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(606); +__webpack_require__(601); /***/ }), -/* 608 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var collection = __webpack_require__(146); -var collectionWeak = __webpack_require__(225); +var collection = __webpack_require__(116); +var collectionWeak = __webpack_require__(196); // `WeakSet` constructor // https://tc39.es/ecma262/#sec-weakset-constructor @@ -51061,30 +50354,30 @@ collection('WeakSet', function (init) { /***/ }), -/* 609 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(608); +__webpack_require__(603); /***/ }), -/* 610 */ +/* 605 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var getBuiltIn = __webpack_require__(43); -var uncurryThis = __webpack_require__(34); -var call = __webpack_require__(36); -var fails = __webpack_require__(33); -var toString = __webpack_require__(41); -var validateArgumentsLength = __webpack_require__(80); -var c2i = __webpack_require__(223).c2i; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var getBuiltIn = __webpack_require__(11); +var uncurryThis = __webpack_require__(2); +var call = __webpack_require__(4); +var fails = __webpack_require__(1); +var toString = __webpack_require__(9); +var validateArgumentsLength = __webpack_require__(48); +var c2i = __webpack_require__(194).c2i; var disallowed = /[^\d+/a-z]/i; var whitespaces = /[\t\n\f\r ]+/g; @@ -51145,20 +50438,20 @@ $({ global: true, bind: true, enumerable: true, forced: FORCED }, { /***/ }), -/* 611 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var getBuiltIn = __webpack_require__(43); -var uncurryThis = __webpack_require__(34); -var call = __webpack_require__(36); -var fails = __webpack_require__(33); -var toString = __webpack_require__(41); -var validateArgumentsLength = __webpack_require__(80); -var i2c = __webpack_require__(223).i2c; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var getBuiltIn = __webpack_require__(11); +var uncurryThis = __webpack_require__(2); +var call = __webpack_require__(4); +var fails = __webpack_require__(1); +var toString = __webpack_require__(9); +var validateArgumentsLength = __webpack_require__(48); +var i2c = __webpack_require__(194).i2c; var $btoa = getBuiltIn('btoa'); var charAt = uncurryThis(''.charAt); @@ -51203,14 +50496,14 @@ $({ global: true, bind: true, enumerable: true, forced: !BASIC || NO_ARG_RECEIVI /***/ }), -/* 612 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var clearImmediate = __webpack_require__(167).clear; +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var clearImmediate = __webpack_require__(137).clear; // `clearImmediate` method // http://w3c.github.io/setImmediate/#si-clearImmediate @@ -51220,16 +50513,16 @@ $({ global: true, bind: true, enumerable: true, forced: globalThis.clearImmediat /***/ }), -/* 613 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var DOMIterables = __webpack_require__(228); -var DOMTokenListPrototype = __webpack_require__(229); -var forEach = __webpack_require__(216); -var createNonEnumerableProperty = __webpack_require__(59); +var globalThis = __webpack_require__(3); +var DOMIterables = __webpack_require__(199); +var DOMTokenListPrototype = __webpack_require__(200); +var forEach = __webpack_require__(187); +var createNonEnumerableProperty = __webpack_require__(27); var handlePrototype = function (CollectionPrototype) { // some Chrome versions have non-configurable methods on DOMTokenList @@ -51250,18 +50543,18 @@ handlePrototype(DOMTokenListPrototype); /***/ }), -/* 614 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var globalThis = __webpack_require__(35); -var DOMIterables = __webpack_require__(228); -var DOMTokenListPrototype = __webpack_require__(229); -var ArrayIteratorMethods = __webpack_require__(172); -var createNonEnumerableProperty = __webpack_require__(59); -var setToStringTag = __webpack_require__(70); -var wellKnownSymbol = __webpack_require__(39); +var globalThis = __webpack_require__(3); +var DOMIterables = __webpack_require__(199); +var DOMTokenListPrototype = __webpack_require__(200); +var ArrayIteratorMethods = __webpack_require__(142); +var createNonEnumerableProperty = __webpack_require__(27); +var setToStringTag = __webpack_require__(38); +var wellKnownSymbol = __webpack_require__(7); var ITERATOR = wellKnownSymbol('iterator'); var ArrayValues = ArrayIteratorMethods.values; @@ -51294,30 +50587,30 @@ handlePrototype(DOMTokenListPrototype, 'DOMTokenList'); /***/ }), -/* 615 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var getBuiltInNodeModule = __webpack_require__(237); -var fails = __webpack_require__(33); -var create = __webpack_require__(62); -var createPropertyDescriptor = __webpack_require__(73); -var defineProperty = __webpack_require__(51).f; -var defineBuiltIn = __webpack_require__(49); -var defineBuiltInAccessor = __webpack_require__(55); -var hasOwn = __webpack_require__(45); -var anInstance = __webpack_require__(71); -var anObject = __webpack_require__(37); -var errorToString = __webpack_require__(234); -var normalizeStringArgument = __webpack_require__(118); -var DOMExceptionConstants = __webpack_require__(227); -var clearErrorStack = __webpack_require__(184); -var InternalStateModule = __webpack_require__(53); -var DESCRIPTORS = __webpack_require__(38); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var getBuiltInNodeModule = __webpack_require__(208); +var fails = __webpack_require__(1); +var create = __webpack_require__(30); +var createPropertyDescriptor = __webpack_require__(41); +var defineProperty = __webpack_require__(19).f; +var defineBuiltIn = __webpack_require__(17); +var defineBuiltInAccessor = __webpack_require__(23); +var hasOwn = __webpack_require__(13); +var anInstance = __webpack_require__(39); +var anObject = __webpack_require__(5); +var errorToString = __webpack_require__(205); +var normalizeStringArgument = __webpack_require__(87); +var DOMExceptionConstants = __webpack_require__(198); +var clearErrorStack = __webpack_require__(155); +var InternalStateModule = __webpack_require__(21); +var DESCRIPTORS = __webpack_require__(6); +var IS_PURE = __webpack_require__(16); var DOM_EXCEPTION = 'DOMException'; var DATA_CLONE_ERR = 'DATA_CLONE_ERR'; @@ -51446,24 +50739,24 @@ for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) { /***/ }), -/* 616 */ +/* 611 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var getBuiltIn = __webpack_require__(43); -var createPropertyDescriptor = __webpack_require__(73); -var defineProperty = __webpack_require__(51).f; -var hasOwn = __webpack_require__(45); -var anInstance = __webpack_require__(71); -var inheritIfRequired = __webpack_require__(101); -var normalizeStringArgument = __webpack_require__(118); -var DOMExceptionConstants = __webpack_require__(227); -var clearErrorStack = __webpack_require__(184); -var DESCRIPTORS = __webpack_require__(38); -var IS_PURE = __webpack_require__(48); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var getBuiltIn = __webpack_require__(11); +var createPropertyDescriptor = __webpack_require__(41); +var defineProperty = __webpack_require__(19).f; +var hasOwn = __webpack_require__(13); +var anInstance = __webpack_require__(39); +var inheritIfRequired = __webpack_require__(70); +var normalizeStringArgument = __webpack_require__(87); +var DOMExceptionConstants = __webpack_require__(198); +var clearErrorStack = __webpack_require__(155); +var DESCRIPTORS = __webpack_require__(6); +var IS_PURE = __webpack_require__(16); var DOM_EXCEPTION = 'DOMException'; var Error = getBuiltIn('Error'); @@ -51521,13 +50814,13 @@ if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) { /***/ }), -/* 617 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var getBuiltIn = __webpack_require__(43); -var setToStringTag = __webpack_require__(70); +var getBuiltIn = __webpack_require__(11); +var setToStringTag = __webpack_require__(38); var DOM_EXCEPTION = 'DOMException'; @@ -51536,29 +50829,29 @@ setToStringTag(getBuiltIn(DOM_EXCEPTION), DOM_EXCEPTION); /***/ }), -/* 618 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's split to modules listed below -__webpack_require__(612); -__webpack_require__(621); +__webpack_require__(607); +__webpack_require__(616); /***/ }), -/* 619 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var microtask = __webpack_require__(255); -var aCallable = __webpack_require__(42); -var validateArgumentsLength = __webpack_require__(80); -var fails = __webpack_require__(33); -var DESCRIPTORS = __webpack_require__(38); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var microtask = __webpack_require__(226); +var aCallable = __webpack_require__(10); +var validateArgumentsLength = __webpack_require__(48); +var fails = __webpack_require__(1); +var DESCRIPTORS = __webpack_require__(6); // Bun ~ 1.0.30 bug // https://github.com/oven-sh/bun/issues/9249 @@ -51579,15 +50872,15 @@ $({ global: true, enumerable: true, dontCallGetSet: true, forced: WRONG_ARITY }, /***/ }), -/* 620 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var defineBuiltInAccessor = __webpack_require__(55); -var DESCRIPTORS = __webpack_require__(38); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var defineBuiltInAccessor = __webpack_require__(23); +var DESCRIPTORS = __webpack_require__(6); var $TypeError = TypeError; // eslint-disable-next-line es/no-object-defineproperty -- safe @@ -51627,15 +50920,15 @@ try { /***/ }), -/* 621 */ +/* 616 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var setTask = __webpack_require__(167).set; -var schedulersFix = __webpack_require__(201); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var setTask = __webpack_require__(137).set; +var schedulersFix = __webpack_require__(172); // https://github.com/oven-sh/bun/issues/1633 var setImmediate = globalThis.setImmediate ? schedulersFix(setTask, false) : setTask; @@ -51648,14 +50941,14 @@ $({ global: true, bind: true, enumerable: true, forced: globalThis.setImmediate /***/ }), -/* 622 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var schedulersFix = __webpack_require__(201); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var schedulersFix = __webpack_require__(172); var setInterval = schedulersFix(globalThis.setInterval, true); @@ -51667,14 +50960,14 @@ $({ global: true, bind: true, forced: globalThis.setInterval !== setInterval }, /***/ }), -/* 623 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var schedulersFix = __webpack_require__(201); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var schedulersFix = __webpack_require__(172); var setTimeout = schedulersFix(globalThis.setTimeout, true); @@ -51686,38 +50979,38 @@ $({ global: true, bind: true, forced: globalThis.setTimeout !== setTimeout }, { /***/ }), -/* 624 */ +/* 619 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var IS_PURE = __webpack_require__(48); -var $ = __webpack_require__(32); -var globalThis = __webpack_require__(35); -var getBuiltIn = __webpack_require__(43); -var uncurryThis = __webpack_require__(34); -var fails = __webpack_require__(33); -var uid = __webpack_require__(126); -var isCallable = __webpack_require__(46); -var isConstructor = __webpack_require__(103); -var isNullOrUndefined = __webpack_require__(89); -var isObject = __webpack_require__(40); -var isSymbol = __webpack_require__(104); -var iterate = __webpack_require__(56); -var anObject = __webpack_require__(37); -var classof = __webpack_require__(79); -var hasOwn = __webpack_require__(45); -var createProperty = __webpack_require__(87); -var createNonEnumerableProperty = __webpack_require__(59); -var lengthOfArrayLike = __webpack_require__(50); -var validateArgumentsLength = __webpack_require__(80); -var getRegExpFlags = __webpack_require__(107); -var MapHelpers = __webpack_require__(247); -var SetHelpers = __webpack_require__(82); -var setIterate = __webpack_require__(121); -var detachTransferable = __webpack_require__(226); -var ERROR_STACK_INSTALLABLE = __webpack_require__(233); -var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(204); +var IS_PURE = __webpack_require__(16); +var $ = __webpack_require__(0); +var globalThis = __webpack_require__(3); +var getBuiltIn = __webpack_require__(11); +var uncurryThis = __webpack_require__(2); +var fails = __webpack_require__(1); +var uid = __webpack_require__(95); +var isCallable = __webpack_require__(14); +var isConstructor = __webpack_require__(72); +var isNullOrUndefined = __webpack_require__(57); +var isObject = __webpack_require__(8); +var isSymbol = __webpack_require__(73); +var iterate = __webpack_require__(24); +var anObject = __webpack_require__(5); +var classof = __webpack_require__(47); +var hasOwn = __webpack_require__(13); +var createProperty = __webpack_require__(55); +var createNonEnumerableProperty = __webpack_require__(27); +var lengthOfArrayLike = __webpack_require__(18); +var validateArgumentsLength = __webpack_require__(48); +var getRegExpFlags = __webpack_require__(76); +var MapHelpers = __webpack_require__(218); +var SetHelpers = __webpack_require__(50); +var setIterate = __webpack_require__(90); +var detachTransferable = __webpack_require__(197); +var ERROR_STACK_INSTALLABLE = __webpack_require__(204); +var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(175); var Object = globalThis.Object; var Array = globalThis.Array; @@ -52228,26 +51521,26 @@ $({ global: true, enumerable: true, sham: !PROPER_STRUCTURED_CLONE_TRANSFER, for /***/ }), -/* 625 */ +/* 620 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's split to modules listed below -__webpack_require__(622); -__webpack_require__(623); +__webpack_require__(617); +__webpack_require__(618); /***/ }), -/* 626 */ +/* 621 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineBuiltIn = __webpack_require__(49); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); -var validateArgumentsLength = __webpack_require__(80); +var defineBuiltIn = __webpack_require__(17); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); +var validateArgumentsLength = __webpack_require__(48); var $URLSearchParams = URLSearchParams; var URLSearchParamsPrototype = $URLSearchParams.prototype; @@ -52295,15 +51588,15 @@ if (params + '' !== 'a=2') { /***/ }), -/* 627 */ +/* 622 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defineBuiltIn = __webpack_require__(49); -var uncurryThis = __webpack_require__(34); -var toString = __webpack_require__(41); -var validateArgumentsLength = __webpack_require__(80); +var defineBuiltIn = __webpack_require__(17); +var uncurryThis = __webpack_require__(2); +var toString = __webpack_require__(9); +var validateArgumentsLength = __webpack_require__(48); var $URLSearchParams = URLSearchParams; var URLSearchParamsPrototype = $URLSearchParams.prototype; @@ -52330,24 +51623,24 @@ if (params.has('a', 2) || !params.has('a', undefined)) { /***/ }), -/* 628 */ +/* 623 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(286); +__webpack_require__(257); /***/ }), -/* 629 */ +/* 624 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var DESCRIPTORS = __webpack_require__(38); -var uncurryThis = __webpack_require__(34); -var defineBuiltInAccessor = __webpack_require__(55); +var DESCRIPTORS = __webpack_require__(6); +var uncurryThis = __webpack_require__(2); +var defineBuiltInAccessor = __webpack_require__(23); var URLSearchParamsPrototype = URLSearchParams.prototype; var forEach = uncurryThis(URLSearchParamsPrototype.forEach); @@ -52368,17 +51661,17 @@ if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) { /***/ }), -/* 630 */ +/* 625 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var fails = __webpack_require__(33); -var validateArgumentsLength = __webpack_require__(80); -var toString = __webpack_require__(41); -var USE_NATIVE_URL = __webpack_require__(171); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var fails = __webpack_require__(1); +var validateArgumentsLength = __webpack_require__(48); +var toString = __webpack_require__(9); +var USE_NATIVE_URL = __webpack_require__(141); var URL = getBuiltIn('URL'); @@ -52411,33 +51704,33 @@ $({ target: 'URL', stat: true, forced: !THROWS_WITHOUT_ARGUMENTS || WRONG_ARITY /***/ }), -/* 631 */ +/* 626 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` -__webpack_require__(285); -var $ = __webpack_require__(32); -var DESCRIPTORS = __webpack_require__(38); -var USE_NATIVE_URL = __webpack_require__(171); -var globalThis = __webpack_require__(35); -var bind = __webpack_require__(75); -var uncurryThis = __webpack_require__(34); -var defineBuiltIn = __webpack_require__(49); -var defineBuiltInAccessor = __webpack_require__(55); -var anInstance = __webpack_require__(71); -var hasOwn = __webpack_require__(45); -var assign = __webpack_require__(259); -var arrayFrom = __webpack_require__(217); -var arraySlice = __webpack_require__(78); -var codeAt = __webpack_require__(164).codeAt; -var toASCII = __webpack_require__(312); -var $toString = __webpack_require__(41); -var setToStringTag = __webpack_require__(70); -var validateArgumentsLength = __webpack_require__(80); -var URLSearchParamsModule = __webpack_require__(286); -var InternalStateModule = __webpack_require__(53); +__webpack_require__(256); +var $ = __webpack_require__(0); +var DESCRIPTORS = __webpack_require__(6); +var USE_NATIVE_URL = __webpack_require__(141); +var globalThis = __webpack_require__(3); +var bind = __webpack_require__(43); +var uncurryThis = __webpack_require__(2); +var defineBuiltIn = __webpack_require__(17); +var defineBuiltInAccessor = __webpack_require__(23); +var anInstance = __webpack_require__(39); +var hasOwn = __webpack_require__(13); +var assign = __webpack_require__(230); +var arrayFrom = __webpack_require__(188); +var arraySlice = __webpack_require__(46); +var codeAt = __webpack_require__(134).codeAt; +var toASCII = __webpack_require__(307); +var $toString = __webpack_require__(9); +var setToStringTag = __webpack_require__(38); +var validateArgumentsLength = __webpack_require__(48); +var URLSearchParamsModule = __webpack_require__(257); +var InternalStateModule = __webpack_require__(21); var setInternalState = InternalStateModule.set; var getInternalURLState = InternalStateModule.getterFor('URL'); @@ -53469,26 +52762,26 @@ $({ global: true, constructor: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS /***/ }), -/* 632 */ +/* 627 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // TODO: Remove this module from `core-js@4` since it's replaced to module below -__webpack_require__(631); +__webpack_require__(626); /***/ }), -/* 633 */ +/* 628 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var getBuiltIn = __webpack_require__(43); -var validateArgumentsLength = __webpack_require__(80); -var toString = __webpack_require__(41); -var USE_NATIVE_URL = __webpack_require__(171); +var $ = __webpack_require__(0); +var getBuiltIn = __webpack_require__(11); +var validateArgumentsLength = __webpack_require__(48); +var toString = __webpack_require__(9); +var USE_NATIVE_URL = __webpack_require__(141); var URL = getBuiltIn('URL'); @@ -53509,13 +52802,13 @@ $({ target: 'URL', stat: true, forced: !USE_NATIVE_URL }, { /***/ }), -/* 634 */ +/* 629 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $ = __webpack_require__(32); -var call = __webpack_require__(36); +var $ = __webpack_require__(0); +var call = __webpack_require__(4); // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson @@ -53527,90 +52820,95 @@ $({ target: 'URL', proto: true, enumerable: true }, { /***/ }), -/* 635 */ +/* 630 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__(554); -__webpack_require__(548); -__webpack_require__(545); -__webpack_require__(546); __webpack_require__(549); -__webpack_require__(551); +__webpack_require__(543); +__webpack_require__(540); +__webpack_require__(541); +__webpack_require__(544); +__webpack_require__(546); +__webpack_require__(547); +__webpack_require__(548); __webpack_require__(552); +__webpack_require__(551); __webpack_require__(553); -__webpack_require__(557); +__webpack_require__(554); +__webpack_require__(555); __webpack_require__(556); +__webpack_require__(557); __webpack_require__(558); __webpack_require__(559); -__webpack_require__(560); -__webpack_require__(561); -__webpack_require__(562); -__webpack_require__(563); -__webpack_require__(564); -__webpack_require__(377); -__webpack_require__(378); -__webpack_require__(379); -__webpack_require__(317); -__webpack_require__(315); -__webpack_require__(544); +__webpack_require__(372); +__webpack_require__(373); +__webpack_require__(374); +__webpack_require__(312); +__webpack_require__(310); +__webpack_require__(539); +__webpack_require__(319); +__webpack_require__(320); +__webpack_require__(321); +__webpack_require__(322); +__webpack_require__(323); __webpack_require__(324); +__webpack_require__(328); __webpack_require__(325); -__webpack_require__(326); __webpack_require__(327); -__webpack_require__(328); -__webpack_require__(329); -__webpack_require__(333); +__webpack_require__(326); __webpack_require__(330); -__webpack_require__(332); +__webpack_require__(329); __webpack_require__(331); -__webpack_require__(335); +__webpack_require__(333); __webpack_require__(334); +__webpack_require__(335); __webpack_require__(336); +__webpack_require__(142); +__webpack_require__(337); __webpack_require__(338); __webpack_require__(339); __webpack_require__(340); __webpack_require__(341); -__webpack_require__(172); -__webpack_require__(342); __webpack_require__(343); +__webpack_require__(342); __webpack_require__(344); __webpack_require__(345); __webpack_require__(346); -__webpack_require__(348); __webpack_require__(347); +__webpack_require__(348); __webpack_require__(349); __webpack_require__(350); __webpack_require__(351); __webpack_require__(352); -__webpack_require__(353); __webpack_require__(354); +__webpack_require__(353); __webpack_require__(355); __webpack_require__(356); -__webpack_require__(357); -__webpack_require__(359); -__webpack_require__(358); -__webpack_require__(360); +__webpack_require__(313); +__webpack_require__(315); +__webpack_require__(316); __webpack_require__(361); +__webpack_require__(360); +__webpack_require__(362); +__webpack_require__(314); __webpack_require__(318); -__webpack_require__(320); -__webpack_require__(321); -__webpack_require__(366); +__webpack_require__(317); +__webpack_require__(363); +__webpack_require__(364); __webpack_require__(365); +__webpack_require__(366); __webpack_require__(367); -__webpack_require__(319); -__webpack_require__(323); -__webpack_require__(322); __webpack_require__(368); __webpack_require__(369); __webpack_require__(370); __webpack_require__(371); -__webpack_require__(372); -__webpack_require__(373); -__webpack_require__(374); __webpack_require__(375); __webpack_require__(376); +__webpack_require__(377); +__webpack_require__(378); +__webpack_require__(379); __webpack_require__(380); __webpack_require__(381); __webpack_require__(382); @@ -53625,24 +52923,24 @@ __webpack_require__(390); __webpack_require__(391); __webpack_require__(392); __webpack_require__(393); +__webpack_require__(254); __webpack_require__(394); -__webpack_require__(395); -__webpack_require__(396); __webpack_require__(397); +__webpack_require__(396); __webpack_require__(398); -__webpack_require__(283); __webpack_require__(399); -__webpack_require__(402); +__webpack_require__(400); __webpack_require__(401); +__webpack_require__(402); __webpack_require__(403); __webpack_require__(404); -__webpack_require__(405); __webpack_require__(406); +__webpack_require__(405); __webpack_require__(407); __webpack_require__(408); __webpack_require__(409); -__webpack_require__(411); __webpack_require__(410); +__webpack_require__(411); __webpack_require__(412); __webpack_require__(413); __webpack_require__(414); @@ -53673,173 +52971,358 @@ __webpack_require__(438); __webpack_require__(439); __webpack_require__(440); __webpack_require__(441); -__webpack_require__(442); __webpack_require__(443); __webpack_require__(444); __webpack_require__(445); +__webpack_require__(449); __webpack_require__(446); +__webpack_require__(447); __webpack_require__(448); -__webpack_require__(449); __webpack_require__(450); -__webpack_require__(454); __webpack_require__(451); __webpack_require__(452); __webpack_require__(453); +__webpack_require__(454); __webpack_require__(455); __webpack_require__(456); __webpack_require__(457); __webpack_require__(458); __webpack_require__(459); __webpack_require__(460); +__webpack_require__(467); __webpack_require__(461); -__webpack_require__(462); __webpack_require__(463); -__webpack_require__(464); -__webpack_require__(465); -__webpack_require__(472); __webpack_require__(466); -__webpack_require__(468); __webpack_require__(471); +__webpack_require__(472); +__webpack_require__(332); +__webpack_require__(357); +__webpack_require__(358); +__webpack_require__(473); +__webpack_require__(474); +__webpack_require__(475); __webpack_require__(476); +__webpack_require__(479); __webpack_require__(477); -__webpack_require__(337); -__webpack_require__(362); -__webpack_require__(363); __webpack_require__(478); -__webpack_require__(479); __webpack_require__(480); __webpack_require__(481); -__webpack_require__(484); __webpack_require__(482); __webpack_require__(483); __webpack_require__(485); +__webpack_require__(484); __webpack_require__(486); __webpack_require__(487); +__webpack_require__(489); __webpack_require__(488); +__webpack_require__(180); __webpack_require__(490); -__webpack_require__(489); __webpack_require__(491); __webpack_require__(492); -__webpack_require__(494); __webpack_require__(493); -__webpack_require__(209); +__webpack_require__(500); __webpack_require__(495); __webpack_require__(496); __webpack_require__(497); __webpack_require__(498); -__webpack_require__(505); -__webpack_require__(500); +__webpack_require__(499); __webpack_require__(501); __webpack_require__(502); -__webpack_require__(503); __webpack_require__(504); -__webpack_require__(506); -__webpack_require__(507); +__webpack_require__(508); __webpack_require__(509); +__webpack_require__(255); __webpack_require__(513); __webpack_require__(514); -__webpack_require__(284); +__webpack_require__(256); __webpack_require__(518); +__webpack_require__(517); __webpack_require__(519); -__webpack_require__(285); -__webpack_require__(523); +__webpack_require__(520); +__webpack_require__(521); __webpack_require__(522); __webpack_require__(524); +__webpack_require__(523); __webpack_require__(525); -__webpack_require__(526); __webpack_require__(527); -__webpack_require__(529); __webpack_require__(528); -__webpack_require__(530); -__webpack_require__(532); +__webpack_require__(531); __webpack_require__(533); -__webpack_require__(536); __webpack_require__(538); -__webpack_require__(543); -__webpack_require__(539); -__webpack_require__(542); -__webpack_require__(508); +__webpack_require__(534); +__webpack_require__(537); +__webpack_require__(503); +__webpack_require__(505); +__webpack_require__(506); +__webpack_require__(507); __webpack_require__(510); __webpack_require__(511); __webpack_require__(512); __webpack_require__(515); __webpack_require__(516); -__webpack_require__(517); -__webpack_require__(520); -__webpack_require__(521); -__webpack_require__(531); -__webpack_require__(534); -__webpack_require__(535); -__webpack_require__(537); -__webpack_require__(574); +__webpack_require__(526); +__webpack_require__(529); +__webpack_require__(530); +__webpack_require__(532); +__webpack_require__(569); +__webpack_require__(570); +__webpack_require__(577); __webpack_require__(575); -__webpack_require__(582); -__webpack_require__(580); -__webpack_require__(581); -__webpack_require__(602); -__webpack_require__(603); -__webpack_require__(600); -__webpack_require__(601); +__webpack_require__(576); +__webpack_require__(597); +__webpack_require__(598); +__webpack_require__(595); +__webpack_require__(596); +__webpack_require__(560); +__webpack_require__(561); +__webpack_require__(562); +__webpack_require__(563); +__webpack_require__(564); +__webpack_require__(568); __webpack_require__(565); -__webpack_require__(566); __webpack_require__(567); -__webpack_require__(568); -__webpack_require__(569); -__webpack_require__(573); -__webpack_require__(570); -__webpack_require__(572); +__webpack_require__(566); __webpack_require__(571); -__webpack_require__(576); -__webpack_require__(577); +__webpack_require__(572); +__webpack_require__(573); +__webpack_require__(574); __webpack_require__(578); __webpack_require__(579); -__webpack_require__(583); +__webpack_require__(580); +__webpack_require__(581); +__webpack_require__(582); __webpack_require__(584); +__webpack_require__(583); __webpack_require__(585); __webpack_require__(586); __webpack_require__(587); -__webpack_require__(589); __webpack_require__(588); +__webpack_require__(589); __webpack_require__(590); __webpack_require__(591); __webpack_require__(592); __webpack_require__(593); __webpack_require__(594); -__webpack_require__(595); -__webpack_require__(596); -__webpack_require__(597); -__webpack_require__(598); __webpack_require__(599); +__webpack_require__(600); +__webpack_require__(602); __webpack_require__(604); __webpack_require__(605); -__webpack_require__(607); +__webpack_require__(606); +__webpack_require__(608); __webpack_require__(609); __webpack_require__(610); __webpack_require__(611); +__webpack_require__(612); __webpack_require__(613); __webpack_require__(614); __webpack_require__(615); -__webpack_require__(616); -__webpack_require__(617); -__webpack_require__(618); __webpack_require__(619); __webpack_require__(620); -__webpack_require__(624); +__webpack_require__(627); __webpack_require__(625); -__webpack_require__(632); -__webpack_require__(630); -__webpack_require__(633); -__webpack_require__(634); __webpack_require__(628); -__webpack_require__(626); -__webpack_require__(627); __webpack_require__(629); +__webpack_require__(623); +__webpack_require__(621); +__webpack_require__(622); +__webpack_require__(624); -module.exports = __webpack_require__(158); +module.exports = __webpack_require__(128); /***/ }), -/* 636 */ +/* 631 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 632 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54606,197 +54089,714 @@ try { /***/ }), -/* 637 */ +/* 633 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/** +* +* VALIDATE: function +* +* +* DESCRIPTION: +* - Validates if a value is a function. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ -Object.defineProperty(exports, "__esModule", { - value: true -}); -/* - oktransition.add({ - obj: el.style, - units: "px", - from: { left: 0 }, - to: { left: 100 }, - duration: 1000, - easing: oktransition.easing.circ_out, - update: function(obj){ - console.log(obj.left) - } - finished: function(){ - console.log("done") - } - }) + +/** +* FUNCTION: isFunction( value ) +* Validates if a value is a function. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is a function */ +function isFunction( value ) { + return ( typeof value === 'function' ); +} // end FUNCTION isFunction() -var oktransition = {}; -var transitions = []; -var last_t = 0; -var id = 0; +// EXPORTS // -var lerp = function lerp(n, a, b) { - return (b - a) * n + a; -}; +module.exports = isFunction; -oktransition.speed = 1; -oktransition.add = function (transition) { - transition.id = id++; - transition.obj = transition.obj || {}; - if (transition.easing) { - if (typeof transition.easing === "string") { - transition.easing = oktransition.easing[transition.easing]; - } - } else { - transition.easing = oktransition.easing.linear; - } - if (!("from" in transition) && !("to" in transition)) { - transition.keys = []; - } else if (!("from" in transition)) { - transition.from = {}; - transition.keys = Object.keys(transition.to); - transition.keys.forEach(function (prop) { - transition.from[prop] = parseFloat(transition.obj[prop]); - }); - } else { - transition.keys = Object.keys(transition.from); - } - transition.delay = transition.delay || 0; - transition.start = last_t + transition.delay; - transition.done = false; - transition.after = transition.after || []; - transition.then = function (fn) { - transition.after.push(fn); - return transition; - }; - transition.tick = 0; - transition.skip = transition.skip || 1; - transition.dt = 0; - transition.cancel = function () { - return transitions = transitions.filter(function (item) { - return item !== transition; - }); - }; - transitions.push(transition); - return transition; -}; -oktransition.update = function (t) { - var done = false; - requestAnimationFrame(oktransition.update); - last_t = t * oktransition.speed; - if (transitions.length === 0) return; - transitions.forEach(function (transition, i) { - var dt = Math.min(1.0, (t - transition.start) / transition.duration); - transition.tick++; - if (dt < 0 || dt < 1 && transition.tick % transition.skip != 0 || transition.done) return; - var ddt = transition.easing(dt); - transition.dt = ddt; - transition.keys.forEach(function (prop) { - var val = lerp(ddt, transition.from[prop], transition.to[prop]); - if (transition.round) val = Math.round(val); - if (transition.units) val = Math.round(val) + transition.units; - transition.obj[prop] = val; - }); - if (transition.update) { - transition.update(transition.obj, dt); - } - if (dt === 1) { - if (transition.finished) { - transition.finished(transition); - } - if (transition.after.length) { - var twn = transition.after.shift(); - twn.obj = twn.obj || transition.obj; - twn.after = transition.after; - oktransition.add(twn); - } - if (transition.loop) { - transition.start = t + transition.delay; - } else { - done = true; - transition.done = true; - } - } - }); - if (done) { - transitions = transitions.filter(function (transition) { - return !transition.done; - }); - } -}; -requestAnimationFrame(oktransition.update); +/***/ }), +/* 634 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** +* +* VALIDATE: integer-array +* +* +* DESCRIPTION: +* - Validates if a value is an integer array. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2015. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2015. +* +*/ + + + +// MODULES // + +var isArray = __webpack_require__( 258 ), + isInteger = __webpack_require__( 635 ); + + +// IS INTEGER ARRAY // + +/** +* FUNCTION: isIntegerArray( value ) +* Validates if a value is an integer array. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating if a value is an integer array +*/ +function isIntegerArray( value ) { + var len; + if ( !isArray( value ) ) { + return false; + } + len = value.length; + if ( !len ) { + return false; + } + for ( var i = 0; i < len; i++ ) { + if ( !isInteger( value[i] ) ) { + return false; + } + } + return true; +} // end FUNCTION isIntegerArray() + + +// EXPORTS // + +module.exports = isIntegerArray; + + +/***/ }), +/* 635 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** +* +* VALIDATE: integer +* +* +* DESCRIPTION: +* - Validates if a value is an integer. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ + + + +// MODULES // + +var isNumber = __webpack_require__( 636 ); + + +// ISINTEGER // + +/** +* FUNCTION: isInteger( value ) +* Validates if a value is an integer. +* +* @param {Number} value - value to be validated +* @returns {Boolean} boolean indicating whether value is an integer +*/ +function isInteger( value ) { + return isNumber( value ) && value%1 === 0; +} // end FUNCTION isInteger() + + +// EXPORTS // + +module.exports = isInteger; + + +/***/ }), +/* 636 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** +* +* VALIDATE: number +* +* +* DESCRIPTION: +* - Validates if a value is a number. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ -oktransition.easing = { - linear: function linear(t) { - return t; - }, - circ_out: function circ_out(t) { - return Math.sqrt(1 - (t = t - 1) * t); - }, - circ_in: function circ_in(t) { - return -(Math.sqrt(1 - t * t) - 1); - }, - circ_in_out: function circ_in_out(t) { - return (t *= 2) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); - }, - quad_in: function quad_in(n) { - return Math.pow(n, 2); - }, - quad_out: function quad_out(n) { - return n * (n - 2) * -1; - }, - quad_in_out: function quad_in_out(n) { - n = n * 2; - if (n < 1) { - return Math.pow(n, 2) / 2; - } - return -1 * (--n * (n - 2) - 1) / 2; - }, - cubic_bezier: function cubic_bezier(mX1, mY1, mX2, mY2) { - function A(aA1, aA2) { - return 1.0 - 3.0 * aA2 + 3.0 * aA1; - } - function B(aA1, aA2) { - return 3.0 * aA2 - 6.0 * aA1; - } - function C(aA1) { - return 3.0 * aA1; - } - // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. - function CalcBezier(aT, aA1, aA2) { - return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; - } - // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. - function GetSlope(aT, aA1, aA2) { - return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); - } +/** +* FUNCTION: isNumber( value ) +* Validates if a value is a number. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is a number +*/ +function isNumber( value ) { + return ( typeof value === 'number' || Object.prototype.toString.call( value ) === '[object Number]' ) && value.valueOf() === value.valueOf(); +} // end FUNCTION isNumber() - function GetTForX(aX) { - // Newton raphson iteration - var aGuessT = aX; - for (var i = 0; i < 10; ++i) { - var currentSlope = GetSlope(aGuessT, mX1, mX2); - if (currentSlope == 0.0) return aGuessT; - var currentX = CalcBezier(aGuessT, mX1, mX2) - aX; - aGuessT -= currentX / currentSlope; - } - return aGuessT; - } - return function (aX) { - if (mX1 == mY1 && mX2 == mY2) return aX; // linear - return CalcBezier(aX, mY1, mY2); - }; - } -}; +// EXPORTS // -exports.default = oktransition; +module.exports = isNumber; + + +/***/ }), +/* 637 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process, global) {/** + * WEBMIDI.js v3.1.12 + * A JavaScript library to kickstart your MIDI projects + * https://webmidijs.org + * Build generated on November 22nd, 2024. + * + * © Copyright 2015-2024, Jean-Philippe Côté. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +Object.defineProperty(exports,"__esModule",{value:!0});class EventEmitter{constructor(e=!1){this.eventMap={},this.eventsSuspended=1==e}addListener(e,t,n={}){if("string"==typeof e&&e.length<1||e instanceof String&&e.length<1||"string"!=typeof e&&!(e instanceof String)&&e!==EventEmitter.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if("function"!=typeof t)throw new TypeError("The callback must be a function.");const r=new Listener(e,this,t,n);return this.eventMap[e]||(this.eventMap[e]=[]),n.prepend?this.eventMap[e].unshift(r):this.eventMap[e].push(r),r}addOneTimeListener(e,t,n={}){n.remaining=1,this.addListener(e,t,n)}static get ANY_EVENT(){return Symbol.for("Any event")}hasListener(e,t){if(void 0===e)return!!(this.eventMap[EventEmitter.ANY_EVENT]&&this.eventMap[EventEmitter.ANY_EVENT].length>0)||Object.entries(this.eventMap).some(([,e])=>e.length>0);if(this.eventMap[e]&&this.eventMap[e].length>0){if(t instanceof Listener){return this.eventMap[e].filter(e=>e===t).length>0}if("function"==typeof t){return this.eventMap[e].filter(e=>e.callback===t).length>0}return null==t}return!1}get eventNames(){return Object.keys(this.eventMap)}getListeners(e){return this.eventMap[e]||[]}suspendEvent(e){this.getListeners(e).forEach(e=>{e.suspended=!0})}unsuspendEvent(e){this.getListeners(e).forEach(e=>{e.suspended=!1})}getListenerCount(e){return this.getListeners(e).length}emit(e,...t){if("string"!=typeof e&&!(e instanceof String))throw new TypeError("The 'event' parameter must be a string.");if(this.eventsSuspended)return;let n=[],r=this.eventMap[EventEmitter.ANY_EVENT]||[];return this.eventMap[e]&&(r=r.concat(this.eventMap[e])),r.forEach(e=>{if(e.suspended)return;let r=[...t];Array.isArray(e.arguments)&&(r=r.concat(e.arguments)),e.remaining>0&&(n.push(e.callback.apply(e.context,r)),e.count++),--e.remaining<1&&e.remove()}),n}removeListener(e,t,n={}){if(void 0===e)return void(this.eventMap={});if(!this.eventMap[e])return;let r=this.eventMap[e].filter(e=>t&&e.callback!==t||n.remaining&&n.remaining!==e.remaining||n.context&&n.context!==e.context);r.length?this.eventMap[e]=r:delete this.eventMap[e]}async waitFor(e,t={}){return t.duration=parseInt(t.duration),(isNaN(t.duration)||t.duration<=0)&&(t.duration=1/0),new Promise((n,r)=>{let i,s=this.addListener(e,()=>{clearTimeout(i),n()},{remaining:1});t.duration!==1/0&&(i=setTimeout(()=>{s.remove(),r("The duration expired before the event was emitted.")},t.duration))})}get eventCount(){return Object.keys(this.eventMap).length}}class Listener{constructor(e,t,n,r={}){if("string"!=typeof e&&!(e instanceof String)&&e!==EventEmitter.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(!t)throw new ReferenceError("The 'target' parameter is mandatory.");if("function"!=typeof n)throw new TypeError("The 'callback' must be a function.");void 0===r.arguments||Array.isArray(r.arguments)||(r.arguments=[r.arguments]),(r=Object.assign({context:t,remaining:1/0,arguments:void 0,duration:1/0},r)).duration!==1/0&&setTimeout(()=>this.remove(),r.duration),this.arguments=r.arguments,this.callback=n,this.context=r.context,this.count=0,this.event=e,this.remaining=parseInt(r.remaining)>=1?parseInt(r.remaining):1/0,this.suspended=!1,this.target=t}remove(){this.target.removeListener(this.event,this.callback,{context:this.context,remaining:this.remaining})}} +/** + * The `Enumerations` class contains enumerations and arrays of elements used throughout the + * library. All its properties are static and should be referenced using the class name. For + * example: `Enumerations.CHANNEL_MESSAGES`. + * + * @license Apache-2.0 + * @since 3.0.0 + */class Enumerations{static get MIDI_CHANNEL_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MESSAGES enum has been deprecated. Use the Enumerations.CHANNEL_MESSAGES enum instead."),Enumerations.CHANNEL_MESSAGES}static get CHANNEL_MESSAGES(){return{noteoff:8,noteon:9,keyaftertouch:10,controlchange:11,programchange:12,channelaftertouch:13,pitchbend:14}}static get CHANNEL_NUMBERS(){return[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]}static get MIDI_CHANNEL_NUMBERS(){return this.validation&&console.warn("The MIDI_CHANNEL_NUMBERS array has been deprecated. Use the Enumerations.CHANNEL_NUMBERS array instead."),[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]}static get CHANNEL_MODE_MESSAGES(){return{allsoundoff:120,resetallcontrollers:121,localcontrol:122,allnotesoff:123,omnimodeoff:124,omnimodeon:125,monomodeon:126,polymodeon:127}}static get MIDI_CHANNEL_MODE_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MODE_MESSAGES enum has been deprecated. Use the Enumerations.CHANNEL_MODE_MESSAGES enum instead."),Enumerations.CHANNEL_MODE_MESSAGES}static get MIDI_CONTROL_CHANGE_MESSAGES(){return this.validation&&console.warn("The MIDI_CONTROL_CHANGE_MESSAGES enum has been deprecated. Use the Enumerations.CONTROL_CHANGE_MESSAGES array instead."),{bankselectcoarse:0,modulationwheelcoarse:1,breathcontrollercoarse:2,controller3:3,footcontrollercoarse:4,portamentotimecoarse:5,dataentrycoarse:6,volumecoarse:7,balancecoarse:8,controller9:9,pancoarse:10,expressioncoarse:11,effectcontrol1coarse:12,effectcontrol2coarse:13,controller14:14,controller15:15,generalpurposeslider1:16,generalpurposeslider2:17,generalpurposeslider3:18,generalpurposeslider4:19,controller20:20,controller21:21,controller22:22,controller23:23,controller24:24,controller25:25,controller26:26,controller27:27,controller28:28,controller29:29,controller30:30,controller31:31,bankselectfine:32,modulationwheelfine:33,breathcontrollerfine:34,controller35:35,footcontrollerfine:36,portamentotimefine:37,dataentryfine:38,volumefine:39,balancefine:40,controller41:41,panfine:42,expressionfine:43,effectcontrol1fine:44,effectcontrol2fine:45,controller46:46,controller47:47,controller48:48,controller49:49,controller50:50,controller51:51,controller52:52,controller53:53,controller54:54,controller55:55,controller56:56,controller57:57,controller58:58,controller59:59,controller60:60,controller61:61,controller62:62,controller63:63,holdpedal:64,portamento:65,sustenutopedal:66,softpedal:67,legatopedal:68,hold2pedal:69,soundvariation:70,resonance:71,soundreleasetime:72,soundattacktime:73,brightness:74,soundcontrol6:75,soundcontrol7:76,soundcontrol8:77,soundcontrol9:78,soundcontrol10:79,generalpurposebutton1:80,generalpurposebutton2:81,generalpurposebutton3:82,generalpurposebutton4:83,controller84:84,controller85:85,controller86:86,controller87:87,controller88:88,controller89:89,controller90:90,reverblevel:91,tremololevel:92,choruslevel:93,celestelevel:94,phaserlevel:95,databuttonincrement:96,databuttondecrement:97,nonregisteredparametercoarse:98,nonregisteredparameterfine:99,registeredparametercoarse:100,registeredparameterfine:101,controller102:102,controller103:103,controller104:104,controller105:105,controller106:106,controller107:107,controller108:108,controller109:109,controller110:110,controller111:111,controller112:112,controller113:113,controller114:114,controller115:115,controller116:116,controller117:117,controller118:118,controller119:119,allsoundoff:120,resetallcontrollers:121,localcontrol:122,allnotesoff:123,omnimodeoff:124,omnimodeon:125,monomodeon:126,polymodeon:127}}static get CONTROL_CHANGE_MESSAGES(){return[{number:0,name:"bankselectcoarse",description:"Bank Select (Coarse)",position:"msb"},{number:1,name:"modulationwheelcoarse",description:"Modulation Wheel (Coarse)",position:"msb"},{number:2,name:"breathcontrollercoarse",description:"Breath Controller (Coarse)",position:"msb"},{number:3,name:"controller3",description:"Undefined",position:"msb"},{number:4,name:"footcontrollercoarse",description:"Foot Controller (Coarse)",position:"msb"},{number:5,name:"portamentotimecoarse",description:"Portamento Time (Coarse)",position:"msb"},{number:6,name:"dataentrycoarse",description:"Data Entry (Coarse)",position:"msb"},{number:7,name:"volumecoarse",description:"Channel Volume (Coarse)",position:"msb"},{number:8,name:"balancecoarse",description:"Balance (Coarse)",position:"msb"},{number:9,name:"controller9",description:"Controller 9 (Coarse)",position:"msb"},{number:10,name:"pancoarse",description:"Pan (Coarse)",position:"msb"},{number:11,name:"expressioncoarse",description:"Expression Controller (Coarse)",position:"msb"},{number:12,name:"effectcontrol1coarse",description:"Effect Control 1 (Coarse)",position:"msb"},{number:13,name:"effectcontrol2coarse",description:"Effect Control 2 (Coarse)",position:"msb"},{number:14,name:"controller14",description:"Undefined",position:"msb"},{number:15,name:"controller15",description:"Undefined",position:"msb"},{number:16,name:"generalpurposecontroller1",description:"General Purpose Controller 1 (Coarse)",position:"msb"},{number:17,name:"generalpurposecontroller2",description:"General Purpose Controller 2 (Coarse)",position:"msb"},{number:18,name:"generalpurposecontroller3",description:"General Purpose Controller 3 (Coarse)",position:"msb"},{number:19,name:"generalpurposecontroller4",description:"General Purpose Controller 4 (Coarse)",position:"msb"},{number:20,name:"controller20",description:"Undefined",position:"msb"},{number:21,name:"controller21",description:"Undefined",position:"msb"},{number:22,name:"controller22",description:"Undefined",position:"msb"},{number:23,name:"controller23",description:"Undefined",position:"msb"},{number:24,name:"controller24",description:"Undefined",position:"msb"},{number:25,name:"controller25",description:"Undefined",position:"msb"},{number:26,name:"controller26",description:"Undefined",position:"msb"},{number:27,name:"controller27",description:"Undefined",position:"msb"},{number:28,name:"controller28",description:"Undefined",position:"msb"},{number:29,name:"controller29",description:"Undefined",position:"msb"},{number:30,name:"controller30",description:"Undefined",position:"msb"},{number:31,name:"controller31",description:"Undefined",position:"msb"},{number:32,name:"bankselectfine",description:"Bank Select (Fine)",position:"lsb"},{number:33,name:"modulationwheelfine",description:"Modulation Wheel (Fine)",position:"lsb"},{number:34,name:"breathcontrollerfine",description:"Breath Controller (Fine)",position:"lsb"},{number:35,name:"controller35",description:"Undefined",position:"lsb"},{number:36,name:"footcontrollerfine",description:"Foot Controller (Fine)",position:"lsb"},{number:37,name:"portamentotimefine",description:"Portamento Time (Fine)",position:"lsb"},{number:38,name:"dataentryfine",description:"Data Entry (Fine)",position:"lsb"},{number:39,name:"channelvolumefine",description:"Channel Volume (Fine)",position:"lsb"},{number:40,name:"balancefine",description:"Balance (Fine)",position:"lsb"},{number:41,name:"controller41",description:"Undefined",position:"lsb"},{number:42,name:"panfine",description:"Pan (Fine)",position:"lsb"},{number:43,name:"expressionfine",description:"Expression Controller (Fine)",position:"lsb"},{number:44,name:"effectcontrol1fine",description:"Effect control 1 (Fine)",position:"lsb"},{number:45,name:"effectcontrol2fine",description:"Effect control 2 (Fine)",position:"lsb"},{number:46,name:"controller46",description:"Undefined",position:"lsb"},{number:47,name:"controller47",description:"Undefined",position:"lsb"},{number:48,name:"controller48",description:"General Purpose Controller 1 (Fine)",position:"lsb"},{number:49,name:"controller49",description:"General Purpose Controller 2 (Fine)",position:"lsb"},{number:50,name:"controller50",description:"General Purpose Controller 3 (Fine)",position:"lsb"},{number:51,name:"controller51",description:"General Purpose Controller 4 (Fine)",position:"lsb"},{number:52,name:"controller52",description:"Undefined",position:"lsb"},{number:53,name:"controller53",description:"Undefined",position:"lsb"},{number:54,name:"controller54",description:"Undefined",position:"lsb"},{number:55,name:"controller55",description:"Undefined",position:"lsb"},{number:56,name:"controller56",description:"Undefined",position:"lsb"},{number:57,name:"controller57",description:"Undefined",position:"lsb"},{number:58,name:"controller58",description:"Undefined",position:"lsb"},{number:59,name:"controller59",description:"Undefined",position:"lsb"},{number:60,name:"controller60",description:"Undefined",position:"lsb"},{number:61,name:"controller61",description:"Undefined",position:"lsb"},{number:62,name:"controller62",description:"Undefined",position:"lsb"},{number:63,name:"controller63",description:"Undefined",position:"lsb"},{number:64,name:"damperpedal",description:"Damper Pedal On/Off"},{number:65,name:"portamento",description:"Portamento On/Off"},{number:66,name:"sostenuto",description:"Sostenuto On/Off"},{number:67,name:"softpedal",description:"Soft Pedal On/Off"},{number:68,name:"legatopedal",description:"Legato Pedal On/Off"},{number:69,name:"hold2",description:"Hold 2 On/Off"},{number:70,name:"soundvariation",description:"Sound Variation",position:"lsb"},{number:71,name:"resonance",description:"Resonance",position:"lsb"},{number:72,name:"releasetime",description:"Release Time",position:"lsb"},{number:73,name:"attacktime",description:"Attack Time",position:"lsb"},{number:74,name:"brightness",description:"Brightness",position:"lsb"},{number:75,name:"decaytime",description:"Decay Time",position:"lsb"},{number:76,name:"vibratorate",description:"Vibrato Rate",position:"lsb"},{number:77,name:"vibratodepth",description:"Vibrato Depth",position:"lsb"},{number:78,name:"vibratodelay",description:"Vibrato Delay",position:"lsb"},{number:79,name:"controller79",description:"Undefined",position:"lsb"},{number:80,name:"generalpurposecontroller5",description:"General Purpose Controller 5",position:"lsb"},{number:81,name:"generalpurposecontroller6",description:"General Purpose Controller 6",position:"lsb"},{number:82,name:"generalpurposecontroller7",description:"General Purpose Controller 7",position:"lsb"},{number:83,name:"generalpurposecontroller8",description:"General Purpose Controller 8",position:"lsb"},{number:84,name:"portamentocontrol",description:"Portamento Control",position:"lsb"},{number:85,name:"controller85",description:"Undefined"},{number:86,name:"controller86",description:"Undefined"},{number:87,name:"controller87",description:"Undefined"},{number:88,name:"highresolutionvelocityprefix",description:"High Resolution Velocity Prefix",position:"lsb"},{number:89,name:"controller89",description:"Undefined"},{number:90,name:"controller90",description:"Undefined"},{number:91,name:"effect1depth",description:"Effects 1 Depth (Reverb Send Level)"},{number:92,name:"effect2depth",description:"Effects 2 Depth"},{number:93,name:"effect3depth",description:"Effects 3 Depth (Chorus Send Level)"},{number:94,name:"effect4depth",description:"Effects 4 Depth"},{number:95,name:"effect5depth",description:"Effects 5 Depth"},{number:96,name:"dataincrement",description:"Data Increment"},{number:97,name:"datadecrement",description:"Data Decrement"},{number:98,name:"nonregisteredparameterfine",description:"Non-Registered Parameter Number (Fine)",position:"lsb"},{number:99,name:"nonregisteredparametercoarse",description:"Non-Registered Parameter Number (Coarse)",position:"msb"},{number:100,name:"registeredparameterfine",description:"Registered Parameter Number (Fine)",position:"lsb"},{number:101,name:"registeredparametercoarse",description:"Registered Parameter Number (Coarse)",position:"msb"},{number:102,name:"controller102",description:"Undefined"},{number:103,name:"controller103",description:"Undefined"},{number:104,name:"controller104",description:"Undefined"},{number:105,name:"controller105",description:"Undefined"},{number:106,name:"controller106",description:"Undefined"},{number:107,name:"controller107",description:"Undefined"},{number:108,name:"controller108",description:"Undefined"},{number:109,name:"controller109",description:"Undefined"},{number:110,name:"controller110",description:"Undefined"},{number:111,name:"controller111",description:"Undefined"},{number:112,name:"controller112",description:"Undefined"},{number:113,name:"controller113",description:"Undefined"},{number:114,name:"controller114",description:"Undefined"},{number:115,name:"controller115",description:"Undefined"},{number:116,name:"controller116",description:"Undefined"},{number:117,name:"controller117",description:"Undefined"},{number:118,name:"controller118",description:"Undefined"},{number:119,name:"controller119",description:"Undefined"},{number:120,name:"allsoundoff",description:"All Sound Off"},{number:121,name:"resetallcontrollers",description:"Reset All Controllers"},{number:122,name:"localcontrol",description:"Local Control On/Off"},{number:123,name:"allnotesoff",description:"All Notes Off"},{number:124,name:"omnimodeoff",description:"Omni Mode Off"},{number:125,name:"omnimodeon",description:"Omni Mode On"},{number:126,name:"monomodeon",description:"Mono Mode On"},{number:127,name:"polymodeon",description:"Poly Mode On"}]}static get REGISTERED_PARAMETERS(){return{pitchbendrange:[0,0],channelfinetuning:[0,1],channelcoarsetuning:[0,2],tuningprogram:[0,3],tuningbank:[0,4],modulationrange:[0,5],azimuthangle:[61,0],elevationangle:[61,1],gain:[61,2],distanceratio:[61,3],maximumdistance:[61,4],maximumdistancegain:[61,5],referencedistanceratio:[61,6],panspreadangle:[61,7],rollangle:[61,8]}}static get MIDI_REGISTERED_PARAMETERS(){return this.validation&&console.warn("The MIDI_REGISTERED_PARAMETERS enum has been deprecated. Use the Enumerations.REGISTERED_PARAMETERS enum instead."),Enumerations.MIDI_REGISTERED_PARAMETERS}static get SYSTEM_MESSAGES(){return{sysex:240,timecode:241,songposition:242,songselect:243,tunerequest:246,tuningrequest:246,sysexend:247,clock:248,start:250,continue:251,stop:252,activesensing:254,reset:255,midimessage:0,unknownsystemmessage:-1}}static get MIDI_SYSTEM_MESSAGES(){return this.validation&&console.warn("The MIDI_SYSTEM_MESSAGES enum has been deprecated. Use the Enumerations.SYSTEM_MESSAGES enum instead."),Enumerations.SYSTEM_MESSAGES}static get CHANNEL_EVENTS(){return["noteoff","controlchange","noteon","keyaftertouch","programchange","channelaftertouch","pitchbend","allnotesoff","allsoundoff","localcontrol","monomode","omnimode","resetallcontrollers","nrpn","nrpn-dataentrycoarse","nrpn-dataentryfine","nrpn-dataincrement","nrpn-datadecrement","rpn","rpn-dataentrycoarse","rpn-dataentryfine","rpn-dataincrement","rpn-datadecrement","nrpn-databuttonincrement","nrpn-databuttondecrement","rpn-databuttonincrement","rpn-databuttondecrement"]}} +/** + * The `Note` class represents a single musical note such as `"D3"`, `"G#4"`, `"F-1"`, `"Gb7"`, etc. + * + * `Note` objects can be played back on a single channel by calling + * [`OutputChannel.playNote()`]{@link OutputChannel#playNote} or, on multiple channels of the same + * output, by calling [`Output.playNote()`]{@link Output#playNote}. + * + * The note has [`attack`](#attack) and [`release`](#release) velocities set at `0.5` by default. + * These can be changed by passing in the appropriate option. It is also possible to set a + * system-wide default for attack and release velocities by using the + * [`WebMidi.defaults`](WebMidi#defaults) property. + * + * If you prefer to work with raw MIDI values (`0` to `127`), you can use [`rawAttack`](#rawAttack) and + * [`rawRelease`](#rawRelease) to both get and set the values. + * + * The note may have a [`duration`](#duration). If it does, playback will be automatically stopped + * when the duration has elapsed by sending a `"noteoff"` event. By default, the duration is set to + * `Infinity`. In this case, it will never stop playing unless explicitly stopped by calling a + * method such as [`OutputChannel.stopNote()`]{@link OutputChannel#stopNote}, + * [`Output.stopNote()`]{@link Output#stopNote} or similar. + * + * @license Apache-2.0 + * @since 3.0.0 + */class Note{constructor(e,t={}){this.duration=wm.defaults.note.duration,this.attack=wm.defaults.note.attack,this.release=wm.defaults.note.release,null!=t.duration&&(this.duration=t.duration),null!=t.attack&&(this.attack=t.attack),null!=t.rawAttack&&(this.attack=Utilities.from7bitToFloat(t.rawAttack)),null!=t.release&&(this.release=t.release),null!=t.rawRelease&&(this.release=Utilities.from7bitToFloat(t.rawRelease)),Number.isInteger(e)?this.identifier=Utilities.toNoteIdentifier(e):this.identifier=e}get identifier(){return this._name+(this._accidental||"")+this._octave}set identifier(e){const t=Utilities.getNoteDetails(e);if(wm.validation&&!e)throw new Error("Invalid note identifier");this._name=t.name,this._accidental=t.accidental,this._octave=t.octave}get name(){return this._name}set name(e){if(wm.validation&&(e=e.toUpperCase(),!["C","D","E","F","G","A","B"].includes(e)))throw new Error("Invalid name value");this._name=e}get accidental(){return this._accidental}set accidental(e){if(wm.validation&&(e=e.toLowerCase(),!["#","##","b","bb"].includes(e)))throw new Error("Invalid accidental value");this._accidental=e}get octave(){return this._octave}set octave(e){if(wm.validation&&(e=parseInt(e),isNaN(e)))throw new Error("Invalid octave value");this._octave=e}get duration(){return this._duration}set duration(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||null===e||e<0))throw new RangeError("Invalid duration value.");this._duration=e}get attack(){return this._attack}set attack(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||!(e>=0&&e<=1)))throw new RangeError("Invalid attack value.");this._attack=e}get release(){return this._release}set release(e){if(wm.validation&&(e=parseFloat(e),isNaN(e)||!(e>=0&&e<=1)))throw new RangeError("Invalid release value.");this._release=e}get rawAttack(){return Utilities.fromFloatTo7Bit(this._attack)}set rawAttack(e){this._attack=Utilities.from7bitToFloat(e)}get rawRelease(){return Utilities.fromFloatTo7Bit(this._release)}set rawRelease(e){this._release=Utilities.from7bitToFloat(e)}get number(){return Utilities.toNoteNumber(this.identifier)}getOffsetNumber(e=0,t=0){return wm.validation&&(e=parseInt(e)||0,t=parseInt(t)||0),Math.min(Math.max(this.number+12*e+t,0),127)}} +/** + * The `Utilities` class contains general-purpose utility methods. All methods are static and + * should be called using the class name. For example: `Utilities.getNoteDetails("C4")`. + * + * @license Apache-2.0 + * @since 3.0.0 + */class Utilities{ +/** + * Returns a MIDI note number matching the identifier passed in the form of a string. The + * identifier must include the octave number. The identifier also optionally include a sharp (#), + * a double sharp (##), a flat (b) or a double flat (bb) symbol. For example, these are all valid + * identifiers: C5, G4, D#-1, F0, Gb7, Eb-1, Abb4, B##6, etc. + * + * When converting note identifiers to numbers, C4 is considered to be middle C (MIDI note number + * 60) as per the scientific pitch notation standard. + * + * The resulting note number can be offset by using the `octaveOffset` parameter. + * + * @param identifier {string} The identifier in the form of a letter, followed by an optional "#", + * "##", "b" or "bb" followed by the octave number. For exemple: C5, G4, D#-1, F0, Gb7, Eb-1, + * Abb4, B##6, etc. + * + * @param {number} [octaveOffset=0] A integer to offset the octave by. + * + * @returns {number} The MIDI note number (an integer between 0 and 127). + * + * @throws RangeError Invalid 'octaveOffset' value + * + * @throws TypeError Invalid note identifier + * + * @license Apache-2.0 + * @since 3.0.0 + * @static + */ +static toNoteNumber(e,t=0){if(t=null==t?0:parseInt(t),isNaN(t))throw new RangeError("Invalid 'octaveOffset' value");"string"!=typeof e&&(e="");const n=this.getNoteDetails(e);if(!n)throw new TypeError("Invalid note identifier");let r=12*(n.octave+1+t);if(r+={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[n.name],n.accidental&&(n.accidental.startsWith("b")?r-=n.accidental.length:r+=n.accidental.length),r<0||r>127)throw new RangeError("Invalid octaveOffset value");return r}static getNoteDetails(e){Number.isInteger(e)&&(e=this.toNoteIdentifier(e));const t=e.match(/^([CDEFGAB])(#{0,2}|b{0,2})(-?\d+)$/i);if(!t)throw new TypeError("Invalid note identifier");const n=t[1].toUpperCase(),r=parseInt(t[3]);let i=t[2].toLowerCase();i=""===i?void 0:i;return{accidental:i,identifier:n+(i||"")+r,name:n,octave:r}}static sanitizeChannels(e){let t;if(wm.validation)if("all"===e)t=["all"];else if("none"===e)return[];return t=Array.isArray(e)?e:[e],t.indexOf("all")>-1&&(t=Enumerations.MIDI_CHANNEL_NUMBERS),t.map((function(e){return parseInt(e)})).filter((function(e){return e>=1&&e<=16}))}static toTimestamp(e){let t=!1;const n=parseFloat(e);return!isNaN(n)&&("string"==typeof e&&"+"===e.substring(0,1)?n>=0&&(t=wm.time+n):n>=0&&(t=n),t)}static guessNoteNumber(e,t){t=parseInt(t)||0;let n=!1;if(Number.isInteger(e)&&e>=0&&e<=127)n=parseInt(e);else if(parseInt(e)>=0&&parseInt(e)<=127)n=parseInt(e);else if("string"==typeof e||e instanceof String)try{n=this.toNoteNumber(e.trim(),t)}catch(e){return!1}return n}static toNoteIdentifier(e,t){if(e=parseInt(e),isNaN(e)||e<0||e>127)throw new RangeError("Invalid note number");if(t=null==t?0:parseInt(t),isNaN(t))throw new RangeError("Invalid octaveOffset value");const n=Math.floor(e/12-1)+t;return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][e%12]+n.toString()}static buildNote(e,t={}){if(t.octaveOffset=parseInt(t.octaveOffset)||0,e instanceof Note)return e;let n=this.guessNoteNumber(e,t.octaveOffset);if(!1===n)throw new TypeError(`The input could not be parsed as a note (${e})`);return t.octaveOffset=void 0,new Note(n,t)}static buildNoteArray(e,t={}){let n=[];return Array.isArray(e)||(e=[e]),e.forEach(e=>{n.push(this.buildNote(e,t))}),n}static from7bitToFloat(e){return e===1/0&&(e=127),e=parseInt(e)||0,Math.min(Math.max(e/127,0),1)}static fromFloatTo7Bit(e){return e===1/0&&(e=1),e=parseFloat(e)||0,Math.min(Math.max(Math.round(127*e),0),127)}static fromMsbLsbToFloat(e,t=0){wm.validation&&(e=Math.min(Math.max(parseInt(e)||0,0),127),t=Math.min(Math.max(parseInt(t)||0,0),127));const n=((e<<7)+t)/16383;return Math.min(Math.max(n,0),1)}static fromFloatToMsbLsb(e){wm.validation&&(e=Math.min(Math.max(parseFloat(e)||0,0),1));const t=Math.round(16383*e);return{msb:t>>7,lsb:127&t}}static offsetNumber(e,t=0,n=0){if(wm.validation){if(e=parseInt(e),isNaN(e))throw new Error("Invalid note number");t=parseInt(t)||0,n=parseInt(n)||0}return Math.min(Math.max(e+12*t+n,0),127)}static getPropertyByValue(e,t){return Object.keys(e).find(n=>e[n]===t)}static getCcNameByNumber(e){if(!wm.validation||(e=parseInt(e))>=0&&e<=127)return Enumerations.CONTROL_CHANGE_MESSAGES[e].name}static getCcNumberByName(e){let t=Enumerations.CONTROL_CHANGE_MESSAGES.find(t=>t.name===e);return t?t.number:Enumerations.MIDI_CONTROL_CHANGE_MESSAGES[e]}static getChannelModeByNumber(e){if(!(e>=120&&e<=127))return!1;for(let t in Enumerations.CHANNEL_MODE_MESSAGES)if(Enumerations.CHANNEL_MODE_MESSAGES.hasOwnProperty(t)&&e===Enumerations.CHANNEL_MODE_MESSAGES[t])return t;return!1}static get isNode(){return"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node}static get isBrowser(){return"undefined"!=typeof window&&void 0!==window.document}} +/** + * The `OutputChannel` class represents a single output MIDI channel. `OutputChannel` objects are + * provided by an [`Output`](Output) port which, itself, is made available by a device. The + * `OutputChannel` object is derived from the host's MIDI subsystem and should not be instantiated + * directly. + * + * All 16 `OutputChannel` objects can be found inside the parent output's + * [`channels`]{@link Output#channels} property. + * + * @param {Output} output The [`Output`](Output) this channel belongs to. + * @param {number} number The MIDI channel number (`1` - `16`). + * + * @extends EventEmitter + * @license Apache-2.0 + * @since 3.0.0 + */class OutputChannel extends EventEmitter{constructor(e,t){super(),this._output=e,this._number=t,this._octaveOffset=0}destroy(){this._output=null,this._number=null,this._octaveOffset=0,this.removeListener()}send(e,t={time:0}){return this.output.send(e,t),this}sendKeyAftertouch(e,t,n={}){if(wm.validation){if(n.useRawValue&&(n.rawValue=n.useRawValue),isNaN(parseFloat(t)))throw new RangeError("Invalid key aftertouch value.");if(n.rawValue){if(!(t>=0&&t<=127&&Number.isInteger(t)))throw new RangeError("Key aftertouch raw value must be an integer between 0 and 127.")}else if(!(t>=0&&t<=1))throw new RangeError("Key aftertouch value must be a float between 0 and 1.")}n.rawValue||(t=Utilities.fromFloatTo7Bit(t));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Array.isArray(e)||(e=[e]),Utilities.buildNoteArray(e).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.keyaftertouch<<4)+(this.number-1),e.getOffsetNumber(r),t],{time:Utilities.toTimestamp(n.time)})}),this} +/** + * Sends a MIDI **control change** message to the channel at the scheduled time. The control + * change message to send can be specified numerically (`0` to `127`) or by using one of the + * following common names: + * + * | Number | Name | + * |--------|-------------------------------| + * | 0 |`bankselectcoarse` | + * | 1 |`modulationwheelcoarse` | + * | 2 |`breathcontrollercoarse` | + * | 4 |`footcontrollercoarse` | + * | 5 |`portamentotimecoarse` | + * | 6 |`dataentrycoarse` | + * | 7 |`volumecoarse` | + * | 8 |`balancecoarse` | + * | 10 |`pancoarse` | + * | 11 |`expressioncoarse` | + * | 12 |`effectcontrol1coarse` | + * | 13 |`effectcontrol2coarse` | + * | 18 |`generalpurposeslider3` | + * | 19 |`generalpurposeslider4` | + * | 32 |`bankselectfine` | + * | 33 |`modulationwheelfine` | + * | 34 |`breathcontrollerfine` | + * | 36 |`footcontrollerfine` | + * | 37 |`portamentotimefine` | + * | 38 |`dataentryfine` | + * | 39 |`volumefine` | + * | 40 |`balancefine` | + * | 42 |`panfine` | + * | 43 |`expressionfine` | + * | 44 |`effectcontrol1fine` | + * | 45 |`effectcontrol2fine` | + * | 64 |`holdpedal` | + * | 65 |`portamento` | + * | 66 |`sustenutopedal` | + * | 67 |`softpedal` | + * | 68 |`legatopedal` | + * | 69 |`hold2pedal` | + * | 70 |`soundvariation` | + * | 71 |`resonance` | + * | 72 |`soundreleasetime` | + * | 73 |`soundattacktime` | + * | 74 |`brightness` | + * | 75 |`soundcontrol6` | + * | 76 |`soundcontrol7` | + * | 77 |`soundcontrol8` | + * | 78 |`soundcontrol9` | + * | 79 |`soundcontrol10` | + * | 80 |`generalpurposebutton1` | + * | 81 |`generalpurposebutton2` | + * | 82 |`generalpurposebutton3` | + * | 83 |`generalpurposebutton4` | + * | 91 |`reverblevel` | + * | 92 |`tremololevel` | + * | 93 |`choruslevel` | + * | 94 |`celestelevel` | + * | 95 |`phaserlevel` | + * | 96 |`dataincrement` | + * | 97 |`datadecrement` | + * | 98 |`nonregisteredparametercoarse` | + * | 99 |`nonregisteredparameterfine` | + * | 100 |`registeredparametercoarse` | + * | 101 |`registeredparameterfine` | + * | 120 |`allsoundoff` | + * | 121 |`resetallcontrollers` | + * | 122 |`localcontrol` | + * | 123 |`allnotesoff` | + * | 124 |`omnimodeoff` | + * | 125 |`omnimodeon` | + * | 126 |`monomodeon` | + * | 127 |`polymodeon` | + * + * As you can see above, not all control change message have a matching name. This does not mean + * you cannot use the others. It simply means you will need to use their number + * (`0` to `127`) instead of their name. While you can still use them, numbers `120` to `127` are + * usually reserved for *channel mode* messages. See + * [`sendChannelMode()`]{@link OutputChannel#sendChannelMode} method for more info. + * + * To view a detailed list of all available **control change** messages, please consult "Table 3 - + * Control Change Messages" from the [MIDI Messages]( + * https://www.midi.org/specifications/item/table-3-control-change-messages-data-bytes-2) + * specification. + * + * **Note**: messages #0-31 (MSB) are paired with messages #32-63 (LSB). For example, message #1 + * (`modulationwheelcoarse`) can be accompanied by a second control change message for + * `modulationwheelfine` to achieve a greater level of precision. if you want to specify both MSB + * and LSB for messages between `0` and `31`, you can do so by passing a 2-value array as the + * second parameter. + * + * @param {number|string} controller The MIDI controller name or number (`0` - `127`). + * + * @param {number|number[]} value The value to send (0-127). You can also use a two-position array + * for controllers 0 to 31. In this scenario, the first value will be sent as usual and the second + * value will be sent to the matching LSB controller (which is obtained by adding 32 to the first + * controller) + * + * @param {object} [options={}] + * + * @param {number|string} [options.time=(now)] If `time` is a string prefixed with `"+"` and + * followed by a number, the message will be delayed by that many milliseconds. If the value is a + * positive number + * ([`DOMHighResTimeStamp`]{@link https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp}), + * the operation will be scheduled for that time. The current time can be retrieved with + * [`WebMidi.time`]{@link WebMidi#time}. If `options.time` is omitted, or in the past, the + * operation will be carried out as soon as possible. + * + * @throws {RangeError} Controller numbers must be between 0 and 127. + * @throws {RangeError} Invalid controller name. + * @throws {TypeError} The value array must have a length of 2. + * + * @returns {OutputChannel} Returns the `OutputChannel` object so methods can be chained. + * + * @license Apache-2.0 + * @since 3.0.0 + */sendControlChange(e,t,n={}){if("string"==typeof e&&(e=Utilities.getCcNumberByName(e)),Array.isArray(t)||(t=[t]),wm.validation){if(void 0===e)throw new TypeError("Control change must be identified with a valid name or an integer between 0 and 127.");if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new TypeError("Control change number must be an integer between 0 and 127.");if(2===(t=t.map(e=>{const t=Math.min(Math.max(parseInt(e),0),127);if(isNaN(t))throw new TypeError("Values must be integers between 0 and 127");return t})).length&&e>=32)throw new TypeError("To use a value array, the controller must be between 0 and 31")}return t.forEach((r,i)=>{this.send([(Enumerations.CHANNEL_MESSAGES.controlchange<<4)+(this.number-1),e+32*i,t[i]],{time:Utilities.toTimestamp(n.time)})}),this}_selectNonRegisteredParameter(e,t={}){return this.sendControlChange(99,e[0],t),this.sendControlChange(98,e[1],t),this}_deselectRegisteredParameter(e={}){return this.sendControlChange(101,127,e),this.sendControlChange(100,127,e),this}_deselectNonRegisteredParameter(e={}){return this.sendControlChange(101,127,e),this.sendControlChange(100,127,e),this}_selectRegisteredParameter(e,t={}){return this.sendControlChange(101,e[0],t),this.sendControlChange(100,e[1],t),this}_setCurrentParameter(e,t={}){return e=[].concat(e),this.sendControlChange(6,e[0],t),e.length<2||this.sendControlChange(38,e[1],t),this}sendRpnDecrement(e,t={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(void 0===e)throw new TypeError("The specified registered parameter is invalid.");let t=!1;if(Object.getOwnPropertyNames(Enumerations.REGISTERED_PARAMETERS).forEach(n=>{Enumerations.REGISTERED_PARAMETERS[n][0]===e[0]&&Enumerations.REGISTERED_PARAMETERS[n][1]===e[1]&&(t=!0)}),!t)throw new TypeError("The specified registered parameter is invalid.")}return this._selectRegisteredParameter(e,t),this.sendControlChange(97,0,t),this._deselectRegisteredParameter(t),this}sendRpnIncrement(e,t={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(void 0===e)throw new TypeError("The specified registered parameter is invalid.");let t=!1;if(Object.getOwnPropertyNames(Enumerations.REGISTERED_PARAMETERS).forEach(n=>{Enumerations.REGISTERED_PARAMETERS[n][0]===e[0]&&Enumerations.REGISTERED_PARAMETERS[n][1]===e[1]&&(t=!0)}),!t)throw new TypeError("The specified registered parameter is invalid.")}return this._selectRegisteredParameter(e,t),this.sendControlChange(96,0,t),this._deselectRegisteredParameter(t),this}playNote(e,t={}){this.sendNoteOn(e,t);const n=Array.isArray(e)?e:[e];for(let e of n)if(parseInt(e.duration)>0){const n={time:(Utilities.toTimestamp(t.time)||wm.time)+parseInt(e.duration),release:e.release,rawRelease:e.rawRelease};this.sendNoteOff(e,n)}else if(parseInt(t.duration)>0){const n={time:(Utilities.toTimestamp(t.time)||wm.time)+parseInt(t.duration),release:t.release,rawRelease:t.rawRelease};this.sendNoteOff(e,n)}return this}sendNoteOff(e,t={}){if(wm.validation){if(null!=t.rawRelease&&!(t.rawRelease>=0&&t.rawRelease<=127))throw new RangeError("The 'rawRelease' option must be an integer between 0 and 127");if(null!=t.release&&!(t.release>=0&&t.release<=1))throw new RangeError("The 'release' option must be an number between 0 and 1");t.rawVelocity&&(t.rawRelease=t.velocity,console.warn("The 'rawVelocity' option is deprecated. Use 'rawRelease' instead.")),t.velocity&&(t.release=t.velocity,console.warn("The 'velocity' option is deprecated. Use 'attack' instead."))}let n=64;null!=t.rawRelease?n=t.rawRelease:isNaN(t.release)||(n=Math.round(127*t.release));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Utilities.buildNoteArray(e,{rawRelease:parseInt(n)}).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.noteoff<<4)+(this.number-1),e.getOffsetNumber(r),e.rawRelease],{time:Utilities.toTimestamp(t.time)})}),this}stopNote(e,t={}){return this.sendNoteOff(e,t)}sendNoteOn(e,t={}){if(wm.validation){if(null!=t.rawAttack&&!(t.rawAttack>=0&&t.rawAttack<=127))throw new RangeError("The 'rawAttack' option must be an integer between 0 and 127");if(null!=t.attack&&!(t.attack>=0&&t.attack<=1))throw new RangeError("The 'attack' option must be an number between 0 and 1");t.rawVelocity&&(t.rawAttack=t.velocity,t.rawRelease=t.release,console.warn("The 'rawVelocity' option is deprecated. Use 'rawAttack' or 'rawRelease'.")),t.velocity&&(t.attack=t.velocity,console.warn("The 'velocity' option is deprecated. Use 'attack' instead."))}let n=64;null!=t.rawAttack?n=t.rawAttack:isNaN(t.attack)||(n=Math.round(127*t.attack));const r=wm.octaveOffset+this.output.octaveOffset+this.octaveOffset;return Utilities.buildNoteArray(e,{rawAttack:n}).forEach(e=>{this.send([(Enumerations.CHANNEL_MESSAGES.noteon<<4)+(this.number-1),e.getOffsetNumber(r),e.rawAttack],{time:Utilities.toTimestamp(t.time)})}),this}sendChannelMode(e,t=0,n={}){if("string"==typeof e&&(e=Enumerations.CHANNEL_MODE_MESSAGES[e]),wm.validation){if(void 0===e)throw new TypeError("Invalid channel mode message name or number.");if(isNaN(e)||!(e>=120&&e<=127))throw new TypeError("Invalid channel mode message number.");if(isNaN(parseInt(t))||t<0||t>127)throw new RangeError("Value must be an integer between 0 and 127.")}return this.send([(Enumerations.CHANNEL_MESSAGES.controlchange<<4)+(this.number-1),e,t],{time:Utilities.toTimestamp(n.time)}),this}sendOmniMode(e,t={}){return void 0===e||e?this.sendChannelMode("omnimodeon",0,t):this.sendChannelMode("omnimodeoff",0,t),this}sendChannelAftertouch(e,t={}){if(wm.validation){if(isNaN(parseFloat(e)))throw new RangeError("Invalid channel aftertouch value.");if(t.rawValue){if(!(e>=0&&e<=127&&Number.isInteger(e)))throw new RangeError("Channel aftertouch raw value must be an integer between 0 and 127.")}else if(!(e>=0&&e<=1))throw new RangeError("Channel aftertouch value must be a float between 0 and 1.")}return t.rawValue||(e=Utilities.fromFloatTo7Bit(e)),this.send([(Enumerations.CHANNEL_MESSAGES.channelaftertouch<<4)+(this.number-1),Math.round(e)],{time:Utilities.toTimestamp(t.time)}),this}sendMasterTuning(e,t={}){if(e=parseFloat(e)||0,wm.validation&&!(e>-65&&e<64))throw new RangeError("The value must be a decimal number larger than -65 and smaller than 64.");let n=Math.floor(e)+64,r=e-Math.floor(e);r=Math.round((r+1)/2*16383);let i=r>>7&127,s=127&r;return this.sendRpnValue("channelcoarsetuning",n,t),this.sendRpnValue("channelfinetuning",[i,s],t),this}sendModulationRange(e,t,n={}){if(wm.validation){if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new RangeError("The semitones value must be an integer between 0 and 127.");if(!(null==t||Number.isInteger(t)&&t>=0&&t<=127))throw new RangeError("If specified, the cents value must be an integer between 0 and 127.")}return t>=0&&t<=127||(t=0),this.sendRpnValue("modulationrange",[e,t],n),this}sendNrpnValue(e,t,n={}){if(t=[].concat(t),wm.validation){if(!Array.isArray(e)||!Number.isInteger(e[0])||!Number.isInteger(e[1]))throw new TypeError("The specified NRPN is invalid.");if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The first byte of the NRPN must be between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The second byte of the NRPN must be between 0 and 127.");t.forEach(e=>{if(!(e>=0&&e<=127))throw new RangeError("The data bytes of the NRPN must be between 0 and 127.")})}return this._selectNonRegisteredParameter(e,n),this._setCurrentParameter(t,n),this._deselectNonRegisteredParameter(n),this}sendPitchBend(e,t={}){if(wm.validation)if(t.rawValue&&Array.isArray(e)){if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The pitch bend MSB must be an integer between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The pitch bend LSB must be an integer between 0 and 127.")}else if(t.rawValue&&!Array.isArray(e)){if(!(e>=0&&e<=127))throw new RangeError("The pitch bend MSB must be an integer between 0 and 127.")}else{if(isNaN(e)||null===e)throw new RangeError("Invalid pitch bend value.");if(!(e>=-1&&e<=1))throw new RangeError("The pitch bend value must be a float between -1 and 1.")}let n=0,r=0;if(t.rawValue&&Array.isArray(e))n=e[0],r=e[1];else if(t.rawValue&&!Array.isArray(e))n=e;else{const t=Utilities.fromFloatToMsbLsb((e+1)/2);n=t.msb,r=t.lsb}return this.send([(Enumerations.CHANNEL_MESSAGES.pitchbend<<4)+(this.number-1),r,n],{time:Utilities.toTimestamp(t.time)}),this}sendPitchBendRange(e,t,n={}){if(wm.validation){if(!Number.isInteger(e)||!(e>=0&&e<=127))throw new RangeError("The semitones value must be an integer between 0 and 127.");if(!Number.isInteger(t)||!(t>=0&&t<=127))throw new RangeError("The cents value must be an integer between 0 and 127.")}return this.sendRpnValue("pitchbendrange",[e,t],n),this}sendProgramChange(e,t={}){if(e=parseInt(e)||0,wm.validation&&!(e>=0&&e<=127))throw new RangeError("The program number must be between 0 and 127.");return this.send([(Enumerations.CHANNEL_MESSAGES.programchange<<4)+(this.number-1),e],{time:Utilities.toTimestamp(t.time)}),this}sendRpnValue(e,t,n={}){if(Array.isArray(e)||(e=Enumerations.REGISTERED_PARAMETERS[e]),wm.validation){if(!Number.isInteger(e[0])||!Number.isInteger(e[1]))throw new TypeError("The specified NRPN is invalid.");if(!(e[0]>=0&&e[0]<=127))throw new RangeError("The first byte of the RPN must be between 0 and 127.");if(!(e[1]>=0&&e[1]<=127))throw new RangeError("The second byte of the RPN must be between 0 and 127.");[].concat(t).forEach(e=>{if(!(e>=0&&e<=127))throw new RangeError("The data bytes of the RPN must be between 0 and 127.")})}return this._selectRegisteredParameter(e,n),this._setCurrentParameter(t,n),this._deselectRegisteredParameter(n),this}sendTuningBank(e,t={}){if(wm.validation&&(!Number.isInteger(e)||!(e>=0&&e<=127)))throw new RangeError("The tuning bank number must be between 0 and 127.");return this.sendRpnValue("tuningbank",e,t),this}sendTuningProgram(e,t={}){if(wm.validation&&(!Number.isInteger(e)||!(e>=0&&e<=127)))throw new RangeError("The tuning program number must be between 0 and 127.");return this.sendRpnValue("tuningprogram",e,t),this}sendLocalControl(e,t={}){return e?this.sendChannelMode("localcontrol",127,t):this.sendChannelMode("localcontrol",0,t)}sendAllNotesOff(e={}){return this.sendChannelMode("allnotesoff",0,e)}sendAllSoundOff(e={}){return this.sendChannelMode("allsoundoff",0,e)}sendResetAllControllers(e={}){return this.sendChannelMode("resetallcontrollers",0,e)}sendPolyphonicMode(e,t={}){return"mono"===e?this.sendChannelMode("monomodeon",0,t):this.sendChannelMode("polymodeon",0,t)}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get output(){return this._output}get number(){return this._number}} +/** + * The `Output` class represents a single MIDI output port (not to be confused with a MIDI channel). + * A port is made available by a MIDI device. A MIDI device can advertise several input and output + * ports. Each port has 16 MIDI channels which can be accessed via the [`channels`](#channels) + * property. + * + * The `Output` object is automatically instantiated by the library according to the host's MIDI + * subsystem and should not be directly instantiated. + * + * You can access all available `Output` objects by referring to the + * [`WebMidi.outputs`](WebMidi#outputs) array or by using methods such as + * [`WebMidi.getOutputByName()`](WebMidi#getOutputByName) or + * [`WebMidi.getOutputById()`](WebMidi#getOutputById). + * + * @fires Output#opened + * @fires Output#disconnected + * @fires Output#closed + * + * @extends EventEmitter + * @license Apache-2.0 + */class Output extends EventEmitter{constructor(e){super(),this._midiOutput=e,this._octaveOffset=0,this.channels=[];for(let e=1;e<=16;e++)this.channels[e]=new OutputChannel(this,e);this._midiOutput.onstatechange=this._onStateChange.bind(this)}async destroy(){this.removeListener(),this.channels.forEach(e=>e.destroy()),this.channels=[],this._midiOutput&&(this._midiOutput.onstatechange=null),await this.close(),this._midiOutput=null}_onStateChange(e){let t={timestamp:wm.time};"open"===e.port.connection?(t.type="opened",t.target=this,t.port=t.target,this.emit("opened",t)):"closed"===e.port.connection&&"connected"===e.port.state?(t.type="closed",t.target=this,t.port=t.target,this.emit("closed",t)):"closed"===e.port.connection&&"disconnected"===e.port.state?(t.type="disconnected",t.port={connection:e.port.connection,id:e.port.id,manufacturer:e.port.manufacturer,name:e.port.name,state:e.port.state,type:e.port.type},this.emit("disconnected",t)):"pending"===e.port.connection&&"disconnected"===e.port.state||console.warn("This statechange event was not caught:",e.port.connection,e.port.state)}async open(){try{return await this._midiOutput.open(),Promise.resolve(this)}catch(e){return Promise.reject(e)}}async close(){this._midiOutput?await this._midiOutput.close():await Promise.resolve()} +/** + * Sends a MIDI message on the MIDI output port. If no time is specified, the message will be + * sent immediately. The message should be an array of 8 bit unsigned integers (0-225), a + * [`Uint8Array`]{@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array} + * object or a [`Message`](Message) object. + * + * It is usually not necessary to use this method directly as you can use one of the simpler + * helper methods such as [`playNote()`](#playNote), [`stopNote()`](#stopNote), + * [`sendControlChange()`](#sendControlChange), etc. + * + * Details on the format of MIDI messages are available in the summary of + * [MIDI messages]{@link https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message} + * from the MIDI Manufacturers Association. + * + * @param message {number[]|Uint8Array|Message} An array of 8bit unsigned integers, a `Uint8Array` + * object (not available in Node.js) containing the message bytes or a `Message` object. + * + * @param {object} [options={}] + * + * @param {number|string} [options.time=(now)] If `time` is a string prefixed with `"+"` and + * followed by a number, the message will be delayed by that many milliseconds. If the value is a + * positive number + * ([`DOMHighResTimeStamp`]{@link https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp}), + * the operation will be scheduled for that time. The current time can be retrieved with + * [`WebMidi.time`]{@link WebMidi#time}. If `options.time` is omitted, or in the past, the + * operation will be carried out as soon as possible. + * + * @throws {RangeError} The first byte (status) must be an integer between 128 and 255. + * + * @returns {Output} Returns the `Output` object so methods can be chained. + * + * @license Apache-2.0 + */send(e,t={time:0},n=0){if(e instanceof Message&&(e=Utilities.isNode?e.data:e.rawData),e instanceof Uint8Array&&Utilities.isNode&&(e=Array.from(e)),wm.validation){if(Array.isArray(e)||e instanceof Uint8Array||(e=[e],Array.isArray(t)&&(e=e.concat(t)),t=isNaN(n)?{time:0}:{time:n}),!(parseInt(e[0])>=128&&parseInt(e[0])<=255))throw new RangeError("The first byte (status) must be an integer between 128 and 255.");e.slice(1).forEach(e=>{if(!((e=parseInt(e))>=0&&e<=255))throw new RangeError("Data bytes must be integers between 0 and 255.")}),t||(t={time:0})}return this._midiOutput.send(e,Utilities.toTimestamp(t.time)),this}sendSysex(e,t=[],n={}){if(e=[].concat(e),t instanceof Uint8Array){const r=new Uint8Array(1+e.length+t.length+1);r[0]=Enumerations.SYSTEM_MESSAGES.sysex,r.set(Uint8Array.from(e),1),r.set(t,1+e.length),r[r.length-1]=Enumerations.SYSTEM_MESSAGES.sysexend,this.send(r,{time:n.time})}else{const r=e.concat(t,Enumerations.SYSTEM_MESSAGES.sysexend);this.send([Enumerations.SYSTEM_MESSAGES.sysex].concat(r),{time:n.time})}return this}clear(){return this._midiOutput.clear?this._midiOutput.clear():wm.validation&&console.warn("The 'clear()' method has not yet been implemented in your environment."),this}sendTimecodeQuarterFrame(e,t={}){if(wm.validation&&(e=parseInt(e),isNaN(e)||!(e>=0&&e<=127)))throw new RangeError("The value must be an integer between 0 and 127.");return this.send([Enumerations.SYSTEM_MESSAGES.timecode,e],{time:t.time}),this}sendSongPosition(e=0,t={}){var n=(e=Math.floor(e)||0)>>7&127,r=127&e;return this.send([Enumerations.SYSTEM_MESSAGES.songposition,n,r],{time:t.time}),this}sendSongSelect(e=0,t={}){if(wm.validation&&(e=parseInt(e),isNaN(e)||!(e>=0&&e<=127)))throw new RangeError("The program value must be between 0 and 127");return this.send([Enumerations.SYSTEM_MESSAGES.songselect,e],{time:t.time}),this}sendTuneRequest(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.tunerequest],{time:e.time}),this}sendClock(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.clock],{time:e.time}),this}sendStart(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.start],{time:e.time}),this}sendContinue(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.continue],{time:e.time}),this}sendStop(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.stop],{time:e.time}),this}sendActiveSensing(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.activesensing],{time:e.time}),this}sendReset(e={}){return this.send([Enumerations.SYSTEM_MESSAGES.reset],{time:e.time}),this}sendTuningRequest(e={}){return wm.validation&&console.warn("The sendTuningRequest() method has been deprecated. Use sendTuningRequest() instead."),this.sendTuneRequest(e)}sendKeyAftertouch(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendKeyAftertouch(e,t,n)}),this}sendControlChange(e,t,n={},r={}){if(wm.validation&&(Array.isArray(n)||Number.isInteger(n)||"all"===n)){const e=n;(n=r).channels=e,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendControlChange(e,t,n)}),this}sendPitchBendRange(e=0,t=0,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendPitchBendRange(e,t,n)}),this}setPitchBendRange(e=0,t=0,n="all",r={}){return wm.validation&&(console.warn("The setPitchBendRange() method is deprecated. Use sendPitchBendRange() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendPitchBendRange(e,t,r)}sendRpnValue(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendRpnValue(e,t,n)}),this}setRegisteredParameter(e,t=[],n="all",r={}){return wm.validation&&(console.warn("The setRegisteredParameter() method is deprecated. Use sendRpnValue() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnValue(e,t,r)}sendChannelAftertouch(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendChannelAftertouch(e,t)}),this}sendPitchBend(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendPitchBend(e,t)}),this}sendProgramChange(e=0,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendProgramChange(e,t)}),this}sendModulationRange(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendModulationRange(e,t,n)}),this}setModulationRange(e=0,t=0,n="all",r={}){return wm.validation&&(console.warn("The setModulationRange() method is deprecated. Use sendModulationRange() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendModulationRange(e,t,r)}sendMasterTuning(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendMasterTuning(e,t)}),this}setMasterTuning(e,t={},n={}){return wm.validation&&(console.warn("The setMasterTuning() method is deprecated. Use sendMasterTuning() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendMasterTuning(e,n)}sendTuningProgram(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendTuningProgram(e,t)}),this}setTuningProgram(e,t="all",n={}){return wm.validation&&(console.warn("The setTuningProgram() method is deprecated. Use sendTuningProgram() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendTuningProgram(e,n)}sendTuningBank(e=0,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendTuningBank(e,t)}),this}setTuningBank(e,t="all",n={}){return wm.validation&&(console.warn("The setTuningBank() method is deprecated. Use sendTuningBank() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendTuningBank(e,n)}sendChannelMode(e,t=0,n={},r={}){if(wm.validation&&(Array.isArray(n)||Number.isInteger(n)||"all"===n)){const e=n;(n=r).channels=e,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendChannelMode(e,t,n)}),this}sendAllSoundOff(e={}){return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendAllSoundOff(e)}),this}sendAllNotesOff(e={}){return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendAllNotesOff(e)}),this}sendResetAllControllers(e={},t={}){if(wm.validation&&(Array.isArray(e)||Number.isInteger(e)||"all"===e)){const n=e;(e=t).channels=n,"all"===e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==e.channels&&(e.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(e.channels).forEach(t=>{this.channels[t].sendResetAllControllers(e)}),this}sendPolyphonicMode(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendPolyphonicMode(e,t)}),this}sendLocalControl(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendLocalControl(e,t)}),this}sendOmniMode(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendOmniMode(e,t)}),this}sendNrpnValue(e,t,n={}){return null==n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].sendNrpnValue(e,t,n)}),this}setNonRegisteredParameter(e,t=[],n="all",r={}){return wm.validation&&(console.warn("The setNonRegisteredParameter() method is deprecated. Use sendNrpnValue() instead."),r.channels=n,"all"===r.channels&&(r.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendNrpnValue(e,t,r)}sendRpnIncrement(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendRpnIncrement(e,t)}),this}incrementRegisteredParameter(e,t="all",n={}){return wm.validation&&(console.warn("The incrementRegisteredParameter() method is deprecated. Use sendRpnIncrement() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnIncrement(e,n)}sendRpnDecrement(e,t={}){return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendRpnDecrement(e,t)}),this}decrementRegisteredParameter(e,t="all",n={}){return wm.validation&&(console.warn("The decrementRegisteredParameter() method is deprecated. Use sendRpnDecrement() instead."),n.channels=t,"all"===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS)),this.sendRpnDecrement(e,n)}sendNoteOff(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendNoteOff(e,t)}),this}stopNote(e,t){return this.sendNoteOff(e,t)}playNote(e,t={},n={}){if(wm.validation&&(t.rawVelocity&&console.warn("The 'rawVelocity' option is deprecated. Use 'rawAttack' instead."),t.velocity&&console.warn("The 'velocity' option is deprecated. Use 'velocity' instead."),Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].playNote(e,t)}),this}sendNoteOn(e,t={},n={}){if(wm.validation&&(Array.isArray(t)||Number.isInteger(t)||"all"===t)){const e=t;(t=n).channels=e,"all"===t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS)}return null==t.channels&&(t.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(t.channels).forEach(n=>{this.channels[n].sendNoteOn(e,t)}),this}get name(){return this._midiOutput.name}get id(){return this._midiOutput.id}get connection(){return this._midiOutput.connection}get manufacturer(){return this._midiOutput.manufacturer}get state(){return this._midiOutput.state}get type(){return this._midiOutput.type}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}} +/** + * The `Forwarder` class allows the forwarding of MIDI messages to predetermined outputs. When you + * call its [`forward()`](#forward) method, it will send the specified [`Message`](Message) object + * to all the outputs listed in its [`destinations`](#destinations) property. + * + * If specific channels or message types have been defined in the [`channels`](#channels) or + * [`types`](#types) properties, only messages matching the channels/types will be forwarded. + * + * While it can be manually instantiated, you are more likely to come across a `Forwarder` object as + * the return value of the [`Input.addForwarder()`](Input#addForwarder) method. + * + * @license Apache-2.0 + * @since 3.0.0 + */class Forwarder{constructor(e=[],t={}){this.destinations=[],this.types=[...Object.keys(Enumerations.SYSTEM_MESSAGES),...Object.keys(Enumerations.CHANNEL_MESSAGES)],this.channels=Enumerations.MIDI_CHANNEL_NUMBERS,this.suspended=!1,Array.isArray(e)||(e=[e]),t.types&&!Array.isArray(t.types)&&(t.types=[t.types]),t.channels&&!Array.isArray(t.channels)&&(t.channels=[t.channels]),wm.validation&&(e.forEach(e=>{if(!(e instanceof Output))throw new TypeError("Destinations must be of type 'Output'.")}),void 0!==t.types&&t.types.forEach(e=>{if(!Enumerations.SYSTEM_MESSAGES.hasOwnProperty(e)&&!Enumerations.CHANNEL_MESSAGES.hasOwnProperty(e))throw new TypeError("Type must be a valid message type.")}),void 0!==t.channels&&t.channels.forEach(e=>{if(!Enumerations.MIDI_CHANNEL_NUMBERS.includes(e))throw new TypeError("MIDI channel must be between 1 and 16.")})),this.destinations=e,t.types&&(this.types=t.types),t.channels&&(this.channels=t.channels)}forward(e){this.suspended||this.types.includes(e.type)&&(e.channel&&!this.channels.includes(e.channel)||this.destinations.forEach(t=>{(!wm.validation||t instanceof Output)&&t.send(e)}))}} +/** + * The `InputChannel` class represents a single MIDI input channel (1-16) from a single input + * device. This object is derived from the host's MIDI subsystem and should not be instantiated + * directly. + * + * All 16 `InputChannel` objects can be found inside the input's [`channels`](Input#channels) + * property. + * + * @fires InputChannel#midimessage + * @fires InputChannel#unknownmessage + * + * @fires InputChannel#noteoff + * @fires InputChannel#noteon + * @fires InputChannel#keyaftertouch + * @fires InputChannel#programchange + * @fires InputChannel#channelaftertouch + * @fires InputChannel#pitchbend + * + * @fires InputChannel#allnotesoff + * @fires InputChannel#allsoundoff + * @fires InputChannel#localcontrol + * @fires InputChannel#monomode + * @fires InputChannel#omnimode + * @fires InputChannel#resetallcontrollers + * + * @fires InputChannel#event:nrpn + * @fires InputChannel#event:nrpn-dataentrycoarse + * @fires InputChannel#event:nrpn-dataentryfine + * @fires InputChannel#event:nrpn-dataincrement + * @fires InputChannel#event:nrpn-datadecrement + * @fires InputChannel#event:rpn + * @fires InputChannel#event:rpn-dataentrycoarse + * @fires InputChannel#event:rpn-dataentryfine + * @fires InputChannel#event:rpn-dataincrement + * @fires InputChannel#event:rpn-datadecrement + * + * @fires InputChannel#controlchange + * @fires InputChannel#event:controlchange-controllerxxx + * @fires InputChannel#event:controlchange-bankselectcoarse + * @fires InputChannel#event:controlchange-modulationwheelcoarse + * @fires InputChannel#event:controlchange-breathcontrollercoarse + * @fires InputChannel#event:controlchange-footcontrollercoarse + * @fires InputChannel#event:controlchange-portamentotimecoarse + * @fires InputChannel#event:controlchange-dataentrycoarse + * @fires InputChannel#event:controlchange-volumecoarse + * @fires InputChannel#event:controlchange-balancecoarse + * @fires InputChannel#event:controlchange-pancoarse + * @fires InputChannel#event:controlchange-expressioncoarse + * @fires InputChannel#event:controlchange-effectcontrol1coarse + * @fires InputChannel#event:controlchange-effectcontrol2coarse + * @fires InputChannel#event:controlchange-generalpurposecontroller1 + * @fires InputChannel#event:controlchange-generalpurposecontroller2 + * @fires InputChannel#event:controlchange-generalpurposecontroller3 + * @fires InputChannel#event:controlchange-generalpurposecontroller4 + * @fires InputChannel#event:controlchange-bankselectfine + * @fires InputChannel#event:controlchange-modulationwheelfine + * @fires InputChannel#event:controlchange-breathcontrollerfine + * @fires InputChannel#event:controlchange-footcontrollerfine + * @fires InputChannel#event:controlchange-portamentotimefine + * @fires InputChannel#event:controlchange-dataentryfine + * @fires InputChannel#event:controlchange-channelvolumefine + * @fires InputChannel#event:controlchange-balancefine + * @fires InputChannel#event:controlchange-panfine + * @fires InputChannel#event:controlchange-expressionfine + * @fires InputChannel#event:controlchange-effectcontrol1fine + * @fires InputChannel#event:controlchange-effectcontrol2fine + * @fires InputChannel#event:controlchange-damperpedal + * @fires InputChannel#event:controlchange-portamento + * @fires InputChannel#event:controlchange-sostenuto + * @fires InputChannel#event:controlchange-softpedal + * @fires InputChannel#event:controlchange-legatopedal + * @fires InputChannel#event:controlchange-hold2 + * @fires InputChannel#event:controlchange-soundvariation + * @fires InputChannel#event:controlchange-resonance + * @fires InputChannel#event:controlchange-releasetime + * @fires InputChannel#event:controlchange-attacktime + * @fires InputChannel#event:controlchange-brightness + * @fires InputChannel#event:controlchange-decaytime + * @fires InputChannel#event:controlchange-vibratorate + * @fires InputChannel#event:controlchange-vibratodepth + * @fires InputChannel#event:controlchange-vibratodelay + * @fires InputChannel#event:controlchange-generalpurposecontroller5 + * @fires InputChannel#event:controlchange-generalpurposecontroller6 + * @fires InputChannel#event:controlchange-generalpurposecontroller7 + * @fires InputChannel#event:controlchange-generalpurposecontroller8 + * @fires InputChannel#event:controlchange-portamentocontrol + * @fires InputChannel#event:controlchange-highresolutionvelocityprefix + * @fires InputChannel#event:controlchange-effect1depth + * @fires InputChannel#event:controlchange-effect2depth + * @fires InputChannel#event:controlchange-effect3depth + * @fires InputChannel#event:controlchange-effect4depth + * @fires InputChannel#event:controlchange-effect5depth + * @fires InputChannel#event:controlchange-dataincrement + * @fires InputChannel#event:controlchange-datadecrement + * @fires InputChannel#event:controlchange-nonregisteredparameterfine + * @fires InputChannel#event:controlchange-nonregisteredparametercoarse + * @fires InputChannel#event:controlchange-registeredparameterfine + * @fires InputChannel#event:controlchange-registeredparametercoarse + * @fires InputChannel#event:controlchange-allsoundoff + * @fires InputChannel#event:controlchange-resetallcontrollers + * @fires InputChannel#event:controlchange-localcontrol + * @fires InputChannel#event:controlchange-allnotesoff + * @fires InputChannel#event:controlchange-omnimodeoff + * @fires InputChannel#event:controlchange-omnimodeon + * @fires InputChannel#event:controlchange-monomodeon + * @fires InputChannel#event:controlchange-polymodeon + * @fires InputChannel#event: + * + * @extends EventEmitter + * @license Apache-2.0 + * @since 3.0.0 + */class InputChannel extends EventEmitter{constructor(e,t){super(),this._input=e,this._number=t,this._octaveOffset=0,this._nrpnBuffer=[],this._rpnBuffer=[],this.parameterNumberEventsEnabled=!0,this.notesState=new Array(128).fill(!1)}destroy(){this._input=null,this._number=null,this._octaveOffset=0,this._nrpnBuffer=[],this.notesState=new Array(128).fill(!1),this.parameterNumberEventsEnabled=!1,this.removeListener()}_processMidiMessageEvent(e){const t=Object.assign({},e);t.port=this.input,t.target=this,t.type="midimessage",this.emit(t.type,t),this._parseEventForStandardMessages(t)}_parseEventForStandardMessages(e){const t=Object.assign({},e);t.type=t.message.type||"unknownmessage";const n=e.message.dataBytes[0],r=e.message.dataBytes[1];if("noteoff"===t.type||"noteon"===t.type&&0===r)this.notesState[n]=!1,t.type="noteoff",t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset),{rawAttack:0,rawRelease:r}),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.velocity=t.note.release,t.rawVelocity=t.note.rawRelease;else if("noteon"===t.type)this.notesState[n]=!0,t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset),{rawAttack:r}),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.velocity=t.note.attack,t.rawVelocity=t.note.rawAttack;else if("keyaftertouch"===t.type)t.note=new Note(Utilities.offsetNumber(n,this.octaveOffset+this.input.octaveOffset+wm.octaveOffset)),t.value=Utilities.from7bitToFloat(r),t.rawValue=r,t.identifier=t.note.identifier,t.key=t.note.number,t.rawKey=n;else if("controlchange"===t.type){t.controller={number:n,name:Enumerations.CONTROL_CHANGE_MESSAGES[n].name,description:Enumerations.CONTROL_CHANGE_MESSAGES[n].description,position:Enumerations.CONTROL_CHANGE_MESSAGES[n].position},t.subtype=t.controller.name||"controller"+n,t.value=Utilities.from7bitToFloat(r),t.rawValue=r;const e=Object.assign({},t);e.type=`${t.type}-controller${n}`,delete e.subtype,this.emit(e.type,e);const i=Object.assign({},t);i.type=t.type+"-"+Enumerations.CONTROL_CHANGE_MESSAGES[n].name,delete i.subtype,0!==i.type.indexOf("controller")&&this.emit(i.type,i),t.message.dataBytes[0]>=120&&this._parseChannelModeMessage(t),this.parameterNumberEventsEnabled&&this._isRpnOrNrpnController(t.message.dataBytes[0])&&this._parseEventForParameterNumber(t)}else"programchange"===t.type?(t.value=n,t.rawValue=t.value):"channelaftertouch"===t.type?(t.value=Utilities.from7bitToFloat(n),t.rawValue=n):"pitchbend"===t.type?(t.value=((r<<7)+n-8192)/8192,t.rawValue=(r<<7)+n):t.type="unknownmessage";this.emit(t.type,t)}_parseChannelModeMessage(e){const t=Object.assign({},e);t.type=t.controller.name,"localcontrol"===t.type&&(t.value=127===t.message.data[2],t.rawValue=t.message.data[2]),"omnimodeon"===t.type?(t.type="omnimode",t.value=!0,t.rawValue=t.message.data[2]):"omnimodeoff"===t.type&&(t.type="omnimode",t.value=!1,t.rawValue=t.message.data[2]),"monomodeon"===t.type?(t.type="monomode",t.value=!0,t.rawValue=t.message.data[2]):"polymodeon"===t.type&&(t.type="monomode",t.value=!1,t.rawValue=t.message.data[2]),this.emit(t.type,t)}_parseEventForParameterNumber(e){const t=e.message.dataBytes[0],n=e.message.dataBytes[1];99===t||101===t?(this._nrpnBuffer=[],this._rpnBuffer=[],99===t?this._nrpnBuffer=[e.message]:127!==n&&(this._rpnBuffer=[e.message])):98===t||100===t?98===t?(this._rpnBuffer=[],1===this._nrpnBuffer.length?this._nrpnBuffer.push(e.message):this._nrpnBuffer=[]):(this._nrpnBuffer=[],1===this._rpnBuffer.length&&127!==n?this._rpnBuffer.push(e.message):this._rpnBuffer=[]):6!==t&&38!==t&&96!==t&&97!==t||(2===this._rpnBuffer.length?this._dispatchParameterNumberEvent("rpn",this._rpnBuffer[0].dataBytes[1],this._rpnBuffer[1].dataBytes[1],e):2===this._nrpnBuffer.length?this._dispatchParameterNumberEvent("nrpn",this._nrpnBuffer[0].dataBytes[1],this._nrpnBuffer[1].dataBytes[1],e):(this._nrpnBuffer=[],this._rpnBuffer=[]))}_isRpnOrNrpnController(e){return 6===e||38===e||96===e||97===e||98===e||99===e||100===e||101===e}_dispatchParameterNumberEvent(e,t,n,r){e="nrpn"===e?"nrpn":"rpn";const i={target:r.target,timestamp:r.timestamp,message:r.message,parameterMsb:t,parameterLsb:n,value:Utilities.from7bitToFloat(r.message.dataBytes[1]),rawValue:r.message.dataBytes[1]};i.parameter="rpn"===e?Object.keys(Enumerations.REGISTERED_PARAMETERS).find(e=>Enumerations.REGISTERED_PARAMETERS[e][0]===t&&Enumerations.REGISTERED_PARAMETERS[e][1]===n):(t<<7)+n;const s=Enumerations.CONTROL_CHANGE_MESSAGES[r.message.dataBytes[0]].name;i.type=`${e}-${s}`,this.emit(i.type,i);const a=Object.assign({},i);"nrpn-dataincrement"===a.type?a.type="nrpn-databuttonincrement":"nrpn-datadecrement"===a.type?a.type="nrpn-databuttondecrement":"rpn-dataincrement"===a.type?a.type="rpn-databuttonincrement":"rpn-datadecrement"===a.type&&(a.type="rpn-databuttondecrement"),this.emit(a.type,a),i.type=e,i.subtype=s,this.emit(i.type,i)}getChannelModeByNumber(e){return wm.validation&&(console.warn("The 'getChannelModeByNumber()' method has been moved to the 'Utilities' class."),e=Math.floor(e)),Utilities.getChannelModeByNumber(e)}getCcNameByNumber(e){if(wm.validation&&(console.warn("The 'getCcNameByNumber()' method has been moved to the 'Utilities' class."),!((e=parseInt(e))>=0&&e<=127)))throw new RangeError("Invalid control change number.");return Utilities.getCcNameByNumber(e)}getNoteState(e){e instanceof Note&&(e=e.identifier);const t=Utilities.guessNoteNumber(e,wm.octaveOffset+this.input.octaveOffset+this.octaveOffset);return this.notesState[t]}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get input(){return this._input}get number(){return this._number}get nrpnEventsEnabled(){return this.parameterNumberEventsEnabled}set nrpnEventsEnabled(e){this.validation&&(e=!!e),this.parameterNumberEventsEnabled=e}} +/** + * The `Message` class represents a single MIDI message. It has several properties that make it + * easy to make sense of the binary data it contains. + * + * @license Apache-2.0 + * @since 3.0.0 + */class Message{constructor(e){this.rawData=e,this.data=Array.from(this.rawData),this.statusByte=this.rawData[0],this.rawDataBytes=this.rawData.slice(1),this.dataBytes=this.data.slice(1),this.isChannelMessage=!1,this.isSystemMessage=!1,this.command=void 0,this.channel=void 0,this.manufacturerId=void 0,this.type=void 0,this.statusByte<240?(this.isChannelMessage=!0,this.command=this.statusByte>>4,this.channel=1+(15&this.statusByte)):(this.isSystemMessage=!0,this.command=this.statusByte),this.isChannelMessage?this.type=Utilities.getPropertyByValue(Enumerations.CHANNEL_MESSAGES,this.command):this.isSystemMessage&&(this.type=Utilities.getPropertyByValue(Enumerations.SYSTEM_MESSAGES,this.command)),this.statusByte===Enumerations.SYSTEM_MESSAGES.sysex&&(0===this.dataBytes[0]?(this.manufacturerId=this.dataBytes.slice(0,3),this.dataBytes=this.dataBytes.slice(3,this.rawDataBytes.length-1),this.rawDataBytes=this.rawDataBytes.slice(3,this.rawDataBytes.length-1)):(this.manufacturerId=[this.dataBytes[0]],this.dataBytes=this.dataBytes.slice(1,this.dataBytes.length-1),this.rawDataBytes=this.rawDataBytes.slice(1,this.rawDataBytes.length-1)))}} +/** + * The `Input` class represents a single MIDI input port. This object is automatically instantiated + * by the library according to the host's MIDI subsystem and does not need to be directly + * instantiated. Instead, you can access all `Input` objects by referring to the + * [`WebMidi.inputs`](WebMidi#inputs) array. You can also retrieve inputs by using methods such as + * [`WebMidi.getInputByName()`](WebMidi#getInputByName) and + * [`WebMidi.getInputById()`](WebMidi#getInputById). + * + * Note that a single MIDI device may expose several inputs and/or outputs. + * + * **Important**: the `Input` class does not directly fire channel-specific MIDI messages + * (such as [`noteon`](InputChannel#event:noteon) or + * [`controlchange`](InputChannel#event:controlchange), etc.). The [`InputChannel`](InputChannel) + * object does that. However, you can still use the + * [`Input.addListener()`](#addListener) method to listen to channel-specific events on multiple + * [`InputChannel`](InputChannel) objects at once. + * + * @fires Input#opened + * @fires Input#disconnected + * @fires Input#closed + * @fires Input#midimessage + * + * @fires Input#sysex + * @fires Input#timecode + * @fires Input#songposition + * @fires Input#songselect + * @fires Input#tunerequest + * @fires Input#clock + * @fires Input#start + * @fires Input#continue + * @fires Input#stop + * @fires Input#activesensing + * @fires Input#reset + * + * @fires Input#unknownmidimessage + * + * @extends EventEmitter + * @license Apache-2.0 + */class Input extends EventEmitter{constructor(e){super(),this._midiInput=e,this._octaveOffset=0,this.channels=[];for(let e=1;e<=16;e++)this.channels[e]=new InputChannel(this,e);this._forwarders=[],this._midiInput.onstatechange=this._onStateChange.bind(this),this._midiInput.onmidimessage=this._onMidiMessage.bind(this)}async destroy(){this.removeListener(),this.channels.forEach(e=>e.destroy()),this.channels=[],this._forwarders=[],this._midiInput&&(this._midiInput.onstatechange=null,this._midiInput.onmidimessage=null),await this.close(),this._midiInput=null}_onStateChange(e){let t={timestamp:wm.time,target:this,port:this};"open"===e.port.connection?(t.type="opened",this.emit("opened",t)):"closed"===e.port.connection&&"connected"===e.port.state?(t.type="closed",this.emit("closed",t)):"closed"===e.port.connection&&"disconnected"===e.port.state?(t.type="disconnected",t.port={connection:e.port.connection,id:e.port.id,manufacturer:e.port.manufacturer,name:e.port.name,state:e.port.state,type:e.port.type},this.emit("disconnected",t)):"pending"===e.port.connection&&"disconnected"===e.port.state||console.warn("This statechange event was not caught: ",e.port.connection,e.port.state)}_onMidiMessage(e){const t=new Message(e.data),n={port:this,target:this,message:t,timestamp:e.timeStamp,type:"midimessage",data:t.data,rawData:t.data,statusByte:t.data[0],dataBytes:t.dataBytes};this.emit("midimessage",n),t.isSystemMessage?this._parseEvent(n):t.isChannelMessage&&this.channels[t.channel]._processMidiMessageEvent(n),this._forwarders.forEach(e=>e.forward(t))}_parseEvent(e){const t=Object.assign({},e);t.type=t.message.type||"unknownmidimessage","songselect"===t.type&&(t.song=e.data[1]+1,t.value=e.data[1],t.rawValue=t.value),this.emit(t.type,t)}async open(){try{await this._midiInput.open()}catch(e){return Promise.reject(e)}return Promise.resolve(this)}async close(){if(!this._midiInput)return Promise.resolve(this);try{await this._midiInput.close()}catch(e){return Promise.reject(e)}return Promise.resolve(this)}getChannelModeByNumber(){wm.validation&&console.warn("The 'getChannelModeByNumber()' method has been moved to the 'Utilities' class.")}addListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=null!=t?[].concat(t):void 0;t=n,n={channels:e}}if(Enumerations.CHANNEL_EVENTS.includes(e)){void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS);let r=[];return Utilities.sanitizeChannels(n.channels).forEach(i=>{r.push(this.channels[i].addListener(e,t,n))}),r}return super.addListener(e,t,n)}addOneTimeListener(e,t,n={}){return n.remaining=1,this.addListener(e,t,n)}on(e,t,n,r){return this.addListener(e,t,n,r)}hasListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=[].concat(t);t=n,n={channels:e}}return Enumerations.CHANNEL_EVENTS.includes(e)?(void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),Utilities.sanitizeChannels(n.channels).every(n=>this.channels[n].hasListener(e,t))):super.hasListener(e,t)}removeListener(e,t,n={}){if(wm.validation&&"function"==typeof n){let e=[].concat(t);t=n,n={channels:e}}if(void 0===n.channels&&(n.channels=Enumerations.MIDI_CHANNEL_NUMBERS),null==e)return Utilities.sanitizeChannels(n.channels).forEach(e=>{this.channels[e]&&this.channels[e].removeListener()}),super.removeListener();Enumerations.CHANNEL_EVENTS.includes(e)?Utilities.sanitizeChannels(n.channels).forEach(r=>{this.channels[r].removeListener(e,t,n)}):super.removeListener(e,t,n)}addForwarder(e,t={}){let n;return n=e instanceof Forwarder?e:new Forwarder(e,t),this._forwarders.push(n),n}removeForwarder(e){this._forwarders=this._forwarders.filter(t=>t!==e)}hasForwarder(e){return this._forwarders.includes(e)}get name(){return this._midiInput.name}get id(){return this._midiInput.id}get connection(){return this._midiInput.connection}get manufacturer(){return this._midiInput.manufacturer}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get state(){return this._midiInput.state}get type(){return this._midiInput.type}get nrpnEventsEnabled(){return wm.validation&&console.warn("The 'nrpnEventsEnabled' property has been moved to the 'InputChannel' class."),!1}}if(Utilities.isNode){try{window.navigator}catch(err){let jzz;eval('jzz = require("jzz")'),global.navigator||(global.navigator={}),Object.assign(global.navigator,jzz)}try{performance}catch(err){let performance;eval('performance = require("perf_hooks").performance'),global.performance=performance}} +/** + * The `WebMidi` object makes it easier to work with the low-level Web MIDI API. Basically, it + * simplifies sending outgoing MIDI messages and reacting to incoming MIDI messages. + * + * When using the WebMidi.js library, you should know that the `WebMidi` class has already been + * instantiated. You cannot instantiate it yourself. If you use the **IIFE** version, you should + * simply use the global object called `WebMidi`. If you use the **CJS** (CommonJS) or **ESM** (ES6 + * module) version, you get an already-instantiated object when you import the module. + * + * @fires WebMidi#connected + * @fires WebMidi#disabled + * @fires WebMidi#disconnected + * @fires WebMidi#enabled + * @fires WebMidi#error + * @fires WebMidi#midiaccessgranted + * @fires WebMidi#portschanged + * + * @extends EventEmitter + * @license Apache-2.0 + */class WebMidi extends EventEmitter{constructor(){super(),this.defaults={note:{attack:Utilities.from7bitToFloat(64),release:Utilities.from7bitToFloat(64),duration:1/0}},this.interface=null,this.validation=!0,this._inputs=[],this._disconnectedInputs=[],this._outputs=[],this._disconnectedOutputs=[],this._stateChangeQueue=[],this._octaveOffset=0}async enable(e={},t=!1){if(this.validation=!1!==e.validation,this.validation&&("function"==typeof e&&(e={callback:e,sysex:t}),t&&(e.sysex=!0)),this.enabled)return"function"==typeof e.callback&&e.callback(),Promise.resolve();const n={timestamp:this.time,target:this,type:"error",error:void 0},r={timestamp:this.time,target:this,type:"midiaccessgranted"},i={timestamp:this.time,target:this,type:"enabled"};try{"function"==typeof e.requestMIDIAccessFunction?this.interface=await e.requestMIDIAccessFunction({sysex:e.sysex,software:e.software}):this.interface=await navigator.requestMIDIAccess({sysex:e.sysex,software:e.software})}catch(t){return n.error=t,this.emit("error",n),"function"==typeof e.callback&&e.callback(t),Promise.reject(t)}this.emit("midiaccessgranted",r),this.interface.onstatechange=this._onInterfaceStateChange.bind(this);try{await this._updateInputsAndOutputs()}catch(t){return n.error=t,this.emit("error",n),"function"==typeof e.callback&&e.callback(t),Promise.reject(t)}return this.emit("enabled",i),"function"==typeof e.callback&&e.callback(),Promise.resolve(this)}async disable(){return this.interface&&(this.interface.onstatechange=void 0),this._destroyInputsAndOutputs().then(()=>{navigator&&"function"==typeof navigator.close&&navigator.close(),this.interface=null;let e={timestamp:this.time,target:this,type:"disabled"};this.emit("disabled",e),this.removeListener()})}getInputById(e,t={disconnected:!1}){if(this.validation){if(!this.enabled)throw new Error("WebMidi is not enabled.");if(!e)return}if(t.disconnected){for(let t=0;t=0&&e<=127&&Utilities.getNoteDetails(Utilities.offsetNumber(e,this.octaveOffset)).octave}sanitizeChannels(e){return this.validation&&console.warn("The sanitizeChannels() method has been moved to the utilities class."),Utilities.sanitizeChannels(e)}toMIDIChannels(e){return this.validation&&console.warn("The toMIDIChannels() method has been deprecated. Use Utilities.sanitizeChannels() instead."),Utilities.sanitizeChannels(e)}guessNoteNumber(e){return this.validation&&console.warn("The guessNoteNumber() method has been deprecated. Use Utilities.guessNoteNumber() instead."),Utilities.guessNoteNumber(e,this.octaveOffset)}getValidNoteArray(e,t={}){return this.validation&&console.warn("The getValidNoteArray() method has been moved to the Utilities.buildNoteArray()"),Utilities.buildNoteArray(e,t)}convertToTimestamp(e){return this.validation&&console.warn("The convertToTimestamp() method has been moved to Utilities.toTimestamp()."),Utilities.toTimestamp(e)}async _destroyInputsAndOutputs(){let e=[];return this.inputs.forEach(t=>e.push(t.destroy())),this.outputs.forEach(t=>e.push(t.destroy())),Promise.all(e).then(()=>{this._inputs=[],this._outputs=[]})}_onInterfaceStateChange(e){this._updateInputsAndOutputs();let t={timestamp:e.timeStamp,type:e.port.state,target:this};if("connected"===e.port.state&&"open"===e.port.connection){"output"===e.port.type?t.port=this.getOutputById(e.port.id):"input"===e.port.type&&(t.port=this.getInputById(e.port.id)),this.emit(e.port.state,t);const n=Object.assign({},t);n.type="portschanged",this.emit(n.type,n)}else if("disconnected"===e.port.state&&"pending"===e.port.connection){"input"===e.port.type?t.port=this.getInputById(e.port.id,{disconnected:!0}):"output"===e.port.type&&(t.port=this.getOutputById(e.port.id,{disconnected:!0})),this.emit(e.port.state,t);const n=Object.assign({},t);n.type="portschanged",this.emit(n.type,n)}}async _updateInputsAndOutputs(){return Promise.all([this._updateInputs(),this._updateOutputs()])}async _updateInputs(){if(!this.interface)return;for(let e=this._inputs.length-1;e>=0;e--){const t=this._inputs[e];Array.from(this.interface.inputs.values()).find(e=>e===t._midiInput)||(this._disconnectedInputs.push(t),this._inputs.splice(e,1))}let e=[];return this.interface.inputs.forEach(t=>{if(!this._inputs.find(e=>e._midiInput===t)){let n=this._disconnectedInputs.find(e=>e._midiInput===t);n||(n=new Input(t)),this._inputs.push(n),e.push(n.open())}}),Promise.all(e)}async _updateOutputs(){if(!this.interface)return;for(let e=this._outputs.length-1;e>=0;e--){const t=this._outputs[e];Array.from(this.interface.outputs.values()).find(e=>e===t._midiOutput)||(this._disconnectedOutputs.push(t),this._outputs.splice(e,1))}let e=[];return this.interface.outputs.forEach(t=>{if(!this._outputs.find(e=>e._midiOutput===t)){let n=this._disconnectedOutputs.find(e=>e._midiOutput===t);n||(n=new Output(t)),this._outputs.push(n),e.push(n.open())}}),Promise.all(e)}get enabled(){return null!==this.interface}get inputs(){return this._inputs}get isNode(){return this.validation&&console.warn("WebMidi.isNode has been deprecated. Use Utilities.isNode instead."),Utilities.isNode}get isBrowser(){return this.validation&&console.warn("WebMidi.isBrowser has been deprecated. Use Utilities.isBrowser instead."),Utilities.isBrowser}get octaveOffset(){return this._octaveOffset}set octaveOffset(e){if(this.validation&&(e=parseInt(e),isNaN(e)))throw new TypeError("The 'octaveOffset' property must be an integer.");this._octaveOffset=e}get outputs(){return this._outputs}get supported(){return"undefined"!=typeof navigator&&!!navigator.requestMIDIAccess}get sysexEnabled(){return!(!this.interface||!this.interface.sysexEnabled)}get time(){return performance.now()}get version(){return"3.1.12"}get flavour(){return"cjs"}get CHANNEL_EVENTS(){return this.validation&&console.warn("The CHANNEL_EVENTS enum has been moved to Enumerations.CHANNEL_EVENTS."),Enumerations.CHANNEL_EVENTS}get MIDI_SYSTEM_MESSAGES(){return this.validation&&console.warn("The MIDI_SYSTEM_MESSAGES enum has been moved to Enumerations.SYSTEM_MESSAGES."),Enumerations.SYSTEM_MESSAGES}get MIDI_CHANNEL_MODE_MESSAGES(){return this.validation&&console.warn("The MIDI_CHANNEL_MODE_MESSAGES enum has been moved to Enumerations.CHANNEL_MODE_MESSAGES."),Enumerations.CHANNEL_MODE_MESSAGES}get MIDI_CONTROL_CHANGE_MESSAGES(){return this.validation&&console.warn("The MIDI_CONTROL_CHANGE_MESSAGES enum has been replaced by the Enumerations.CONTROL_CHANGE_MESSAGES array."),Enumerations.MIDI_CONTROL_CHANGE_MESSAGES}get MIDI_REGISTERED_PARAMETER(){return this.validation&&console.warn("The MIDI_REGISTERED_PARAMETER enum has been moved to Enumerations.REGISTERED_PARAMETERS."),Enumerations.REGISTERED_PARAMETERS}get NOTES(){return this.validation&&console.warn("The NOTES enum has been deprecated."),["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]}}const wm=new WebMidi;wm.constructor=null,exports.Enumerations=Enumerations,exports.Forwarder=Forwarder,exports.Input=Input,exports.InputChannel=InputChannel,exports.Message=Message,exports.Note=Note,exports.Output=Output,exports.OutputChannel=OutputChannel,exports.Utilities=Utilities,exports.WebMidi=wm; +//# sourceMappingURL=webmidi.cjs.min.js.map + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(631), __webpack_require__(259))) /***/ }) /******/ ]); -- cgit v1.2.3-70-g09d2