/* Merge shapes of queries which have completed inputs and build their promises.
978155
function preCacheQueries(queries) {
  var groupBy = {};
  _.each(queries, function (query) {
    if (!query.queryKey) {
      return;
    }
    var hasAllValues = _.reduce(_.values(query.queryParams), function (acc, val) {
      return acc && (val !== null);
    }, true);
    if (hasAllValues) {
      var cacheKey = _executionCache.getKey(query);
      groupBy[cacheKey] = groupBy[cacheKey] || [];
      groupBy[cacheKey].push(query);
    }
  });

  _.each(groupBy, function (groupedQueries, key) {
    var aggregateShape = _.reduce(_.map(groupedQueries, 'shape'), _.assign, {});
    var query = _.cloneDeep(groupedQueries[0]);
    query.shape = aggregateShape;
    _executionCache.execute(query);
  });
}
1110458
function _merge (getKeys, a, b) {
    return reduce([a, b], function (result, source) {
        forEach(getKeys(source), function (key) {
            result[key] = source[key];
        });

        return result;
    }, {});
}
25563
private QueryResultImpl combineResults(QueryResultImpl a, QueryResultImpl b, boolean distinct) {
        QueryResultImpl result = new QueryResultImpl(a.getQuery());

        for (QueryBindingImpl bindingA : a.getBindings()) {
            for (QueryBindingImpl bindingB : b.getBindings()) {
                QueryBindingImpl binding = new QueryBindingImpl();
                binding.set(bindingA);
                binding.set(bindingB);
                result.add(binding);
            }
        }

        if (distinct) {
            return eliminateDuplicates(result);
        }
        return result;
    }
1252583
function promisedConcat(promises, unknown) {
    return promises.then(function(values) {
      return Promise.resolve(unknown).then(function(value) {
        return values.concat([ value ]);
      });
    });
  }
1326092
function Polyfills() {

    Promise.create = function () {
        let resolve, reject;
        const promise = new Promise(function (res, rej) {
            resolve = res;
            reject = rej;
        });
        promise.resolve = resolve;
        promise.reject = reject;
        return promise;
    };

    Math.sign = function (x) {
        x = +x;
        if (x === 0 || isNaN(x)) return Number(x);
        return x > 0 ? 1 : -1;
    };

    Math.degrees = function (radians) {
        return radians * (180 / Math.PI);
    };

    Math.radians = function (degrees) {
        return degrees * (Math.PI / 180);
    };

    Math.clamp = function (value, min, max) {
        return Math.max(min, Math.min(max, value));
    };

    Math.range = function (value, oldMin, oldMax, newMin, newMax, isClamp) {
        const newValue = (value - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin;
        if (isClamp) return Math.clamp(newValue, newMin, newMax);
        return newValue;
    };

    Math.mix = function (a, b, alpha) {
        return a * (1 - alpha) + b * alpha;
    };

    Math.step = function (edge, value) {
        return value < edge ? 0 : 1;
    };

    Math.smoothStep = function (min, max, value) {
        const x = Math.max(0, Math.min(1, (value - min) / (max - min)));
        return x * x * (3 - 2 * x);
    };

    Math.fract = function (value) {
        return value - Math.floor(value);
    };

    Math.mod = function (value, n) {
        return (value % n + n) % n;
    };

    Array.prototype.shuffle = function () {
        let i = this.length,
            temp, r;
        while (i !== 0) {
            r = Math.floor(Math.random() * i);
            i -= 1;
            temp = this[i];
            this[i] = this[r];
            this[r] = temp;
        }
        return this;
    };

    Array.prototype.random = function (range) {
        let value = Math.floor(Math.random() * this.length);
        if (range && !this.randomStore) this.randomStore = [];
        if (!this.randomStore) return this[value];
        if (range > this.length) range = this.length;
        if (range > 1) {
            while (~this.randomStore.indexOf(value)) if (++value > this.length - 1) value = 0;
            this.randomStore.push(value);
            if (this.randomStore.length >= range) this.randomStore.shift();
        }
        return this[value];
    };

    Array.prototype.remove = function (element) {
        const index = this.indexOf(element);
        if (~index) return this.splice(index, 1);
    };

    Array.prototype.last = function () {
        return this[this.length - 1];
    };

    String.prototype.includes = function (str) {
        if (!Array.isArray(str)) return ~this.indexOf(str);
        for (let i = 0; i < str.length; i++) if (~this.indexOf(str[i])) return true;
        return false;
    };

    String.prototype.clip = function (num, end) {
        return this.length > num ? this.slice(0, num) + end : this;
    };

    String.prototype.capitalize = function () {
        return this.charAt(0).toUpperCase() + this.slice(1);
    };

    String.prototype.replaceAll = function (find, replace) {
        return this.split(find).join(replace);
    };

    Date.prototype.addDays = function (days) {
        const date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    };

    window.get = function (url, options = {}) {
        const promise = Promise.create();
        options.method = 'GET';
        window.fetch(url, options).then(handleResponse).catch(promise.reject);

        function handleResponse(e) {
            if (!e.ok) return promise.reject(e);
            e.text().then(function (text) {
                if (text.charAt(0).includes(['[', '{'])) {
                    try {
                        promise.resolve(JSON.parse(text));
                    } catch (err) {
                        promise.resolve(text);
                    }
                } else {
                    promise.resolve(text);
                }
            });
        }
        return promise;
    };

    window.post = function (url, body, options = {}) {
        const promise = Promise.create();
        options.method = 'POST';
        options.body = JSON.stringify(body);
        window.fetch(url, options).then(handleResponse).catch(promise.reject);

        function handleResponse(e) {
            if (!e.ok) return promise.reject(e);
            e.text().then(function (text) {
                if (text.charAt(0).includes(['[', '{'])) {
                    try {
                        promise.resolve(JSON.parse(text));
                    } catch (err) {
                        promise.resolve(text);
                    }
                } else {
                    promise.resolve(text);
                }
            });
        }
        return promise;
    };

    window.defer = function (callback) {
        if (!callback) {
            const promise = Promise.create();
            TweenLite.delayedCall(0.001, promise.resolve);
            return promise;
        }
        TweenLite.delayedCall(0.001, callback);
    };

    window.tween = function (object, props, time, ease, delay, complete, update) {
        if (typeof delay !== 'number') {
            update = complete;
            complete = delay;
            delay = 0;
        }
        const promise = Promise.create();
        if (complete) promise.then(complete);
        complete = promise.resolve;
        const CustomEase = window.CustomEase;
        props.ease = typeof ease === 'object' ? ease : (CustomEase && CustomEase.get(ease)) || Interpolation.get(ease);
        if (props.spring || props.damping) {
            props.ease = props.ease.config(props.spring || 1, props.damping || 0.3);
            delete props.spring;
            delete props.damping;
        }
        props.delay = delay * 0.001;
        props.onComplete = complete;
        props.onUpdate = update;
        TweenLite.to(object, time * 0.001, props);
        return promise;
    };

    window.clearTween = function (object) {
        TweenLite.killTweensOf(object);
    };

    if (!window.Config) window.Config = {};
    if (!window.Global) window.Global = {};
}
1058185
function onDataFetch(query, resolve) {
    let output = [];

    query.forEach(function(query) {
        let filteredItems = data.filter(function(obj) {
            return obj.parent === query.parent;
        });

        output.push({
            parent: query.parent,
            items: filteredItems.splice(query.offset, query.limit)
        });

    });

    resolve(JSON.parse(JSON.stringify(output)));
}
1304075
function mergeObjects(params, addition) {
        for (var i in addition)
            if (i && addition.hasOwnProperty(i))
                params[i] = mergeParams(params[i], addition[i]);

        return params;
    }
124653
function(req){
    var params = req.params.all();
    _.merge(params, req.headers);
    return _.merge(params, req.query);
  }
614647
function resultRaw (results) {
    // throw error if results required and not retrieved
    if (this.args.required && !results.length) {
        // throw error
        throw this.error('no records found')
    }
    // if only ids were selected the return result object to fetch records
    if (this.select.isSelectOnlyIds) {
        // build result object
        var result = new ImmutableCoreModelResult({
            query: this,
            results: results,
        })
        // return result or all records if specified
        return this.args.all ? result.all() : result
    }
    // otherwise return ImmutableCoreModelInstance record(s)
    else {
        // query is for a single record
        if (this.args.limit === 1) {
            // return new instance or undefined
            return results.length
                ? this.newInstance(results[0])
                : undefined
        }
        // query is for multiple records
        else {
            return _.map(results, result => this.newInstance(result))
        }
    }
}
232090
function promisify() {
    var promiseLike = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

    if (promiseLike instanceof _es6Promise.Promise) {
        return promiseLike;
    }

    if (typeof promiseLike === "function") {
        return promisify(promiseLike());
    }

    return new _es6Promise.Promise(function (resolve, reject) {
        promiseLike === false ? reject() : resolve(promiseLike);
    });
}
628668
function combineChangesets (changesets) {
  const actions = changesets.map((changeset) => changeset.apply)

  const combinedAction = function () {
    const args = arguments

    return actions.reduce((promise, action) => (
      promise.then(() => action.apply(null, args))
    ), Promise.resolve())
  }

  return createChangeset(combinedAction)
}
1336713
function transform(input, process = () => undefined, finish = () => undefined) {
  if (isStream(input)) {
    return transformRaw(input, {
      async transform(value, controller) {
        try {
          const result = await process(value);
          if (result !== undefined) controller.enqueue(result);
        } catch(e) {
          controller.error(e);
        }
      },
      async flush(controller) {
        try {
          const result = await finish();
          if (result !== undefined) controller.enqueue(result);
        } catch(e) {
          controller.error(e);
        }
      }
    });
  }
  const result1 = process(input);
  const result2 = finish();
  if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
  return result1 !== undefined ? result1 : result2;
}
1326555
function query(connection, ...params){
    return new Promise(function(resolve, reject){
        // execute query
        connection.query(...params, function(err, result, fields){
            if (err){
                reject(err);
            }else{
                resolve([result, fields]);
            }
        });
    });
}
409014
function combineStatsAndIndexes(done, results) {
  var indexes = results.getIndexes;
  var stats = results.getIndexStats;
  var sizes = results.getIndexSizes;
  _.each(indexes, function(idx, i) {
    _.assign(indexes[i], stats[idx.name]);
    _.assign(indexes[i], sizes[idx.name]);
  });
  done(null, indexes);
}
281275
function(input, callback, context, remoteData)
  {
    var db = this;
    var promise = new Promise();

    promise.success( callback, context || db );

    function checkModel()
    {
      var result = db.parseModel( input, remoteData );

      if ( result !== false && !promise.isComplete() && db.initialized )
      {
        var remoteLoaded = db.remoteLoaded || !db.hasLoad( Load.All );
        var missingModel = (result === null || !result.$isSaved());
        var lazyLoad = db.hasLoad( Load.Lazy );

        if ( lazyLoad && remoteLoaded && missingModel )
        {
          if ( !result )
          {
            result = db.keyHandler.buildObjectFromKey( db.keyHandler.buildKeyFromInput( input ) );
          }

          result.$once( Model.Events.RemoteGets, function()
          {
            if ( !promise.isComplete() )
            {
              if ( isObject( input ) )
              {
                result.$set( input );
              }

              promise.resolve( result.$isSaved() ? result : null );
            }
          });

          result.$refresh( Cascade.All, db.fetchOptions );
        }
        else
        {
          promise.resolve( result );
        }
      }

      return promise.isComplete() ? false : true;
    }

    if ( checkModel() )
    {
      db.ready( checkModel, db, true );
    }

    return promise;
  }
1037608
function merge(source, target) {
    if (target == null) {
        return clone(source);
    }
    if (source == null) {
        return clone(target);
    }
    if (typeof source !== 'object' || typeof target !== 'object') {
        return clone(target);
    }
    const merge = (source, target) => {
        Object.keys(target).forEach(key => {
            if (source[key] == null) {
                source[key] = target[key];
            } else if (typeof source[key] === 'object') {
                if (typeof target[key] === 'object') {
                    merge(source[key], target[key]);
                } else {
                    source[key] = target[key];
                }
            } else {
                source[key] = target[key];
            }
        });

        return source;
    };

    return merge(clone(source), clone(target));
}
1070819
function executeRelatedResultWith (result) {
    // skip if no with models specified
    if (!defined(this.args.with)) {
        return
    }
    // add related records keyed by related model name
    result._related = {}
    // load all related records
    return Promise.map(_.keys(this.args.with), relatedName => this.executeRelatedResultWithQuery(result, relatedName), {
        concurrency: this.model.concurrency,
    })
}