code
stringlengths
2
1.05M
/* AngularJS v1.3.0-rc.0 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(r,d,s){'use strict';d.module("ngMessages",[]).directive("ngMessages",["$compile","$animate","$templateRequest",function(q,l,m){return{restrict:"AE",controller:["$scope",function(k){this.$renderNgMessageClasses=d.noop;var b=[];this.registerMessage=function(a,e){for(var c=0;c<b.length;c++)if(b[c].type==e.type){if(a!=c){var g=b[a];b[a]=b[c];a<b.length?b[c]=g:b.splice(0,c)}return}b.splice(a,0,e)};this.renderMessages=function(a,e){a=a||{};var c;d.forEach(b,function(b){var f;if(f=!c||e)f=a[b.type], f=null!==f&&!1!==f&&f;f?(b.attach(),c=!0):b.detach()});this.renderElementClasses(c)}}],require:"ngMessages",link:function(k,b,a,e){e.renderElementClasses=function(a){a?l.setClass(b,"ng-active","ng-inactive"):l.setClass(b,"ng-inactive","ng-active")};var c=d.isString(a.ngMessagesMultiple)||d.isString(a.multiple),g;k.$watchCollection(a.ngMessages||a["for"],function(a){g=a;e.renderMessages(a,c)});(a=a.ngMessagesInclude||a.include)&&m(a).then(function(a){var h;a=d.element("<div/>").html(a);d.forEach(a.children(), function(a){a=d.element(a);h?h.after(a):b.prepend(a);h=a;q(a)(k)});e.renderMessages(g,c)})}}}]).directive("ngMessage",["$animate",function(d){return{require:"^ngMessages",transclude:"element",terminal:!0,restrict:"AE",link:function(l,m,k,b,a){for(var e,c,g=m[0],f=g.parentNode,h=0,p=0;h<f.childNodes.length;h++){var n=f.childNodes[h];if(8==n.nodeType&&0<=n.nodeValue.indexOf("ngMessage")){if(n===g){e=p;break}p++}}b.registerMessage(e,{type:k.ngMessage||k.when,attach:function(){c||a(l,function(a){d.enter(a, null,m);c=a})},detach:function(a){c&&(d.leave(c),c=null)}})}}}])})(window,window.angular); //# sourceMappingURL=angular-messages.min.js.map
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("geolocator", [], factory); else if(typeof exports === 'object') exports["geolocator"] = factory(); else root["geolocator"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 7); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _toString = Object.prototype.toString; /** * Simple utility methods; internally used within Geolocator core; * made publically accessible. * @type {Object} * @readonly * * @license MIT * @copyright 2016, Onur Yıldırım (onur@cutepilot.com) */ var utils = { noop: function noop() {}, // --------------------------- // Validation // --------------------------- /** * Checks if the type of the given value is `String`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isString: function isString(value) { return typeof value === 'string'; }, isStringSet: function isStringSet(value) { return typeof value === 'string' && value.trim().length > 0; }, /** * Checks if the type of the given value is `Number`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isNumber: function isNumber(value) { return typeof value === 'number'; }, /** * Checks if the type of the given value is an `Object` or `Function`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isObject: function isObject(value) { var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return Boolean(value) && (type === 'object' || type === 'function'); }, /** * Checks if the type of the given value is `Function`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isFunction: function isFunction(value) { return typeof value === 'function'; }, /** * Checks if the type of the given value is `Array`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isArray: function isArray(value) { return Boolean(value) && _toString.call(value) === '[object Array]'; }, /** * Checks if the given object is a non-empty `Array`. * @memberof utils * * @param {*} array - Object to be checked. * @returns {Boolean} */ isFilledArray: function isFilledArray(array) { return utils.isArray(array) && array.length > 0; }, /** * Checks if the given value is a plain `Object`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isPlainObject: function isPlainObject(value) { return Boolean(value) && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && _toString.call(value) === '[object Object]'; }, /** * Checks if the given value is a `Date`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isDate: function isDate(value) { return Boolean(value) && _toString.call(value) === '[object Date]'; }, /** * Checks if the given object is a DOM element. * @memberof utils * * @param {Object} object - Object to be checked. * @returns {Boolean} */ isElement: function isElement(object) { if (!object) return false; return object instanceof HTMLElement || (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1; }, /** * Checks if the given object is a DOM node. * @memberof utils * * @param {Object} object - Object to be checked. * @returns {Boolean} */ isNode: function isNode(object) { if (!object) return false; return object instanceof Node || (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number'; }, /** * Checks if the given object is a jQuery instance. * This will still return `false` if the jQuery instance has no items. * @memberof utils * * @param {Object} object - Object to be checked. * @returns {Boolean} */ isJQueryObject: function isJQueryObject(object) { if (!object) return false; return 'jQuery' in window && object instanceof window.jQuery && Boolean(object[0]); // http://api.jquery.com/jquery-2/ // || (typeof object === 'object' && Boolean(object.jquery)); }, /** * Checks if the type of the given value is an HTML5 `PositionError`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isPositionError: function isPositionError(value) { return Boolean(value) && _toString.call(value) === '[object PositionError]'; }, /** * Checks if the given value is an instance of `Error` or HTML5 `PositionError`. * @memberof utils * * @param {*} value - Value to be checked. * @returns {Boolean} */ isError: function isError(value) { return value instanceof Error || utils.isPositionError(value); }, // --------------------------- // String // --------------------------- /** * Removes the query string portion from the given URL string. * @memberof utils * * @param {String} str - String to be processed. * @returns {String} - Returns the rest of the string. */ removeQuery: function removeQuery(str) { return str.replace(/\?.*$/, ''); }, /** * Removes the protocol portion from the given URL string. * @memberof utils * * @param {String} str - String to be processed. * @returns {String} - Returns the rest of the string. */ removeProtocol: function removeProtocol(str) { return str.replace(/^(.*:)?\/\//, ''); }, /** * Sets the protocol of the given URL. * @memberof utils * * @param {String} url * The URL to be modified. * @param {Boolean} [https] * Specifies whether to set the protocol to HTTPS. * If omitted, current page protocol will be used. * * @returns {String} - The modified URL string. */ setProtocol: function setProtocol(url, https) { var p = void 0; if (https === undefined || https === null) { p = window.location.protocol; } else { p = https ? 'https:' : 'http:'; } url = utils.removeProtocol(url); return p + '//' + url; }, /** * Removes both the leading and trailing dots from the given string. * @memberof utils * * @param {String} str - String to be processed. * @returns {String} - Returns the rest of the string. */ trimDots: function trimDots(str) { return str.replace(/^\.+?(.*?)\.+?$/g, '$1'); }, /** * URL-Encodes the given string. Note that the encoding is done Google's * way; that is, spaces are replaced with `+` instead of `%20`. * @memberof utils * * @param {String} str - String to be processed. * @returns {String} - Returns the encoded string. */ encodeURI: function encodeURI(str) { return encodeURIComponent(str).replace(/%20/g, '+'); }, /** * URL-Decodes the given string. This is the reverse of `utils.encodeURI()`; * so pluses (`+`) are replaced with spaces. * @memberof utils * * @param {String} str - String to be processed. * @returns {String} - Returns the decoded string. */ decodeURI: function decodeURI(str) { return decodeURIComponent(str.replace(/\+/g, '%20')); }, /** * Converts the given value to string. * `null` and `undefined` converts to empty string. * If value is a function, it's native `toString()` method is used. * Otherwise, value is coerced. * @memberof utils * * @param {*} value - String to be converted. * @returns {String} - Returns the result string. */ toString: function toString(value) { if (value === null || value === undefined) return ''; if (value.toString && utils.isFunction(value.toString)) { return value.toString(); } return String(value); }, /** * Generates a random string with the number of characters. * @memberof utils * * @param {Number} [len=1] - Length of the string. * @returns {String} - Returns a random string. */ randomString: function randomString(len) { if (!len || !utils.isNumber(len)) len = 1; len = -Math.abs(len); return Math.random().toString(36).slice(len); }, /** * Gets the abbreviation of the given phrase. * @memberof utils * * @param {String} str * String to abbreviate. * @param {Object} [options] * Abbreviation options. * @param {Boolean} [options.upper=true] * Whether to convert to upper-case. * @param {Boolean} [options.dots=true] * Whether to add dots after each abbreviation. * * @returns {String} - Returns the abbreviation of the given phrase. */ abbr: function abbr(str, options) { options = utils.extend({ upper: true, dots: true }, options); var d = options.dots ? '.' : '', s = str.match(/(\b\w)/gi).join(d) + d; return options.upper ? s.toUpperCase() : s; }, /** * Builds URI parameters from the given object. * Note: This does not iterate deep objects. * @memberof utils * * @param {Object} obj - Object to be processed. * @param {Object} options - Parameterize options. * @param {Boolean} [options.encode=true] * Whether to encode URI components. * @param {String} [options.operator="="] * @param {String} [options.separator="&"] * @param {Array} [options.include] * Keys to be included in the output params. If defined, * `options.exclude` is ignored. * @param {Array} [options.exclude] * Keys to be excluded from the output params. * * @returns {String} - URI parameters string. */ params: function params(obj, options) { if (!utils.isPlainObject(obj) || Object.keys(obj).length === 0) { return ''; } options = utils.extend({ encode: true, operator: '=', separator: '&', include: undefined, exclude: undefined }, options); var params = [], inc = utils.isArray(options.include) ? options.include : null, exc = !inc && utils.isArray(options.exclude) ? options.exclude : null; utils.forIn(obj, function (value, key) { if ((!inc || inc.indexOf(key) >= 0) && (!exc || exc.indexOf(key) < 0)) { var v = utils.toString(value); v = options.encode ? utils.encodeURI(v) : v; var k = options.encode ? utils.encodeURI(key) : key; params.push(k + options.operator + v); } }); return params.join(options.separator); }, /** * Gets the object from the given object notation string. * @private * * @param {String} notation - Object notation. * @returns {*} - Any existing object. */ notateGlobalObj: function notateGlobalObj(notation) { notation = utils.trimDots(notation); var levels = notation.split('.'), o = window; if (levels[0] === 'window' || levels[0] === 'document') { levels.shift(); } levels.forEach(function (note) { o = o[note]; }); return o; }, // --------------------------- // Object // --------------------------- /** * Iterates over own properties of an object invoking a callback for each * property. * @memberof utils * * @param {Object} obj * Object to be processed. * @param {Function} callback * Callback function with the following signature: * `function (value, key, object) { ... }`. * Explicitly returning `false` will exit the iteration early. * @returns {void} */ forIn: function forIn(obj, callback) { var k = void 0; for (k in obj) { // if (obj.hasOwnProperty(k)) {} // Do this inside callback if needed. if (callback(obj[k], k, obj) === false) break; } }, /** * Extends the given object with the specified sources. * Right most source overwrites the previous. * NOTE: This is not a full implementation. Use with caution. * @memberof utils * * @param {Object} destination * Destionation Object that will be extended and holds the default * values. * @param {...Object} sources * Source objects to be merged. * * @returns {Object} - Returns the extended object. */ extend: function extend(destination) { if (!utils.isObject(destination)) return {}; var key = void 0, value = void 0; for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } sources.forEach(function (source) { for (key in source) { // eslint-disable-line value = source[key]; if (utils.isArray(value)) { destination[key] = value.concat(); } else if (utils.isDate(value)) { destination[key] = new Date(value); } else if (utils.isFunction(value)) { // should be before object destination[key] = value; } else if (utils.isObject(value)) { destination[key] = utils.extend({}, value); } else { destination[key] = value; } } }); return destination; }, /** * Clones the given object. * NOTE: This is not a full implementation. Use with caution. * @memberof utils * * @param {Object} obj * Target Object to be cloned. * @param {Object|Array} [options] * Clone options or array of keys to be cloned. * @param {Array} [options.keys] * Keys of the properties to be cloned. * @param {Boolean} [options.own=true] * Whether to clone own properties only. This is only effective * if `keys` is not defined. * * @returns {Object} - Returns the cloned object. */ clone: function clone(obj, options) { if (!obj) return {}; if (utils.isArray(options)) { options = { keys: options }; } options = utils.extend({ keys: null, own: true }, options); var include = void 0, cloned = {}; utils.forIn(obj, function (value, key) { include = options.keys ? options.keys.indexOf(key) >= 0 : options.own && obj.hasOwnProperty(key) || !options.own; if (include) { if (utils.isObject(value)) { cloned[key] = utils.clone(value, options); } else { cloned[key] = value; } } }); return cloned; }, /** * Maps the values of the given object to a schema to re-structure a new * object. * @memberof utils * * @param {Object} obj * Original object to be mapped. * @param {Object} schema * Schema to be used to map the object. * * @returns {Object} - Mapped object. */ mapToSchema: function mapToSchema(obj, schema) { var mapped = {}; utils.forIn(schema, function (value, key) { if (utils.isPlainObject(value)) { mapped[key] = utils.mapToSchema(obj, value); } else { mapped[key] = obj[value]; } }); return mapped; }, // --------------------------- // Misc // --------------------------- /** * Safely parses the given JSON `String` into an `Object`. * The only difference from `JSON.parse()` is that this method does not * throw for invalid input. Instead, returns `null`. * @memberof utils * * @param {String} str - JSON string to be parsed * @returns {Object|null} - Returns the parsed `Object` or `null` if the * input is invalid. */ safeJsonParse: function safeJsonParse(str) { var o = null; try { o = JSON.parse(str); } catch (e) {} return o; }, /** * Gets a timestamp that is seconds or milliseconds since midnight, * January 1, 1970 UTC. * @memberof utils * * @param {Boolean} [seconds=false] * Specifies whether seconds should be returned instead of * milliseconds. * * @returns {Number} - Returns seconds or milliseconds since midnight, * January 1, 1970 UTC. */ time: function time(seconds) { var ts = Date.now(); return seconds ? parseInt(ts / 1000, 10) : ts; } }; exports.default = utils; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GOOGLE_MAPS_API_BASE = '//maps.googleapis.com/maps/api'; /** * This file only includes partial documentation about `geolocator` enumerations. * Note that these enumerations are mostly an aggregation of * {@link https://developers.google.com/maps/documentation/javascript|Google Maps API} constants. * * @private * @readonly */ var enums = Object.freeze({ /** * Enumerates API endpoints used within Geolocator core. * * @enum {String} * @readonly * @private */ URL: { /** * Public IP retrieval (free) service. * @type {String} * @private */ IP: '//api.ipify.org', /** * Country SVG flags. * e.g. <url>/tr.svg for Turkey flag. * @type {String} * @private */ FLAG: '//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/', /** * Google Maps API bootstrap endpoint that loads all of the main * Javascript objects and symbols for use in the Maps API. * Some Maps API features are also available in self-contained * libraries which are not loaded unless you specifically request them. * See {@link https://developers.google.com/maps/documentation/javascript/libraries|details}. * @type {String} * @private */ GOOGLE_MAPS_API: GOOGLE_MAPS_API_BASE + '/js', /** * Google Maps API Static Map endpoint. * @type {String} * @private */ GOOGLE_SATATIC_MAP: GOOGLE_MAPS_API_BASE + '/staticmap', /** * Google Geolocation API endpoint. * @type {String} * @private */ GOOGLE_GEOLOCATION: '//www.googleapis.com/geolocation/v1/geolocate', /** * Google Geocode API endpoint. * @type {String} * @private */ GOOGLE_GEOCODE: '//maps.googleapis.com/maps/api/geocode/json', /** * Google TimeZone API endpoint. * @type {String} * @private */ GOOGLE_TIMEZONE: '//maps.googleapis.com/maps/api/timezone/json', /** * Google Distance Matrix API endpoint. * @type {String} * @private */ GOOGLE_DISTANCE_MATRIX: '//maps.googleapis.com/maps/api/distancematrix/json' }, /** * Enumerates Google map types. * @memberof! geolocator * * @enum {String} * @readonly */ MapTypeId: { /** * Map type that displays a transparent layer of major streets on * satellite images. * @type {String} */ HYBRID: 'hybrid', /** * Map type that displays a normal street map. * @type {String} */ ROADMAP: 'roadmap', /** * Map type that displays satellite images. * @type {String} */ SATELLITE: 'satellite', /** * Map type displays maps with physical features such as terrain and * vegetation. * @type {String} */ TERRAIN: 'terrain' }, /** * Enumerates Google location types. * @memberof! geolocator * * @enum {String} * @readonly */ LocationType: { /** * Indicates that the returned result is a precise geocode for which * we have location information accurate down to street address * precision. * @type {String} */ ROOFTOP: 'ROOFTOP', /** * Indicates that the returned result reflects an approximation * (usually on a road) interpolated between two precise points (such as * intersections). Interpolated results are generally returned when * rooftop geocodes are unavailable for a street address. * @type {String} */ RANGE_INTERPOLATED: 'RANGE_INTERPOLATED', /** * Indicates that the returned result is the geometric center of a * result such as a polyline (for example, a street) or polygon * (region). * @type {String} */ GEOMETRIC_CENTER: 'GEOMETRIC_CENTER', /** * Indicates that the returned result is approximate. * @type {String} */ APPROXIMATE: 'APPROXIMATE' }, /** * Enumerates Google travel modes. * @memberof! geolocator * * @enum {String} * @readonly */ TravelMode: { /** * Indicates distance calculation using the road network. * @type {String} */ DRIVING: 'DRIVING', /** * Requests distance calculation for walking via pedestrian paths & * sidewalks (where available). * @type {String} */ WALKING: 'WALKING', /** * Requests distance calculation for bicycling via bicycle paths & * preferred streets (where available). * @type {String} */ BICYCLING: 'BICYCLING', /** * Requests distance calculation via public transit routes (where * available). This value may only be specified if the request includes * an API key or a Google Maps APIs Premium Plan client ID. If you set * the mode to transit you can optionally specify either a * `departureTime` or an `arrivalTime`. If neither time is specified, * the `departureTime` defaults to now (that is, the departure time defaults * to the current time). You can also optionally include a `transitMode` * and/or a `transitRoutingPreference`. * @type {String} */ TRANSIT: 'TRANSIT' }, // /** // * Enumerates Google route restrictions. // * @memberof! geolocator // * // * @enum {String} // * @readonly // */ // RouteRestriction: { // TOLLS: 'tolls', // HIGHWAYS: 'highways', // FERRIES: 'ferries', // INDOOR: 'indoor' // }, /** * Enumerates Google unit systems. * @memberof! geolocator * * @enum {Number} * @readonly */ UnitSystem: { /** * Distances in kilometers and meters. * @type {Number} */ METRIC: 0, /** * Distances defined in miles and feet. * @type {Number} */ IMPERIAL: 1 }, /** * Enumerates mobile radio types. * @memberof! geolocator * * @enum {String} * @readonly */ RadioType: { /** * LTE (Long-Term Evolution) mobile radio type. * @type {String} */ LTE: 'lte', /** * GSM (Global System for Mobile Communications) mobile radio type. * @type {String} */ GSM: 'gsm', /** * CDMA (Code division multiple access) mobile radio access technology. * @type {String} */ CDMA: 'cdma', /** * Wideband CDMA mobile radio access technology. * @type {String} */ WCDMA: 'wcdma' }, /** * Enumerates formulas/algorithms for calculating the distance between two * lat/lng points. * @memberof! geolocator * * @readonly * @enum {String} * * @todo {@link https://en.wikipedia.org/wiki/Vincenty%27s_formulae|Vincenty's Formula} */ DistanceFormula: { /** * Haversine formula for calculating the distance between two lat/lng points * by relating the sides and angles of spherical triangles. * @see {@link http://en.wikipedia.org/wiki/Haversine_formula|Haversine_formula}. * @type {String} */ HAVERSINE: 'haversine', /** * Formula based on the Pythagoras Theorem for calculating the * distance between two lat/lng points on a Equirectangular projection * to account for curvature of the longitude lines. * @see {@link https://en.wikipedia.org/wiki/Pythagorean_theorem|Pythagorean_theorem} * @type {String} */ PYTHAGOREAN: 'pythagorean' }, /** * Enumerates the image formats used for getting static Google Map images. * @memberof! geolocator * * @readonly * @enum {String} */ ImageFormat: { /** * Specifies the PNG image format. * Same as `PNG_8`. * @type {String} */ PNG: 'png', /** * Specifies the 8-bit PNG image format. * Same as `PNG`. * @type {String} */ PNG_8: 'png8', /** * Specifies the 32-bit PNG image format. * @type {String} */ PNG_32: 'png32', /** * Specifies the GIF image format. * @type {String} */ GIF: 'gif', /** * Specifies the JPEG compressed image format. * @type {String} */ JPG: 'jpg', /** * Specifies a non-progressive JPEG compression image format. * @type {String} */ JPG_BASELINE: 'jpg-baseline' } }); exports.default = enums; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _utils = __webpack_require__(0); var _utils2 = _interopRequireDefault(_utils); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Geolocator Error class that provides a common type of error object for the * various APIs implemented in Geolocator. All callbacks of Geolocator will * include an instance of this object as the first argument; if the * corresponding operation fails. Also all thrown errors will be an instance of * this object. * * This object can be publicly accessed via `geolocator.Error`. * * @extends Error */ var GeoError = function () { // extends Error (doesn't work with transpilers) /** * Costructs a new instance of `GeoError`. * * @param {String} [code="UNKNOWN_ERROR"] * Any valid Geolocator Error code. * See {@link #GeoError.Code|`GeoError.Code` enumeration} for * possible values. * @param {String} [message] * Error message. If omitted, this will be set to `code`. * * @returns {GeoError} * * @example * var GeoError = geolocator.Error, * error = new GeoError(GeoError.Code.GEOLOCATION_NOT_SUPPORTED); * console.log(error.code); // "GEOLOCATION_NOT_SUPPORTED" * console.log(error instanceof GeoError); // true */ function GeoError() { var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : GeoError.Code.UNKNOWN_ERROR; var message = arguments[1]; _classCallCheck(this, GeoError); message = message || String(code); /** * Gets the name of the Error object. * This always returns `"GeoError"`. * @name GeoError#name * @type {String} */ Object.defineProperty(this, 'name', { enumerable: false, writable: false, value: 'GeoError' // this.constructor.name }); /** * Gets the error code set for this instance. * This will return one of * {@link #GeoError.Code|`GeoError.Code` enumeration}. * @name GeoError#code * @type {String} */ Object.defineProperty(this, 'code', { enumerable: false, writable: true, value: code }); /** * Gets the error message set for this instance. * If no message is set, this will return the error code value. * @name GeoError#message * @type {String} */ Object.defineProperty(this, 'message', { enumerable: false, writable: true, value: message }); if (Error.hasOwnProperty('captureStackTrace')) { // V8 Error.captureStackTrace(this, this.constructor); } else { /** * Gets the error stack for this instance. * @name GeoError#stack * @type {String} */ Object.defineProperty(this, 'stack', { enumerable: false, writable: false, value: new Error(message).stack }); } } /** * Creates a new instance of `GeoError` from the given value. * * @param {*} [err] * Value to be transformed. This is used to determine the proper * error code for the created instance. If an `Error` or `Object` is * passed, its `message` property is checked if it matches any of the * valid error codes. If omitted or no match is found, error code * `GeoError.Code.UNKNOWN_ERROR` will be used as default. * * @returns {GeoError} * * @example * var GeoError = geolocator.Error, * error = GeoError.create(); * console.log(error.code); // "UNKNOWN_ERROR" * error = GeoError.create(GeoError.Code.GEOLOCATION_NOT_SUPPORTED); * console.log(error.code); // "GEOLOCATION_NOT_SUPPORTED" */ _createClass(GeoError, null, [{ key: 'create', value: function create(err) { if (err instanceof GeoError) { return err; } var code = void 0, msg = void 0; if (_utils2.default.isPositionError(err) && err.code) { switch (err.code) { case 1: code = GeoError.Code.PERMISSION_DENIED; break; case 2: code = GeoError.Code.POSITION_UNAVAILABLE; break; case 3: code = GeoError.Code.TIMEOUT; break; default: code = GeoError.Code.UNKNOWN_ERROR; break; } return new GeoError(code, err.message || ''); } if (typeof err === 'string') { code = msg = err; } else if ((typeof err === 'undefined' ? 'undefined' : _typeof(err)) === 'object') { code = err.code || err.message; msg = err.message || err.code; } if (code && GeoError.isValidErrorCode(code)) { return new GeoError(code, msg); } return new GeoError(GeoError.Code.UNKNOWN_ERROR, msg); } /** * Creates a new instance of `GeoError` from the given response object. * Since Geolocator implements various Google APIs, we might receive * responses if different structures. For example, some APIs return a * response object with a `status:String` property (such as the TimeZone * API) and some return responses with an `error:Object` property. This * method will determine the correct reason or message and return a * consistent error object. * * @param {Object|String} response * Response (Object) or status (String) to be transformed. * @param {String} [message=null] * Error message. * * @returns {GeoError} * `GeoError` instance if response contains an error. Otherwise, * returns `null`. * * @example * var error = geolocator.Error.fromResponse(googleResponse); * console.log(error.code); // "GOOGLE_KEY_INVALID" */ }, { key: 'fromResponse', value: function fromResponse(response) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; // example Google Geolocation API response: // https://developers.google.com/maps/documentation/geolocation/intro#errors // { // "error": { // "errors": [ // { // "domain": "global", // "reason": "parseError", // "message": "Parse Error", // } // ], // "code": 400, // "message": "Parse Error" // } // } // example Google TimeZone API response: // { // "status": "REQUEST_DENIED" // } if (!response) return new GeoError(GeoError.Code.INVALID_RESPONSE); var errCode = void 0; if (_utils2.default.isString(response)) { errCode = errorCodeFromStatus(response); if (errCode) return new GeoError(errCode, message || response); } if (!_utils2.default.isObject(response)) return null; var errMsg = response.error_message || response.errorMessage || response.error && response.error.message || '' || ''; if (response.status) { errCode = errorCodeFromStatus(response.status); if (errCode) return new GeoError(errCode, errMsg || message || response.status); } if (response.error) { var reason = response.reason || response.error.reason; if (!reason) { var errors = response.error.errors; if (_utils2.default.isArray(errors) && errors.length > 0) { reason = errors[0].reason; // get the first reason only errMsg = errMsg || errors[0].message; // update errMsg } } errCode = errorCodeFromReason(reason) || GeoError.Code.UNKNOWN_ERROR; return new GeoError(errCode, errMsg || reason || message); } if (errMsg) { errCode = errorCodeFromStatus(errMsg) || GeoError.Code.UNKNOWN_ERROR; return new GeoError(errCode, errMsg || message); } return null; } /** * Checks whether the given value is an instance of `GeoError`. * * @param {*} err - Object to be checked. * * @returns {Boolean} */ }, { key: 'isGeoError', value: function isGeoError(err) { return err instanceof GeoError; } /** * Checks whether the given value is a valid Geolocator Error code. * * @param {String} errorCode - Error code to be checked. * * @returns {Boolean} */ }, { key: 'isValidErrorCode', value: function isValidErrorCode(errorCode) { var prop = void 0; for (prop in GeoError.Code) { if (GeoError.Code.hasOwnProperty(prop) && errorCode === GeoError.Code[prop]) { return true; } } return false; } }]); return GeoError; }(); /** * Gets the string representation of the error instance. * * @returns {String} */ GeoError.prototype.toString = function () { var msg = this.code !== this.message ? ' (' + this.message + ')' : ''; return this.name + ': ' + this.code + msg; }; // `class x extends Error` doesn't work when using an ES6 transpiler, such as // Babel, since subclasses must extend a class. With Babel 6, we need // transform-builtin-extend plugin for this to work. So we're extending from // Error the old way. Now, `err instanceof Error` also returns `true`. if (typeof Object.setPrototypeOf === 'function') { Object.setPrototypeOf(GeoError.prototype, Error.prototype); } else { GeoError.prototype = Object.create(Error.prototype); } // --------------------------- // ERROR CODES // --------------------------- /** * Enumerates Geolocator error codes. * This enumeration combines Google API status (error) codes, HTML5 Geolocation * position error codes and other Geolocator-specific error codes. * @enum {String} */ GeoError.Code = { /** * Indicates that HTML5 Geolocation API is not supported by the browser. * @type {String} */ GEOLOCATION_NOT_SUPPORTED: 'GEOLOCATION_NOT_SUPPORTED', /** * Indicates that Geolocation-IP source is not set or invalid. * @type {String} */ INVALID_GEO_IP_SOURCE: 'INVALID_GEO_IP_SOURCE', /** * The acquisition of the geolocation information failed because the * page didn't have the permission to do it. * @type {String} */ PERMISSION_DENIED: 'PERMISSION_DENIED', /** * The acquisition of the geolocation failed because at least one * internal source of position returned an internal error. * @type {String} */ POSITION_UNAVAILABLE: 'POSITION_UNAVAILABLE', /** * The time allowed to acquire the geolocation, defined by * PositionOptions.timeout information was reached before * the information was obtained. * @type {String} */ TIMEOUT: 'TIMEOUT', /** * Indicates that the request had one or more invalid parameters. * @type {String} */ INVALID_PARAMETERS: 'INVALID_PARAMETERS', /** * Indicates that the service returned invalid response. * @type {String} */ INVALID_RESPONSE: 'INVALID_RESPONSE', /** * Generally indicates that the query (address, components or latlng) * is missing. * @type {String} */ INVALID_REQUEST: 'INVALID_REQUEST', /** * Indicates that the request was denied by the service. * This will generally occur because of a missing API key or because the request * is sent over HTTP instead of HTTPS. * @type {String} */ REQUEST_DENIED: 'REQUEST_DENIED', /** * Indicates that the request has failed. * This will generally occur because of an XHR error. * @type {String} */ REQUEST_FAILED: 'REQUEST_FAILED', /** * Indicates that Google API could not be loaded. * @type {String} */ GOOGLE_API_FAILED: 'GOOGLE_API_FAILED', /** * Indicates that you are over your Google API quota. * @type {String} */ OVER_QUERY_LIMIT: 'OVER_QUERY_LIMIT', /** * Indicates that you've exceeded the requests per second per user limit that * you configured in the Google Developers Console. This limit should be * configured to prevent a single or small group of users from exhausting your * daily quota, while still allowing reasonable access to all users. * @type {String} */ USER_RATE_LIMIT_EXCEEDED: 'USER_RATE_LIMIT_EXCEEDED', /** * Indicates that you've exceeded your daily limit for Google API(s). * @type {String} */ DAILY_LIMIT_EXCEEDED: 'DAILY_LIMIT_EXCEEDED', /** * Indicates that your Google API key is not valid. Please ensure that you've * included the entire key, and that you've either purchased the API or have * enabled billing and activated the API to obtain the free quota. * @type {String} */ GOOGLE_KEY_INVALID: 'GOOGLE_KEY_INVALID', /** * Indicates that maximum number of elements limit is exceeded. For * example, for the Distance Matrix API; occurs when the product of * origins and destinations exceeds the per-query limit. * @type {String} */ MAX_ELEMENTS_EXCEEDED: 'MAX_ELEMENTS_EXCEEDED', /** * Indicates that the request contained more than 25 origins, * or more than 25 destinations. * @type {String} */ MAX_DIMENSIONS_EXCEEDED: 'MAX_DIMENSIONS_EXCEEDED', /** * Indicates that the request contained more than allowed waypoints. * @type {String} */ MAX_WAYPOINTS_EXCEEDED: 'MAX_WAYPOINTS_EXCEEDED', /** * Indicates that the request body is not valid JSON. * @type {String} */ PARSE_ERROR: 'PARSE_ERROR', /** * Indicates that the requested resource could not be found. * Note that this also covers `ZERO_RESULTS`. * @type {String} */ NOT_FOUND: 'NOT_FOUND', /** * Indicates that an internal error (such as XHR cross-domain, etc) has occured. * @type {String} */ INTERNAL_ERROR: 'INTERNAL_ERROR', /** * Indicates that an unknown error has occured. * @type {String} */ UNKNOWN_ERROR: 'UNKNOWN_ERROR' }; // --------------------------- // HELPER METHODS // --------------------------- /** * @private */ function errorCodeFromStatus(status) { if (!status) return GeoError.Code.INVALID_RESPONSE; if (status === 'OK') return null; if (status === 'ZERO_RESULTS') return GeoError.Code.NOT_FOUND; if (GeoError.Code.hasOwnProperty(status)) return status; return null; } /** * Gets `GeoError.Code` from the given response error reason. * @private * * @param {String} reason * Google response error reason. * * @returns {String} */ function errorCodeFromReason(reason) { switch (reason) { case 'invalid': return GeoError.Code.INVALID_REQUEST; case 'dailyLimitExceeded': return GeoError.Code.DAILY_LIMIT_EXCEEDED; case 'keyInvalid': return GeoError.Code.GOOGLE_KEY_INVALID; case 'userRateLimitExceeded': return GeoError.Code.USER_RATE_LIMIT_EXCEEDED; case 'notFound': return GeoError.Code.NOT_FOUND; case 'parseError': return GeoError.Code.PARSE_ERROR; default: return null; } } // --------------------------- // EXPORT // --------------------------- exports.default = GeoError; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _utils = __webpack_require__(0); var _utils2 = _interopRequireDefault(_utils); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Utility for making `XMLHttpRequest` and `JSONP` requests. * * @license MIT * @copyright 2016, Onur Yıldırım (onur@cutepilot.com) */ var fetch = function () { function fetch() { _classCallCheck(this, fetch); } _createClass(fetch, null, [{ key: 'jsonp', // https://html.spec.whatwg.org/multipage/scripting.html#script /** * Makes a JSONP (GET) request by injecting a script tag in the browser. * Note that using JSONP has some security implications. As JSONP is really * javascript, it can do everything else javascript can do, so you need to * trust the provider of the JSONP data. * @see https://en.wikipedia.org/wiki/JSONP * @memberof fetch * * @param {Object|String} options - Required. Either the URL string which * will set other options to defaults or an options object with the * following properties. * @param {String} options.url * Source URL to be called. * @param {String} [options.type] * The MIME type that identifies the scripting language of the * code referenced within the script element. * e.g. `"text/javascript"` * @param {String} [options.charset] * Indicates the character encoding of the external resource. * e.g. `"utf-8"`. * @param {Boolean} [options.async=true] * Indicates whether or not to perform the operation * asynchronously. See {@link http://caniuse.com/#feat=script-async|browser support}. * @param {Boolean} [options.defer=false] * Indicates whether the script should be executed when the page * has finished parsing. See {@link http://caniuse.com/#feat=script-defer|browser support}. * @param {String} [options.crossorigin] * Indicates the CORS setting for the script element being * injected. Note that this attribute is not widely supported. * Valid values: `"anonymous"`, `"use-credentials"`. * See {@link https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes|CORS settings}. * @param {Number} [options.timeout=0] * The number of milliseconds a request can take before * automatically being terminated. `0` disables timeout. * @param {Boolean} [options.clean=false] * Whether to remove the loaded script from DOM when the * operation ends. Note that the initial source might load * additional sources which are not deteceted or removed. Only * the initial source is removed. * @param {Object} [options.params] * Optional query parameters to be appended at the end of the URL. * e.g. `{ key: "MY-KEY" }` * You can also include the JSONP callback name parameter here * but if you want the object to be passed to the callback * argument of this method, use `options.callbackParam` to set * the callback parameter. * @param {String} [options.callbackParam] * If the endpoint supports JSONP callbacks, you can set the * callback parameter with this setting. This will enable a * second `obj` argument in the callback of this method which is * useful if the JSONP source invokes the callback with an * argument. * @param {String} [options.rootName] * The name (or notation) of the object that the generated JSONP * callback function should be assigned to. By default, this is * the `window` object but you can set this to a custom object * notation; for example, to prevent global namespace polution. * Note that this root object has to be globally accessible for * this to work. e.g. `"window.myObject"` (as string) * @param {Function} [callback] * The callback function that will be executed when the script is * loaded. This callback has the following signature: * `function (err, obj) { ... }`. Note that the second argument * `obj` will always be `undefined` if the source endpoint does not * support JSONP callbacks or a callback param is not set explicitly * via `options.callbackParam` (or if the source does not invoke the * jsonp with an argument). However, the function will always execute * when the script loads or an error occurs. * * @returns {void} * * @example * var opts1 = { * url: 'some/api', * callbackParam: 'jsonCallback', * params: { key: 'MY-KEY' } * }; * // This will load the following source: * // some/api?jsonCallback={auto-generated-fn-name}&key=MY-KEY * fetch.jsonp(opts1, function (err, obj) { * console.log(obj); // some object * }); * * var opts2 = { * url: 'some/api', * params: { * key: 'MY-KEY', * jsonCallback: 'my-fn-name' * } * }; * // This will load the following source: * // some/api?jsonCallback=my-fn-name&key=MY-KEY * fetch.jsonp(options, function (err, obj) { * console.log(obj); // undefined * // still executes, catch errors here * }); * // JSON callback should be explicitly set. * window['my-fn-name'] = function (obj) { * console.log(obj); // some object * }; */ value: function jsonp(options, callback) { var timeout = void 0; callback = _utils2.default.isFunction(callback) ? callback : _utils2.default.noop; if (_utils2.default.isString(options)) { options = { url: options }; } if (_utils2.default.isPlainObject(options)) { options = _utils2.default.extend({ // type: undefined, async: true, defer: false, // crossorigin: undefined, timeout: 0, params: {}, // callbackParam: undefined, // rootName: undefined, clean: true }, options); } else { return callback(new Error('No options or target URL is provided.')); } if (_utils2.default.isString(options.url) === false || options.url.trim() === '') { return callback(new Error('No target URL is provided.')); } var script = document.createElement('script'), cbParamSet = _utils2.default.isString(options.callbackParam) && options.callbackParam.trim() !== '', cbFnName = void 0, root = void 0, rootNameSet = _utils2.default.isString(options.rootName) && options.rootName !== 'window' && options.rootName !== 'document' && options.rootName.trim() !== ''; if (cbParamSet) { cbFnName = '_jsonp_' + _utils2.default.randomString(10); options.params[options.callbackParam] = rootNameSet ? options.rootName + '.' + cbFnName : cbFnName; } var query = _utils2.default.params(options.params) || '', qMark = options.url.indexOf('?') >= 0 ? '&' : '?', url = query ? '' + options.url + qMark + query : options.url; // console.log(url); function execCb(err, timeUp, obj) { if (timeout) { clearTimeout(timeout); timeout = null; } if ((timeUp || options.clean) && script.parentNode) { script.parentNode.removeChild(script); } // delete the jsonp callback function if (rootNameSet) { delete root[cbFnName]; } callback(err, obj); } if (cbFnName) { var fn = function fn(obj) { execCb(null, false, obj); }; root = rootNameSet // ? window[options.rootName][cbFnName] = fn; ? _utils2.default.notateGlobalObj(options.rootName) // if rootName is dot-notation. : window; root[cbFnName] = fn; } else if (script.readyState) { // IE < 11 script.onreadystatechange = function () { if (script.readyState === 'loaded' || script.readyState === 'complete') { script.onreadystatechange = null; execCb(null); } }; } else { // IE 11+ script.onload = function () { execCb(null); }; } script.onerror = function (error) { var errMsg = 'Could not load source at ' + _utils2.default.removeQuery(options.url); if (error) { errMsg += '\n' + (error.message || error); } execCb(new Error(errMsg)); }; if (options.type) { script.type = options.type; } if (options.charset) { script.charset = options.charset; } if (options.async) { script.async = true; } if (options.defer) { script.defer = true; } if (options.crossorigin) { script.crossorigin = options.crossorigin; } script.src = url; document.getElementsByTagName('head')[0].appendChild(script); // Timeout if (_utils2.default.isNumber(options.timeout) && options.timeout > 0) { timeout = setTimeout(function () { script.src = ''; execCb(new Error('Operation timed out.'), true); }, options.timeout); } } /** * Makes an XMLHttpRequest with the given parameters. * Note that `"Access-Control-Allow-Origin"` header should be present on * the requested resource. Otherwise, the request will not be allowed. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}. * @memberof fetch * * @param {Object|String} options * Either the URL string which will set other options to defaults or * the full options object. * @param {String} options.url * Target URL to be called. * @param {String} [options.method="GET"] * HTTP method. * @param {*} [options.data] * Data to be sent with the request. * @param {Number} [options.timeout] * The number of milliseconds a request can take before * automatically being terminated. `0` disables timeout. * @param {Boolean} [options.withCredentials=false] * Indicates whether or not cross-site Access-Control requests * should be made using credentials such as cookies or * authorization headers. * @param {Boolean} [options.async=true] * Indicating whether or not to perform the operation * asynchronously. If this value is false, the `send()` method * does not return until the response is received. If `true`, * notification of a completed transaction is provided using * event listeners. This must be `true` if the multipart * attribute is `true`, or an exception will be thrown. * @param {String} [options.mimeType] * If set, overrides the MIME type returned by the server. This * may be used, for example, to force a stream to be treated and * parsed as `text/xml`, even if the server does not report it as * such. * @param {Object} [options.headers] * Sets the HTTP request headers. Each key should be a header * name with a value. e.g. `{ 'Content-Length': 50 }`. For * security reasons, some headers cannot be set and can only be * controlled by the user agent. * @param {String} [options.username=""] * User name to use for authentication purposes. * @param {String} [options.password=""] * Password to use for authentication purposes. * @param {Function} [callback] * The callback function in the following signature: * `function (err, xhr) { ... }` * Note that `xhr` object is always passed regardless of an error. * * @returns {void} */ }, { key: 'xhr', value: function xhr(options, callback) { var xhr = void 0, err = void 0; if ('XMLHttpRequest' in window) { xhr = new XMLHttpRequest(); } else { throw new Error('XMLHttpRequest is not supported!'); } var hasCallback = _utils2.default.isFunction(callback); callback = hasCallback ? callback : _utils2.default.noop; if (_utils2.default.isString(options)) { options = { url: options }; } if (_utils2.default.isPlainObject(options)) { options = _utils2.default.extend({ method: 'GET', data: undefined, async: true, timeout: 0, // no timeout withCredentials: false, mimeType: undefined, username: '', password: '' }, options); } else { callback(new Error('No options or target URL is provided.')); } if (_utils2.default.isString(options.url) === false) { callback(new Error('No target URL is provided.')); } options.username = String(options.username); options.password = String(options.password); options.method = options.method.toUpperCase(); if (options.method !== 'POST' && options.method !== 'PUT') { options.data = undefined; } // console.log(JSON.stringify(options)); if (hasCallback) { xhr.onreadystatechange = function () { if (xhr.readyState === fetch.XHR_READY_STATE.DONE) { if (xhr.status === 200) { callback(null, xhr); } else { // let response = utils.safeJsonParse(xhr.responseText); // if (response && response.error) var crossDomain = xhr.status === 0 ? '. Make sure you have permission if this is a cross-domain request.' : ''; err = new Error('The request returned status: ' + xhr.status + crossDomain); // console.log(xhr); callback(err, xhr); } } }; if (_utils2.default.isNumber(options.timeout) && options.timeout > 0) { xhr.timeout = options.timeout; xhr.ontimeout = function () { // xhr.abort(); err = new Error('The request had timed out.'); callback(err, xhr); }; } } // console.log(options); xhr.open(options.method, options.url, options.async, options.username, options.password); // xhr.setRequestHeader() method should b called œafter open(), but // before send(). if (_utils2.default.isPlainObject(options.headers)) { Object.keys(options.headers).forEach(function (key) { var value = options.headers[key]; xhr.setRequestHeader(key, value); }); } // xhr.overrideMimeType() method must be called before send(). if (options.mimeType) { xhr.overrideMimeType(options.mimeType); } xhr.send(options.data); } /** * Alias of `fetch.xhr()` with request method set to `"GET"` by default. * @memberof fetch * * @param {Object} options * Either the URL string which will set other options to defaults or * the full options object. See `fetch.xhr()` method options for * details. * @param {Function} [callback] * The callback function in the following signature: * `function (err, xhr) { ... }` * Note that `xhr` object is always passed regardless of an error. * @returns {void} */ }, { key: 'get', value: function get(options, callback) { return fetch.xhr(options, callback); } /** * Alias of `fetch.xhr()` with request method set to `"POST"` by default. * @memberof fetch * * @param {Object} options * Either the URL string which will set other options to defaults or * the full options object. See `fetch.xhr()` method options for * details. * @param {Function} [callback] * The callback function in the following signature: * `function (err, xhr) { ... }` * Note that `xhr` object is always passed regardless of an error. * @returns {void} */ }, { key: 'post', value: function post(options, callback) { return _xhr('POST', options, callback); } /** * Alias of `fetch.xhr()` with request method set to `"PUT"` by default. * @memberof fetch * * @param {Object} options * Either the URL string which will set other options to defaults or * the full options object. See `fetch.xhr()` method options for * details. * @param {Function} [callback] * The callback function in the following signature: * `function (err, xhr) { ... }` * Note that `xhr` object is always passed regardless of an error. * @returns {void} */ }, { key: 'put', value: function put(options, callback) { return _xhr('PUT', options, callback); } /** * Alias of `fetch.xhr()` with request method set to `"DELETE"` by default. * @memberof fetch * * @param {Object} options * Either the URL string which will set other options to defaults or * the full options object. See `fetch.xhr()` method options for * details. * @param {Function} [callback] * The callback function in the following signature: * `function (err, xhr) { ... }` * Note that `xhr` object is always passed regardless of an error. * @returns {void} */ }, { key: 'delete', value: function _delete(options, callback) { return _xhr('DELETE', options, callback); } }]); return fetch; }(); /** * @private */ function _xhr(method, options, callback) { options = _utils2.default.isString(options) ? { url: options } : options || {}; options.method = method; return fetch.xhr(options, callback); } /** * Enumerates `XMLHttpRequest` ready states. * Not to be confused with `script.readyState`. * @memberof fetch * * @enum {Number} */ fetch.XHR_READY_STATE = { /** * `xhr.open()` has not been called yet. * @type {Number} */ UNSENT: 0, /** * `xhr.send()` has been called. * @type {Number} */ OPENED: 1, /** * `xhr.send()` has been called, and headers and status are available. * @type {Number} */ HEADERS_RECEIVED: 2, /** * Downloading; responseText holds partial data. * @type {Number} */ LOADING: 3, /** * The operation is complete. * @type {Number} */ DONE: 4 }; exports.default = fetch; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _utils = __webpack_require__(0); var _utils2 = _interopRequireDefault(_utils); var _fetch = __webpack_require__(3); var _fetch2 = _interopRequireDefault(_fetch); var _geo = __webpack_require__(5); var _geo2 = _interopRequireDefault(_geo); var _geo3 = __webpack_require__(2); var _geo4 = _interopRequireDefault(_geo3); var _geo5 = __webpack_require__(6); var _geo6 = _interopRequireDefault(_geo5); var _enums = __webpack_require__(1); var _enums2 = _interopRequireDefault(_enums); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Radius of earth in kilometers. * @private * @type {Number} */ var EARTH_RADIUS_KM = 6371; /** * Radius of earth in miles. * @private * @type {Number} */ var EARTH_RADIUS_MI = 3959; /** * Storage for Geolocator default configuration. * * @readonly * @private */ var defaultConfig = { language: 'en', https: true, google: { version: '3', // latest 3.x key: '', styles: null } }; /** * Geolocator library that provides methods for getting geo-location information, * geocoding, address look-ups, distance & durations, timezone information and more... * This library makes use of HTML5 position feautures, implements Google APIs * and other services. * * <b>Important Notes:</b> * * Although some calls might work without a key, it is generally required by * most {@link https://developers.google.com/maps/faq#using-google-maps-apis|Goolge APIs} * (such as Time Zone API). To get a free (or premium) key, * {@link https://developers.google.com/maps/documentation/javascript/|click here}. * After getting a key, you can enable multiple APIs for it. Make sure you * {@link https://console.developers.google.com|enable} * all the APIs supported by Geolocator. * * Note that browser API keys cannot have referer restrictions when used * with some Google APIs. * * Make sure your doctype is HTML5 and you're calling Geolocation APIs from an * HTTPS page. Geolocation API is removed from unsecured origins in Chrome 50. * Other browsers are expected to follow. * * @license MIT * @copyright 2016, Onur Yıldırım (onur@cutepilot.com) */ var geolocator = function () { function geolocator() { _classCallCheck(this, geolocator); } _createClass(geolocator, null, [{ key: 'config', // --------------------------- // STATIC METHODS // --------------------------- /** * Sets or gets the geolocator configuration object. * Make sure you configure Geolocator before calling other methods that * require a Google API key. * * @param {Object} [options] * Configuration object. If omitted, this method returns the current * configuration. * @param {String} [options.language="en"] * Language to be used for API requests that supports language * configurations. This is generally used for Google APIs. * See {@link https://developers.google.com/maps/faq#languagesupport|supported languages}. * @param {Boolean} [options.https=true] * As Google recommends; using HTTPS encryption makes your site * more secure, and more resistant to snooping or tampering. * If set to `true`, the API calls are made over HTTPS, at all * times. Setting to `false` will switch to HTTP (even if the * page is on HTTPS). And if set to `null`, current protocol will * be used. Note that some APIs might not work with HTTP such as * Google Maps TimeZone API. * @param {Object} [options.google] * Google specific options. * @param {String} [options.google.version="3"] * Google Maps API version to be used (with * `geolocator.createMap()`) method. The default version * value is tested and works with Geolocator. You can set a * greater value or the latest version number and it should * work; but it's not guaranteed. Find out the * {@link https://developers.google.com/maps/documentation/javascript/versions|latest version here}. * @param {String} [options.google.key=""] * API key to be used with Google API calls. Although some * calls might work without a key, it is generally required * by most Goolge APIs. To get a free (or premium) key, * {@link https://developers.google.com/maps/documentation/javascript/|click here}. * @param {Array} [options.google.styles] * An array of objects to customize the presentation of the * Google base maps, changing the visual display of such * elements as roads, parks, and built-up areas. * See {@link https://developers.google.com/maps/documentation/javascript/styling|Styling Maps}. * * @returns {Object} - Returns the current or updated configuration object. * * @example * geolocator.config({ * language: "en", * google: { * version: "3", * key: "YOUR-GOOGLE-API-KEY" * } * }); */ value: function config(options) { if (options) { geolocator._.config = _utils2.default.extend(defaultConfig, options); } return geolocator._.config; } /** * Gets a static map image URL which can be embeded via an `<img />` tag * on the page. * * Note that, if `options.center` is set to an address (instead of * coordinates) and `options.marker` is also set; we will need to geocode * that address to get center coordinates for the marker. * In this case, you must use the `callback` parameter to get the async * result. Otherwise, this method will directly return a `String`. * * Make sure you have enabled Static Maps API (and Geocoding API if * `marker` is enabled) in your Google Developers console. * * For interactive map, see {@link #geolocator.createMap|`geolocator.createMap()` method}. * * @see {@link https://developers.google.com/maps/documentation/static-maps/intro|Static Maps} * @see {@link https://developers.google.com/maps/documentation/static-maps/usage-limits|Usage Limits} * * @param {Object} options * Static map options. * @param {String|Object} options.center * Defines the center of the map and the location. * Either an address `String` or an coordinates `Object` with * `latitude:Number` and `longitude:Number` properties. * @param {String} [options.mapTypeId="roadmap"] * Type of the map to be created. * See {@link #geolocator.MapTypeId|`geolocator.MapTypeId` enumeration} * for possible values. * @param {String|Object} [options.size="600x300"] * Defines the size (in pixels) of the returned image. * Either a string in `widthxheight` format or an Object * with `width:Number` and `height:Number` properties. * @param {Number} [options.scale=1] * Affects the number of pixels that are returned. scale=2 * returns twice as many pixels as scale=1 while retaining * the same coverage area and level of detail (i.e. the * contents of the map don't change). Accepted values are 1, * 2 and 4 (4 is only available to Google Maps APIs Premium * Plan customers.) * @param {Number} [options.zoom=9] * Zoom level to be set for the map. * @param {String} [options.format=png] * Defines the format of the resulting image. * See {@link #geolocator.ImageFormat|`geolocator.ImageFormat` enumeration} * for possible values. * @param {Boolean|String} [options.marker=true] * Specifies whether to add a marker to the center of the map. * You can define the color of the marker by passing a color * `String` instead of a `Boolean`. Color can be a predefined * color from the set `red` (default), `black`, `brown`, * `green`, `purple`, `yellow`, `blue`, `gray`, `orange` and * `white`; or a HEX 24-bit color (e.g. `"0xFF0000"`). * Note that marker will not be visible if `center` is set to * a `String` address and you don't use the callback. * @param {String} [options.region] * Defines the appropriate borders to display, based on * geo-political sensitivities. Accepts a region code * specified as a two-character ccTLD (top-level domain) * value. e.g. `"us"`. * @param {Array} [options.styles] * An array of objects to customize the presentation of the * Google base maps, changing the visual display of such * elements as roads, parks, and built-up areas. * This will default to the global styles set via * {@link #geolocator.config|`geolocator.config()` method}, if any. * See {@link https://developers.google.com/maps/documentation/javascript/styling|Styling Maps}. * * @param {Function} [callback] * Callback function to be executed when the static map URL is built. * This takes 2 arguments: `function (err, url) { ... }`. * If omitted, this method will directly return the static map * image URL; but (if enabled) the marker will not be visible if * `options.center` is set to an address `String` instead of a * coordinates `Object`. * * @returns {String|void} * If a callback is passed, this will return `void`. * Otherwise, a `String` that represents the URL of the static map. * * @example * // Async example (with address and marker) * var options = { * center: "Los Angles, CA, US", * mapTypeId: geolocator.MapTypeId.ROADMAP, * size: "600x300", * scale: 1, * zoom: 5, * marker: "0xFFCC00", * format: geolocator.ImageFormat.PNG * }; * geolocator.getStaticMap(options, function (err, url) { * if (!err) { * document.getElementById('my-img').src = url; * } * }); * * @example * // Sync example (with coordinates) * var options = { * center: { * longitude: 34.0522342, * latitude: -118.2436849 * }, * mapTypeId: geolocator.MapTypeId.ROADMAP, * size: "600x300", * scale: 1, * zoom: 5, * marker: "0xFFCC00", * format: geolocator.ImageFormat.PNG * }; * document.getElementById('my-img').src = geolocator.getStaticMap(options); */ }, { key: 'getStaticMap', value: function getStaticMap(options, callback) { if (!_utils2.default.isPlainObject(options) || !options.center) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS, 'A center address or coordinates are required.'); } if (_utils2.default.isString(options.center)) { return geolocator.geocode(options.center, function (err, location) { if (err) callback(err); options.center = location.coords; callback(null, geolocator.getStaticMap(options)); }); } var conf = geolocator._.config; var opts = _utils2.default.extend({ mapTypeId: _enums2.default.MapTypeId.ROADMAP, size: { width: 600, height: 300 }, scale: 1, // 1 | 2 | (4 for business customers of google maps) zoom: 9, marker: 'red', format: _enums2.default.ImageFormat.PNG, language: conf.language || 'en', region: null }, options); var center = _utils2.default.isPlainObject(opts.center) ? opts.center.latitude + ',' + opts.center.longitude : String(opts.center); var size = _utils2.default.isPlainObject(opts.size) ? opts.size.width + 'x' + opts.size.height : String(opts.size); var url = _enums2.default.URL.GOOGLE_SATATIC_MAP // not using utils.setProtocol() here + ('?center=' + center + '&maptype=' + opts.mapTypeId) + ('&size=' + size + '&scale=' + opts.scale + '&zoom=' + opts.zoom) + ('&format=' + opts.format + '&language=' + opts.language); if (opts.marker) { var color = _utils2.default.isString(opts.marker) ? opts.marker : 'red'; url += '&markers=' + encodeURIComponent('color:' + color + '|' + center); } if (opts.region) url += '&region=' + opts.region; if (conf.google.key) url += '&key=' + conf.google.key; var styles = getStyles(opts); if (styles) url += '&' + _geo2.default.mapStylesToParams(styles); if (_utils2.default.isFunction(callback)) return callback(null, url); return url; } /** * Creates an interactive Google Map within the given element. * Make sure you have enabled Google Static Maps API in your Google Developers console. * For static map, see {@link #geolocator.getStaticMap|`geolocator.getStaticMap()` method}. * @see {@link https://developers.google.com/maps/documentation/javascript/reference|Google Maps JavaScript API} * @see {@link https://developers.google.com/maps/documentation/javascript/usage|Usage Limits} * * @param {Object|String|HTMLElement|Map} options * Either map options object with the following properties or; the ID * of a DOM element, or element itself which the map will be * created within; or a previously created `google.maps.Map` instance. * If a map instance is set, this only will apply the options without * re-creating it. * @param {String|HTMLElement|Map} options.element * Either the ID of a DOM element or the element itself; * which the map will be created within; or a previously created * `google.maps.Map` instance. If a map instance is set, this * only will apply the options without re-creating it. * @param {Object} options.center * Center coordinates for the map to be created. * @param {Number} options.center.latitude * Latitude of the center point coordinates. * @param {Number} options.center.longitude * Longitude of the center point coordinates. * @param {String} [options.mapTypeId="roadmap"] * Type of the map to be created. * See {@link #geolocator.MapTypeId|`geolocator.MapTypeId` enumeration} * for possible values. * @param {String} [options.title] * Title text to be displayed within an `InfoWindow`, when the * marker is clicked. This only take effect if `marker` is * enabled. * @param {Boolean} [options.marker=true] * Whether to place a marker at the given coordinates. * If `title` is set, an `InfoWindow` will be opened when the * marker is clicked. * @param {Number} [options.zoom=9] * Zoom level to be set for the map. * @param {Array} [options.styles] * An array of objects to customize the presentation of the * Google base maps, changing the visual display of such * elements as roads, parks, and built-up areas. * This will default to the global styles set via * {@link #geolocator.config|`geolocator.config` method}`, if any. * See {@link https://developers.google.com/maps/documentation/javascript/styling|Styling Maps}. * * @param {Function} callback * Callback function to be executed when the map is created. * This takes 2 arguments: `function (err, map) { ... }`. * See {@link #geolocator~MapData|`geolocator~MapData` type} for details. * * @returns {void} * * @example * var options = { * element: "my-map", * center: { * latitude: 48.8534100, * longitude: 2.3488000 * }, * marker: true, * title: "Paris, France", * zoom: 12 * }; * geolocator.createMap(options, function (err, map) { * if (map && map.infoWindow) { * map.infoWindow.open(map.instance, map.marker); * } * }); */ }, { key: 'createMap', value: function createMap(options, callback) { // if options is not a plain object, consider element ID, `HTMLElement`, // `jQuery` instance or `google.maps.Map` instance. if (!_utils2.default.isPlainObject(options)) { options = { element: options }; } options = _utils2.default.extend({ element: null, mapTypeId: _enums2.default.MapTypeId.ROADMAP, title: undefined, marker: true, zoom: 9 }, options); var e = options.element, elem = void 0; if (_utils2.default.isString(e)) { elem = document.getElementById(e); } else if (_utils2.default.isJQueryObject(e)) { elem = e[0]; } else if (geolocator.isGoogleLoaded() && e instanceof google.maps.Map) { elem = e.getDiv(); } if (!_utils2.default.isElement(elem) && !_utils2.default.isNode(elem)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS, 'A valid DOM element or element ID is required to create a map.'); } if (!_utils2.default.isPlainObject(options.center) || !_utils2.default.isNumber(options.center.latitude) || !_utils2.default.isNumber(options.center.longitude)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS, 'Center coordinates are required to create a map.'); } options.element = elem; var conf = geolocator._.config, key = conf.google.key; options.styles = getStyles(options); geolocator.ensureGoogleLoaded(key, function (err) { if (err) { throw new _geo4.default(_geo4.default.Code.GOOGLE_API_FAILED, String(err.message || err)); } var mapData = configCreateMap(options); callback(null, mapData); }); } /** * Locates the user's location via HTML5 geolocation. This may * require/prompt for user's permission. If the permission is granted we'll * get the most accurate location information. Otherwise, we'll fallback to * locating via user's IP (if enabled). * * For better accuracy, Geolocator implements a different approach than the * `getCurrentPosition` API; which generally triggers before the device's * GPS hardware can provide anything accurate. Thanks to * {@link https://github.com/gwilson/getAccurateCurrentPosition#background|Greg Wilson} * for the idea. * * Also note that HTML5 Geolocation feature no more allows insecure origins. * See {@link https://goo.gl/rStTGz|this} for more details. * This means if you don't call this method from an HTTPS page, it will * fail. And if `options.fallbackToIP` is enabled, this will locate by IP. * * @param {Object} [options] * HTML5 geo-location settings with some additional options. * @param {Boolean} [options.enableHighAccuracy=true] * Specifies whether the device should provide the most accurate * position it can. Note that setting this to `true` might * consume more CPU and/or battery power; and result in slower * response times. * @param {Number} [options.desiredAccuracy=30] * Minimum accuracy desired, in meters. Position will not be * returned until this is met, before the timeout. This only * takes effect if `enableHighAccuracy` is set to `true`. * @param {Number} [options.timeout=5000] * HTML5 position timeout setting in milliseconds. Setting this * to `Infinity` means that Geolocator won't return until the * position is available. * @param {Number} [options.maximumWait=10000] * Maximum time to wait (in milliseconds) for the desired * accuracy (which should be greater than `timeout`). * This only takes effect if `enableHighAccuracy` is set to * `true`. * @param {Number} [options.maximumAge=0] * HTML5 position maximum age. Indicates the maximum age in * milliseconds of a possible cached position that is acceptable * to return. `0` means, the device cannot use a cached position * and must attempt to retrieve the real current position. If set * to `Infinity` the device must return a cached position * regardless of its age. Note that if `enableHighAccuracy` is * set to `true`, `maximumAge` will be forced to `0`. * @param {Function} [options.onProgress] * If `enableHighAccuracy` is set to `true`, you can use this * callback to check the progress of the location accuracy; * while waiting for the final, best accurate location. * @param {Boolean} [options.fallbackToIP=false] * Specifies whether to fallback to IP geolocation if the HTML5 * geolocation fails (e.g. user rejection). * @param {Boolean} [options.addressLookup=false] * Specifies whether to run a reverse-geocode operation for the * fetched coordinates to retrieve detailed address information. * Note that this means an additional request which requires a * Google API key to be set in the Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {Boolean} [options.timezone=false] * Specifies whether to also fetch the time zone information for * the receieved coordinates. Note that this means an additional * request which requires a Google API key to be set in the * Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {String|MapOptions} [options.map] * In order to create an interactive map from the fetched * location coordinates; either set this to a * {@link #geolocator~MapOptions|`MapOptions` object} * or; the ID of a DOM element or DOM element itself which the * map will be created within. * @param {Boolean|Object} [options.staticMap=false] * Set to `true` to get a static Google Map image URL (with * default options); or pass a static map options object. * * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }`. * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {void} * * @example * var options = { * enableHighAccuracy: true, * desiredAccuracy: 30, * timeout: 5000, * maximumWait: 10000, * maximumAge: 0, * fallbackToIP: true, * addressLookup: true, * timezone: true, * map: "my-map", * staticMap: true * }; * geolocator.locate(options, function (err, location) { * console.log(err || location); * }); * * @example * // location result: * { * coords: { * latitude: 37.4224764, * longitude: -122.0842499, * accuracy: 30, * altitude: null, * altitudeAccuracy: null, * heading: null, * speed: null * }, * address: { * commonName: "", * street: "Amphitheatre Pkwy", * route: "Amphitheatre Pkwy", * streetNumber: "1600", * neighborhood: "", * town: "", * city: "Mountain View", * region: "Santa Clara County", * state: "California", * stateCode: "CA", * postalCode: "94043", * country: "United States", * countryCode: "US" * }, * formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA", * type: "ROOFTOP", * placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA", * timezone: { * id: "America/Los_Angeles", * name: "Pacific Standard Time", * abbr: "PST", * dstOffset: 0, * rawOffset: -28800 * }, * flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg", * map: { * element: HTMLElement, * instance: Object, // google.maps.Map * marker: Object, // google.maps.Marker * infoWindow: Object, // google.maps.InfoWindow * options: Object // map options * }, * staticMap: "//maps.googleapis.com/maps/api/staticmap?center=37.4224764,-122.0842499&maptype=roadmap&size=600x300&scale=1&zoom=9&format=png&language=en&markers=color%3Ared%7C37.4224764%2C2-122.0842499&key=YOUR-GOOGLE-API-KEY", * timestamp: 1456795956380 * } */ }, { key: 'locate', value: function locate(options, callback) { options = _utils2.default.extend({ enableHighAccuracy: true, timeout: 5000, maximumWait: 10000, maximumAge: 0, desiredAccuracy: 30, onProgress: _utils2.default.noop, fallbackToIP: false, addressLookup: false, timezone: false, map: undefined, staticMap: false }, options); // force disable cache if high-accuracy is enabled if (options.enableHighAccuracy) options.maximumAge = 0; // set a min value for timeout if (options.timeout < 1000) options.timeout = 1000; // max wait should not be less than timeout if (options.maximumWait < options.timeout) options.maximumWait = options.timeout; // check options and Google key checkGoogleKey(options); var cb = callbackMap(options, callback); function fallbackToIP(error) { if (options.fallbackToIP) { return geolocator.locateByIP(options, function (err, location) { if (err) return cb(err, null); return cb(null, location); }); } cb(error, null); } function onPositionReceived(location) { fetchAddressAndTimezone(location, options, cb); } function onPositionError(err) { err = _geo4.default.create(err); fallbackToIP(err); } if (geolocator.isGeolocationSupported()) { if (options.enableHighAccuracy) { locateAccurate(options, onPositionReceived, onPositionError); } else { navigator.geolocation.getCurrentPosition(onPositionReceived, onPositionError, options); } } else { var err = new _geo4.default(_geo4.default.Code.GEOLOCATION_NOT_SUPPORTED); fallbackToIP(err); } } /** * Returns a location and accuracy radius based on information about cell * towers and WiFi nodes that the mobile client can detect; via the Google * Maps Geolocation API. * @see {@link https://developers.google.com/maps/documentation/geolocation/intro|Google Maps Geolocation API} * @see {@link https://developers.google.com/maps/documentation/geolocation/usage-limits|Usage Limits} * * @param {Object} [options] * Geolocation options. * @param {Number} [options.homeMobileCountryCode] * The mobile country code (MCC) for the device's home network. * @param {Number} [options.homeMobileNetworkCode] * The mobile network code (MNC) for the device's home network. * @param {String} [options.radioType] * The mobile radio type. * See {@link #geolocator.RadioType|`geolocator.RadioType` enumeration} * for possible values. While this field is optional, it should * be included if a value is available, for more accurate results. * @param {string} [options.carrier] * The carrier name. e.g. "Vodafone" * @param {Boolean} [options.fallbackToIP=false] * Specifies whether to fallback to IP geolocation if wifi and * cell tower signals are not available. Note that the IP address * in the request header may not be the IP of the device. Set * `fallbackToIP` to `false` to disable fall back. * @param {Array} [options.cellTowers] * An array of cell tower objects. * See {@link https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object|Cell tower objects} for details. * @param {Array} [options.wifiAccessPoints] * An array of WiFi access point objects. * See {@link https://developers.google.com/maps/documentation/geolocation/intro#wifi_access_point_object|WiFi access point objects} for details. * @param {Boolean} [options.addressLookup=false] * Specifies whether to run a reverse-geocode operation for the * fetched coordinates to retrieve detailed address information. * Note that this means an additional request which requires a * Google API key to be set in the Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {Boolean} [options.timezone=false] * Specifies whether to also fetch the time zone information for * the receieved coordinates. Note that this means an additional * request which requires a Google API key to be set in the * Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {String|MapOptions} [options.map] * In order to create an interactive map from the fetched * location coordinates; either set this to a * {@link #geolocator~MapOptions|`MapOptions` object} * or; the ID of a DOM element or DOM element itself which the * map will be created within. * @param {Boolean|Object} [options.staticMap=false] * Set to `true` to get a static Google Map image URL (with * default options); or pass a static map options object. * @param {Boolean} [options.raw=false] * Whether to return the raw Google API result. * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }`. * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {void} * * @example * var options = { * homeMobileCountryCode: 310, * homeMobileNetworkCode: 410, * carrier: 'Vodafone', * radioType: geolocator.RadioType.GSM, * fallbackToIP: true, * addressLookup: false, * timezone: false, * map: "my-map", * staticMap: false * }; * geolocator.locateByMobile(options, function (err, location) { * console.log(err || location); * }); */ }, { key: 'locateByMobile', value: function locateByMobile(options, callback) { if (!_utils2.default.isPlainObject(options)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS); } var cb = callbackMap(options, callback); options = _utils2.default.extend({ homeMobileCountryCode: undefined, homeMobileNetworkCode: undefined, radioType: undefined, carrier: undefined, fallbackToIP: false, cellTowers: undefined, wifiAccessPoints: undefined, addressLookup: false, timezone: false, map: undefined, raw: false }, options); options.considerIp = options.fallbackToIP; // check Google key checkGoogleKey(); var conf = geolocator._.config, key = conf.google.key || '', url = _utils2.default.setProtocol(_enums2.default.URL.GOOGLE_GEOLOCATION, conf.https), xhrOpts = { url: url + '?key=' + key, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(options) }; // console.log(xhrOpts.data); _fetch2.default.post(xhrOpts, function (err, xhr) { var response = getXHRResponse(err, xhr); if (_geo4.default.isGeoError(response)) return cb(response, null); response = options.raw ? response : { coords: { latitude: response.location.lat, longitude: response.location.lng, accuracy: response.accuracy }, timestamp: _utils2.default.time() }; fetchAddressAndTimezone(response, options, cb); // e.g. raw response // { // "location": { // "lat": 51.0, // "lng": -0.1 // }, // "accuracy": 1200.4 // } }); } /** * Locates the user's location by the client's IP. * * This method uses FreeGeoIP's lookup service, by default. * In order to change the source provider, you can use * {@link #geolocator.setGeoIPSource|`geolocator.setGeoIPSource()` method}. * * @param {Object} [options] * Locate options. * @param {Boolean} [options.addressLookup=false] * Specifies whether to run a reverse-geocode operation for the * fetched coordinates to retrieve detailed address information. * Since no precise address can be fetched from an IP addres; you * should only enable this if the Geo-IP Source returns no useful * address information other than coordinates. Also, note that * this means an additional request which requires a Google API * key to be set in the Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {Boolean} [options.timezone=false] * Specifies whether to also fetch the time zone information for * the receieved coordinates. Note that this means an additional * request which requires a Google API key to be set in the * Geolocator configuration. * See {@link #geolocator.config|`geolocator.config()`}. * @param {String|MapOptions} [options.map] * In order to create an interactive map from the fetched * location coordinates; either set this to a * {@link #geolocator~MapOptions|`MapOptions` object} * or; the ID of a DOM element or DOM element itself which the * map will be created within. * @param {Boolean|Object} [options.staticMap=false] * Set to `true` to get a static Google Map image URL (with * default options); or pass a static map options object. * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }`. * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {void} * * @example * var options = { * addressLookup: true, * timezone: true, * map: "my-map", * staticMap: true * }; * geolocator.locateByIP(options, function (err, location) { * console.log(err || location); * }); * * @example * // location result: * { * coords: { * latitude: 41.0214, * longitude: 28.9948, * }, * address: { * city: "Istanbul", * region: "34", * state: "34", * country: "Turkey", * countryCode: "TR" * }, * formattedAddress: "Demirtaş, Tesviyeci Sk. No:7, 34134 Fatih/İstanbul, Turkey", * type: "ROOFTOP", * placeId: "ChIJ-ZRLfO25yhQRBi5YJxX80Q0", * timezone: { * id: "Europe/Istanbul", * name: "Eastern European Summer Time", * abbr: "EEST", * dstOffset: 3600, * rawOffset: 7200 * }, * flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/tr.svg", * map: { * element: HTMLElement, * instance: Object, // google.maps.Map * marker: Object, // google.maps.Marker * infoWindow: Object, // google.maps.InfoWindow * options: Object // map options * }, * staticMap: "//maps.googleapis.com/maps/api/staticmap?center=41.0214,28.9948&maptype=roadmap&size=600x300&scale=1&zoom=9&format=png&language=en&markers=color%3Ared%7C41.0214%2C228.9948&key=YOUR-GOOGLE-API-KEY", * provider: "freegeoip", * timestamp: 1466216325223 * } */ }, { key: 'locateByIP', value: function locateByIP(options, callback) { // passed source can be a string or object var source = geolocator._.geoIpSource; if (!_utils2.default.isPlainObject(source)) { throw new _geo4.default(_geo4.default.Code.INVALID_GEO_IP_SOURCE, 'Please set a valid Geo-IP Source via geolocator.setGeoIPSource(options).'); } // check options and Google key checkGoogleKey(options || {}); var jsonpOpts = { url: source.url, async: true, clean: true // params: {} }; if (source.callbackParam) { jsonpOpts.callbackParam = source.callbackParam; jsonpOpts.rootName = 'geolocator._.cb'; } else if (!source.globalVar) { throw new _geo4.default(_geo4.default.Code.INVALID_GEO_IP_SOURCE, 'Either callbackParam or globalVar should be set for Geo-IP source.'); } return _fetch2.default.jsonp(jsonpOpts, function (err, response) { if (err) { return callback(_geo4.default.create(err), null); } if (source.globalVar) { if (window[source.globalVar]) { response = _utils2.default.clone(window[source.globalVar]); delete window[source.globalVar]; } else { response = null; } } if (!response) { err = new _geo4.default(_geo4.default.Code.INVALID_RESPONSE); return callback(err, null); } if (_utils2.default.isPlainObject(source.schema)) { response = _utils2.default.mapToSchema(response, source.schema); } response.provider = source.provider || 'unknown'; setLocationURLs(response, options); if (response.coords) { response.coords.latitude = Number(response.coords.latitude); response.coords.longitude = Number(response.coords.longitude); } var cb = callbackMap(options, callback); fetchAddressAndTimezone(response, options, cb); }); } /** * Sets the Geo-IP source to be used for fetching location information * by user's IP; which is internally used by * {@link #geolocator.locateByIP|`geolocator.locateByIP()` method}. * * By default, Geolocator uses FreeGeoIP as the Geo-IP source provider. * You can use this method to change this; or you can choose from * ready-to-use * {@link https://github.com/onury/geolocator/tree/master/src/geo-ip-sources|Geo-IP sources}. * * @param {Object} options * Geo-IP Source options. * @param {String} [options.provider] * Source or service provider's name. * @param {String} options.url * Source URL without the callback query parameter. The callback * name (if supported) should be set via `options.callbackParam`. * Also, make sure the service supports the protocol you use in * the enums.URL. If it supports both HTTP and HTTPS, you can omit the * protocol. In this case, it will be determined via Geolocator * configuration. * See {@link #geolocator.config|`geolocator.config()`}. * NOTE: Do not forget to include your API key in the query * parameters of the URL, if you have one. * @param {String} [options.callbackParam] * If JSON callback is supported, pass the name of the callback * parameter, defined by the provider. * @param {Object} [options.globalVar] * Set this instead of `options.callbackParam` if the service * does not support JSON callbacks, but weirdly set a global * variable in the document. For example, if the response is * `Geo = { lat, lng }`, you should set this to `"Geo"`. * @param {Object} [options.schema] * Schema object to be used to re-structure the response returned * from the service. Set the response object's keys as values of * a custom object to map the format to the `location` object. * For example; if the service returns a response like * `{ lat: 40.112233, lng: 10.112233, otherProp: 'hello' }`. * Then you should set the following schema: * `{ coords: { latitude: 'lat', longitude: 'lng' } }`. * * @return {geolocator} */ }, { key: 'setGeoIPSource', value: function setGeoIPSource(options) { if (!_utils2.default.isPlainObject(options)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS, 'Geo-IP source options is invalid.'); } if (!_utils2.default.isStringSet(options.url)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS, 'Geo-IP source should have a valid URI.'); } // if (!utils.isStringSet(options.callbackParam) && !utils.isStringSet(options.globalVar)) { // throw new GeoError(GeoError.Code.INVALID_PARAMETERS, 'No \'callbackParam\' or \'globalVar\' is provided for the Geo-IP Source options.'); // } geolocator._.geoIpSource = Object.freeze(options); } /** * Registers a handler for watching the user's location via HTML5 * geolocation; that is triggered each time the position of the device * changes. This may require/prompt for user's permission. * * @param {Object} [options] * HTML5 geo-location settings. * @param {Boolean} [options.enableHighAccuracy=true] * Specifies whether the device should provide the most accurate * position it can. Note that setting this to `true` might consume * more CPU and/or battery power; and result in slower response * times. * @param {Number} [options.timeout=6000] * HTML5 position timeout setting in milliseconds. Setting this * to `Infinity` means that Geolocator won't return until the * position is available. * @param {Number} [options.maximumAge=0] * HTML5 position maximum age. Indicates the maximum age in * milliseconds of a possible cached position that is acceptable * to return. `0` means, the device cannot use a cached position * and must attempt to retrieve the real current position. If set * to `Infinity` the device must return a cached position * regardless of its age. * @param {Boolean} [options.clearOnError=false] * Specifies whether to clear the watcher on first error so that * it does not execute any more callbacks. * @param {Object} [options.target] * Object that defines the target location and settings; that * when the location is reached, the watcher will auto-clear * itself and invoke the callback. * @param {Number} options.target.latitude * The `latitude` of the target location. * @param {Number} options.target.longitude * The `longitude` of the target location. * @param {Number} [options.target.radius=0.5] * The radius, in other words; the minimum distance (in * kilometers or miles) to the target point that should be * reached. * @param {Number} [options.target.unitSystem=0] * Unit system to be used for target radius. * See {@link #geolocator.UnitSystem|`geolocator.UnitSystem` enumeration} * for possible values. * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }`. * If `options.target` is set, `location` will also * include a `targetReached:Boolean` property. * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {GeoWatcher} - A watcher object that provides a * `.clear(delay:Number, callback:Function)` method to clear the watcher * when needed. Optional `delay` argument can be set (in milliseconds) to * clear in a later time. Omitting this argument will clear the watcher * immediately. You should always call this method, except if you've set up * a target; which will auto-clear the watcher when reached. * * @example * // Watch my position for 5 minutes. * var options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 }; * var watcher = geolocator.watch(options, function (err, location) { * console.log(err || location); * }); * console.log(watcher.id); // ID of the watcher * watcher.clear(300000); // clear after 5 minutes. * * @example * // Watch my position until I'm 350 meters near Disneyland Park. * options.target = { * latitude: 33.8120918, * longitude: -117.9233569, * radius: 0.35, * unitSystem: geolocator.UnitSystem.METRIC * }; * watcher = geolocator.watch(options, function (err, location) { * if (err) { * console.log(err); * return; * } * if (location.targetReached) { * console.log(watcher.isCleared); // true * console.log(watcher.cycle); // 15 — target reached after 15 cycles * } else { * console.log(watcher.isCleared); // false — watcher is active. * } * }); */ }, { key: 'watch', value: function watch(options, callback) { if (!geolocator.isGeolocationSupported()) { callback(new _geo4.default(_geo4.default.Code.GEOLOCATION_NOT_SUPPORTED), null); return {}; } var watcher = void 0, target = void 0; options = _utils2.default.extend({ enableHighAccuracy: true, timeout: 6000, maximumAge: 0, clearOnError: false }, options); if (_utils2.default.isPlainObject(options.target)) { target = _utils2.default.extend({ radius: 0.5, unitSystem: geolocator.UnitSystem.METRIC }, options.target); } function onPositionChanged(location) { var pos = _utils2.default.clone(location, { own: false }); if (target) { var distance = geolocator.calcDistance({ from: location.coords, to: target, formula: geolocator.DistanceFormula.HAVERSINE, unitSystem: target.unitSystem }); pos.targetReached = distance <= target.radius; if (watcher && pos.targetReached) { watcher.clear(function () { return callback(null, pos); }); } } return callback(null, pos); } function onPositionError(err) { callback(_geo4.default.create(err), null); } return new _geo6.default(onPositionChanged, onPositionError, options); } /** * Converts a given address (or address components) into geographic * coordinates (i.e. latitude, longitude); and gets detailed address * information. * @see {@link https://developers.google.com/maps/documentation/geocoding/intro|Google Maps Geocoding API} * @see {@link https://developers.google.com/maps/documentation/geocoding/usage-limits|Usage Limits} * * @param {String|Object} options * Either the address to geocode or geocoding options with the * following properties. * @param {String} options.address * The street address to geocode, in the format used by the * national postal service of the country concerned. Additional * address elements such as business names and unit, suite or * floor numbers should be avoided. Note that any address * component (route, locality, administrativeArea, postalCode and * country) should be specified either in address or the * corresponding property - not both. Doing so may result in * `ZERO_RESULTS`. * @param {String} [options.route] * Long or short name of a route. * @param {String} [options.locality] * Locality and sublocality of the location. * @param {String} [options.administrativeArea] * Administrative area of the location. * @param {String} [options.postalCode] * Postal code of the location. * @param {String} [options.country] * A country name or a two letter ISO 3166-1 country code. * @param {String} [options.region] * The region code, specified as a ccTLD ("top-level domain") * two-character value. e.g.: `"fr"` for France. * @param {Array|Object} [options.bounds] * The bounding box of the viewport within which to bias geocode * results more prominently. e.g.: * `[ southwestLat:Number, southwestLng:Number, northeastLat:Number, northeastLng:Number ]` * @param {String|MapOptions} [options.map] * In order to create an interactive map from the fetched * location coordinates; either set this to a * {@link #geolocator~MapOptions|`MapOptions` object} * or; the ID of a DOM element or DOM element itself which the * map will be created within. * @param {Boolean|Object} [options.staticMap=false] * Set to `true` to get a static Google Map image URL (with * default options); or pass a static map options object. * @param {Boolean} [options.raw=false] * Whether to return the raw Google API result. * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }`. * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {void} * * @example * var address = '1600 Amphitheatre Parkway, CA'; * geolocator.geocode(address, function (err, location) { * console.log(err || location); * }); * * @example * // location result: * { * coords: { * latitude: 37.4224764, * longitude: -122.0842499 * }, * address: { * commonName: "", * street: "Amphitheatre Pkwy", * route: "Amphitheatre Pkwy", * streetNumber: "1600", * neighborhood: "", * town: "", * city: "Mountain View", * region: "Santa Clara County", * state: "California", * stateCode: "CA", * postalCode: "94043", * country: "United States", * countryCode: "US" * }, * formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA", * type: "ROOFTOP", * placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA", * flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg", * map: { * element: HTMLElement, * instance: Object, // google.maps.Map * marker: Object, // google.maps.Marker * infoWindow: Object, // google.maps.InfoWindow * options: Object // map options * }, * timestamp: 1456795956380 * } */ }, { key: 'geocode', value: function geocode(options, callback) { _geocode(false, options, callback); } /** * Converts the given geographic coordinates into a human-readable address * information. * @see {@link https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding|Google Maps (Reverse) Geocoding API} * @see {@link https://developers.google.com/maps/documentation/geocoding/usage-limits|Usage Limits} * @alias geolocator.addressLookup * * @param {Object|String} options * Either the `placeId` of the location or Reverse Geocoding options * with the following properties. * @param {Number} options.latitude * Latitude of the target location. * @param {Number} options.longitude * Longitude of the target location. * @param {String} [options.placeId] * Required if `latitude` and `longitude` are omitted. The place * ID of the place for which you wish to obtain the * human-readable address. The place ID is a unique identifier * that can be used with other Google APIs. Note that if * `placeId` is set, `latitude` and `longitude` are ignored. * @param {String|MapOptions} [options.map] * In order to create an interactive map from the fetched * location coordinates; either set this to a * {@link #geolocator~MapOptions|`MapOptions` object} * or; the ID of a DOM element or DOM element itself which the * map will be created within. * @param {Boolean|Object} [options.staticMap=false] * Set to `true` to get a static Google Map image URL (with * default options); or pass a static map options object. * @param {Boolean} [options.raw=false] * Whether to return the raw Google API result. * @param {Function} callback * Callback function to be executed when the request completes. * This takes 2 arguments: `function (err, location) { ... }` * See {@link #geolocator~Location|`geolocator~Location` type} for details. * * @returns {void} * * @example * var coords = { * latitude: 37.4224764, * longitude: -122.0842499 * }; * * geolocator.reverseGeocode(coords, function (err, location) { * console.log(err || location); * }); * * @example * // location result: * { * coords: { * latitude: 37.4224764, * longitude: -122.0842499 * }, * address: { * commonName: "", * street: "Amphitheatre Pkwy", * route: "Amphitheatre Pkwy", * streetNumber: "1600", * neighborhood: "", * town: "", * city: "Mountain View", * region: "Santa Clara County", * state: "California", * stateCode: "CA", * postalCode: "94043", * country: "United States", * countryCode: "US" * }, * formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA", * type: "ROOFTOP", * placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA", * flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg", * map: { * element: HTMLElement, * instance: Object, // google.maps.Map * marker: Object, // google.maps.Marker * infoWindow: Object, // google.maps.InfoWindow * options: Object // map options * }, * timestamp: 1456795956380 * } */ }, { key: 'reverseGeocode', value: function reverseGeocode(options, callback) { _geocode(true, options, callback); } /** * Alias for `geolocator.reverseGeocode` * @private */ }, { key: 'addressLookup', value: function addressLookup(options, callback) { geolocator.reverseGeocode(options, callback); } /** * Gets timezone information for the given coordinates. * Note: Google Browser API keys cannot have referer restrictions when used with this API. * @see {@link https://developers.google.com/maps/documentation/timezone/intro|Google Maps TimeZone API} * @see {@link https://developers.google.com/maps/documentation/timezone/usage-limits|Usage Limits} * * @param {Object} options * Time zone options. * @param {Number} options.latitude * Latitude of location. * @param {Number} options.longitude * Longitude of location. * @param {Number} [options.timestamp=Date.now()] * Specifies the desired time as seconds since midnight, January * 1, 1970 UTC. This is used to determine whether or not Daylight * Savings should be applied. * @param {Boolean} [options.raw=false] * Whether to return the raw Google API result. * @param {Function} callback * Callback function to be executed when the request completes, in * the following signature: `function (err, timezone) { ... }`. * See {@link #geolocator~TimeZone|`geolocator~TimeZone` type} for * details. * * @returns {void} * * @example * var options = { * latitude: 48.8534100, * longitude: 2.3488000 * }; * geolocator.getTimeZone(options, function (err, timezone) { * console.log(err || timezone); * }); * * @example * // timezone result: * { * id: "Europe/Paris", * name: "Central European Standard Time", * abbr: "CEST", * dstOffset: 0, * rawOffset: 3600, * timestamp: 1455733120 * } */ }, { key: 'getTimeZone', value: function getTimeZone(options, callback) { if (!_utils2.default.isPlainObject(options) || !_utils2.default.isNumber(options.latitude) || !_utils2.default.isNumber(options.longitude)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS); } checkGoogleKey(); var conf = geolocator._.config; options = _utils2.default.extend({ key: conf.google.key || '', language: conf.language || 'en', timestamp: _utils2.default.time(true), raw: false }, options); var url = _utils2.default.setProtocol(_enums2.default.URL.GOOGLE_TIMEZONE, conf.https), xhrOpts = { url: url + '?location=' + options.latitude + ',' + options.longitude + '&timestamp=' + options.timestamp + '&language=' + options.language + '&key=' + options.key }; _fetch2.default.xhr(xhrOpts, function (err, xhr) { var response = getXHRResponse(err, xhr); if (_geo4.default.isGeoError(response)) return callback(response, null); response = options.raw ? response : { id: response.timeZoneId, name: response.timeZoneName, abbr: _utils2.default.abbr(response.timeZoneName, { dots: false }), dstOffset: response.dstOffset, rawOffset: response.rawOffset, timestamp: options.timestamp }; callback(err, response); }); } /** * Gets the distance and duration values based on the recommended route * between start and end points. * @see {@link https://developers.google.com/maps/documentation/distance-matrix/intro|Google Maps Distance Matrix API} * @see {@link https://developers.google.com/maps/documentation/distance-matrix/usage-limits|Usage Limits} * * @param {Object} options * Distance matrix options. * @param {String|Object|Array} options.origins * One or more addresses and/or an object of latitude/longitude * values, from which to calculate distance and time. If you pass * an address as a string, the service will geocode the string * and convert it to a latitude/longitude coordinate to calculate * distances. Following are valid examples: * <pre><code>options.origins = 'London'; * options.origins = ['London', 'Paris']; * options.origins = { latitude: 51.5085300, longitude: -0.1257400 }; * options.origins = [ * { latitude: 51.5085300, longitude: -0.1257400 }, * { latitude: 48.8534100, longitude: 2.3488000 } * ]; * </code></pre> * @param {String|Object|Array} options.destinations * One or more addresses and/or an object of latitude/longitude * values, from which to calculate distance and time. If you pass * an address as a string, the service will geocode the string * and convert it to a latitude/longitude coordinate to calculate * distances. * @param {String} [options.travelMode="DRIVING"] * Type of routing requested. * See {@link #geolocator.TravelMode|`geolocator.TravelMode` enumeration} * for possible values. * @param {Boolean} [options.avoidFerries] * If true, instructs the Distance Matrix service to avoid * ferries where possible. * @param {Boolean} [options.avoidHighways] * If true, instructs the Distance Matrix service to avoid * highways where possible. * @param {Boolean} [options.avoidTolls] * If true, instructs the Distance Matrix service to avoid toll * roads where possible. * @param {Number} [options.unitSystem=0] * Preferred unit system to use when displaying distance. * See {@link #geolocator.UnitSystem|`geolocator.UnitSystem` enumeration} * for possible values. * @param {String} [options.region] * Region code used as a bias for geocoding requests. * @param {Boolean} [options.raw=false] * Whether to return the raw Google API result. * @param {Function} callback * Callback function to be executed when the request completes, * in the following signature: `function (err, result) { ... }` * * @returns {void} * * @example * var options = { * origins: [{ latitude: 51.5085300, longitude: -0.1257400 }], * destinations: [{ latitude: 48.8534100, longitude: 2.3488000 }], * travelMode: geolocator.TravelMode.DRIVING, * unitSystem: geolocator.UnitSystem.METRIC * }; * geolocator.getDistanceMatrix(options, function (err, result) { * console.log(err || result); * }); * * @example * // result: * [ * { * from: "449 Duncannon St, London WC2R 0DZ, UK", * to: "1 Parvis Notre-Dame - Pl. Jean-Paul II, 75004 Paris-4E-Arrondissement, France", * distance: { * value: 475104, * text: "475 km" * }, * duration: { * value: 20193, * text: "5 hours 37 mins" * }, * fare: undefined, * timestamp: 1456795956380 * } * ] */ }, { key: 'getDistanceMatrix', value: function getDistanceMatrix(options, callback) { checkGoogleKey(); var key = geolocator._.config.google.key; geolocator.ensureGoogleLoaded(key, function (err) { if (err) { throw new _geo4.default(_geo4.default.Code.GOOGLE_API_FAILED, String(err.message || err)); } var o = options.origins || options.origin || options.from, d = options.destinations || options.destination || options.to; if (!_utils2.default.isPlainObject(options) || invalidOriginOrDest(o) || invalidOriginOrDest(d)) { throw new _geo4.default(_geo4.default.Code.INVALID_PARAMETERS); } options.origins = _geo2.default.toPointList(o); options.destinations = _geo2.default.toPointList(d); options = _utils2.default.extend({ travelMode: google.maps.TravelMode.DRIVING, avoidFerries: undefined, avoidHighways: undefined, avoidTolls: undefined, unitSystem: google.maps.UnitSystem.METRIC }, options); var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix(options, function (response, status) { var err = null; if (status !== google.maps.DistanceMatrixStatus.OK) { err = _geo4.default.fromResponse(status) || _geo4.default.fromResponse(response); response = null; } else { response = options.raw ? response : _geo2.default.formatDistanceResults(response); } callback(err, response); }); }); } /** * Calculates the distance between two geographic points. * * @param {Object} options * Calculation and display options. * @param {Object} options.from * Object containing the `latitude` and `longitude` of original * location. * @param {Object} options.to * Object containing the `latitude` and `longitude` of destination. * @param {String} [options.formula="haversine"] * The algorithm or formula to calculate the distance. * See {@link #geolocator.DistanceFormula|`geolocator.DistanceFormula` enumeration}. * @param {Number} [options.unitSystem=0] * Preferred unit system to use when displaying distance. * See {@link #geolocator.UnitSystem|`geolocator.UnitSystem` enumeration}. * * @returns {Number} - The calculated distance. * * @example * // Calculate distance from London to Paris. * var result = geolocator.calcDistance({ * from: { * latitude: 51.5085300, * longitude: -0.1257400 * }, * to: { * latitude: 48.8534100, * longitude: 2.3488000 * }, * formula: geolocator.DistanceFormula.HAVERSINE, * unitSystem: geolocator.UnitSystem.METRIC * }); * // result: 366.41656039126093 (kilometers) */ }, { key: 'calcDistance', value: function calcDistance(options) { options = _utils2.default.extend({ formula: geolocator.DistanceFormula.HAVERSINE, unitSystem: geolocator.UnitSystem.METRIC }, options); var from = options.from, to = options.to, radius = options.unitSystem === geolocator.UnitSystem.METRIC ? EARTH_RADIUS_KM : EARTH_RADIUS_MI; if (options.formula === geolocator.DistanceFormula.HAVERSINE) { var dLat = geolocator.degToRad(to.latitude - from.latitude), dLng = geolocator.degToRad(to.longitude - from.longitude), a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(geolocator.degToRad(from.latitude)) * Math.cos(geolocator.degToRad(to.longitude)) * Math.sin(dLng / 2) * Math.sin(dLng / 2), c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return radius * c; } // geolocator.DistanceFormula.PYTHAGOREAN var latA = geolocator.degToRad(from.latitude), latB = geolocator.degToRad(to.latitude), lngA = geolocator.degToRad(from.longitude), lngB = geolocator.degToRad(to.longitude), x = (lngB - lngA) * Math.cos((latA + latB) / 2), y = latB - latA; return Math.sqrt(x * x + y * y) * radius; } /** * Gets the current public IP of the client. * * @param {Function} callback * Callback function to be executed when the request completes, in * the following signature: `function (err, result) { ... }` * * @returns {void} * * @example * geolocator.getIP(function (err, result) { * console.log(err || result); * }); * * @example * // result: * { * ip: "176.232.71.155", * timestamp: 1457573683427 * } */ }, { key: 'getIP', value: function getIP(callback) { var conf = geolocator._.config; var jsonpOpts = { url: _utils2.default.setProtocol(_enums2.default.URL.IP, conf.https), async: true, clean: true, params: { format: 'jsonp' }, callbackParam: 'callback', rootName: 'geolocator._.cb' }; return _fetch2.default.jsonp(jsonpOpts, function (err, response) { if (err) { return callback(_geo4.default.create(err), null); } if (!response) { err = new _geo4.default(_geo4.default.Code.INVALID_RESPONSE); return callback(err, null); } if ((typeof response === 'undefined' ? 'undefined' : _typeof(response)) === 'object') response.timestamp = _utils2.default.time(); callback(null, response); }); } /** * Ensures Google Maps API is loaded. If not, this will load all of the * main Javascript objects and symbols for use in the Maps API. * * Note that, Google Maps API is loaded only when needed. For example, * the DistanceMatrix API does not support Web Service requests and * requires this API to be loaded. However, the TimeZone API requests are * made throught the Web Service without requiring a `google` object * within DOM. * * Also note that this will not re-load the API if `google.maps` object * already exists. In this case, the `callback` is still executed and * no errors are passed. * * You can use the following overload to omit the `key` argument altogether: * * `geolocator.ensureGoogleLoaded(callback)` * * @param {String} [key] * Google API key. * @param {Function} callback * Callback function to be executed when the operation ends. * * @returns {void} * * @example * geolocator.ensureGoogleLoaded(function (err) { * if (err) return; * console.log('google' in window); // true * }); */ }, { key: 'ensureGoogleLoaded', value: function ensureGoogleLoaded(key, callback) { var k = void 0; if (_utils2.default.isFunction(key)) { callback = key; } else { k = key; } if (!geolocator.isGoogleLoaded()) { var jsonpOpts = { url: _enums2.default.URL.GOOGLE_MAPS_API, async: true, callbackParam: 'callback', params: { key: k || '' // callback: '' }, rootName: 'geolocator._.cb' }; return _fetch2.default.jsonp(jsonpOpts, callback); } callback(); } /** * Checks whether the Google Maps API is loaded. * * @returns {Boolean} - Returns `true` if already loaded. */ }, { key: 'isGoogleLoaded', value: function isGoogleLoaded() { return 'google' in window && google.maps; } /** * Checks whether the type of the given object is an HTML5 `PositionError`. * * @param {*} obj - Object to be checked. * @return {Boolean} */ }, { key: 'isPositionError', value: function isPositionError(obj) { return _utils2.default.isPositionError(obj); } /** * Checks whether the given value is an instance of `GeoError`. * * @param {*} obj - Object to be checked. * @return {Boolean} */ }, { key: 'isGeoError', value: function isGeoError(obj) { return _geo4.default.isGeoError(obj); } /** * Checks whether HTML5 Geolocation API is supported. * * @return {Boolean} */ }, { key: 'isGeolocationSupported', value: function isGeolocationSupported() { return navigator && 'geolocation' in navigator; } /** * Converts kilometers to miles. * * @param {Number} km - Kilometers to be converted. * @returns {Number} - Miles. */ }, { key: 'kmToMi', value: function kmToMi(km) { return km * 0.621371; } /** * Converts miles to kilometers. * * @param {Number} mi - Miles to be converted. * @returns {Number} - Kilometers. */ }, { key: 'miToKm', value: function miToKm(mi) { return mi / 0.621371; } /** * Converts degrees to radians. * * @param {Number} deg - Degrees to be converted. * @returns {Number} - Radians. */ }, { key: 'degToRad', value: function degToRad(degrees) { return degrees * (Math.PI / 180); } /** * Converts radians to degrees. * * @param {Number} rad - Radians to be converted. * @returns {Number} - Degrees. */ }, { key: 'radToDeg', value: function radToDeg(radians) { return radians * (180 / Math.PI); } /** * Converts decimal coordinates (either lat or lng) to degrees, minutes, seconds. * * @param {Number} dec * Decimals to be converted. * @param {Boolean} [isLng=false] * Indicates whether the given decimals is longitude. * * @returns {String} - Degrees, minutes, seconds. */ }, { key: 'decToDegMinSec', value: function decToDegMinSec(dec) { var isLng = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; // Degrees Latitude must be in the range of -90. to 90. // Degrees Longitude must be in the range of -180 to 180. // +Latitude is North, -Latitude is South // +Longitude is East, -Longitude is West var sign = dec < 0 ? -1 : 1, sn = dec < 0 ? 'S' : 'N', we = dec < 0 ? 'W' : 'E', nsew = !isLng ? sn : we, absValue = Math.abs(Math.round(dec * 1000000.0)); return Math.floor(absValue / 1000000) * sign + '° ' + Math.floor((absValue / 1000000 - Math.floor(absValue / 1000000)) * 60) + '\' ' + Math.floor(((absValue / 1000000 - Math.floor(absValue / 1000000)) * 60 - Math.floor((absValue / 1000000 - Math.floor(absValue / 1000000)) * 60)) * 100000) * 60 / 100000 + '" ' + nsew; } }, { key: 'Error', // --------------------------- // PROPERTIES // --------------------------- /** * Geolocator Error class that provides a common type of error object for * the various APIs implemented in Geolocator. All callbacks of Geolocator * will include an instance of this object as the first argument; if the * corresponding operation fails. Also all thrown errors will be an instance * of this object. * * This object also enumerates * {@link ?api=geolocator-error#GeoError.Code|Geolocator Error codes}. * * @see {@link ?api=geolocator-error|`GeoError` documentation} * @type {GeoError} * @readonly */ get: function get() { return _geo4.default; } /** * Documented separately in enums.js * @private */ }, { key: 'MapTypeId', get: function get() { return _enums2.default.MapTypeId; } /** * Documented separately in enums.js * @private */ }, { key: 'LocationType', get: function get() { return _enums2.default.LocationType; } /** * Documented separately in enums.js * @private */ }, { key: 'TravelMode', get: function get() { return _enums2.default.TravelMode; } /** * Documented separately in enums.js * @private */ }, { key: 'UnitSystem', get: function get() { return _enums2.default.UnitSystem; } /** * Documented separately in enums.js * @private */ }, { key: 'RadioType', get: function get() { return _enums2.default.RadioType; } /** * Documented separately in enums.js * @private */ }, { key: 'DistanceFormula', get: function get() { return _enums2.default.DistanceFormula; } /** * Documented separately in enums.js * @private */ }, { key: 'ImageFormat', get: function get() { return _enums2.default.ImageFormat; } }]); return geolocator; }(); // --------------------------- // HELPER METHODS // --------------------------- /** * Used with distance matrix calls. * @private */ function invalidOriginOrDest(value) { return !_utils2.default.isString(value) && !_utils2.default.isArray(value) && !_utils2.default.isPlainObject(value); } /** * Check if XHR response is an error response and returns a `GeoError`. * If not, returns the parsed response. * @private * * @param {Error} err * XHR error. * @param {Object} xhr * XHR object to be checked. * * @returns {GeoError|Object} */ function getXHRResponse(err, xhr) { if (err) return _geo4.default.create(err); if (!xhr) return new _geo4.default(_geo4.default.Code.REQUEST_FAILED); var response = _utils2.default.safeJsonParse(xhr.responseText); // Check if XHR response is an error response. // return response if not. return _geo4.default.fromResponse(response) || response; } /** * Checks the given options and determines if Google key is required. * Throws if key is required but not set or valid. * @private * * @param {Object} [options] * Options to be checked. If `undefined`, directly checks Googke key. */ function checkGoogleKey(options) { if (!options || options.addressLookup || options.timezone || options.map || options.staticMap) { if (!geolocator._.config.google.key) { throw new _geo4.default(_geo4.default.Code.GOOGLE_KEY_INVALID, 'A Google API key is required but it\'s not set or valid.'); } } } /** * Checks and adds necessary properties to map options from the given location * result object. This is used with methods that support `map` option; to * create a map from the result coordinates; such as locate() method. * @private * * @param {Object|String} options * Original options object. * @param {Object} location * Location result object. * * @returns {Object} - Final map options object. */ function getMapOpts(mapOptions, location) { if (_utils2.default.isObject(mapOptions)) { mapOptions.center = location.coords; } else { mapOptions = { element: mapOptions, center: location.coords }; } // this will enable infoWindow if (location.formattedAddress) { mapOptions.title = location.formattedAddress; } // if location has accuracy, (and zoom is not set) we can zoom in a bit more if (!mapOptions.zoom && location.coords && _utils2.default.isNumber(location.coords.accuracy) && location.coords.accuracy < 1500) { mapOptions.zoom = 15; } return mapOptions; } /** * Checks the HTMLElement to see whether a previous map and related objects * (marker, infoWindow) are created for it; by checking our private property * `_geolocatorMapData`. If there is a map, this does not re-create it (which * will break the map) but only re-adjust center, zoom and re-create the marker * if needed. We use this approach bec. Google maps has no feature to destroy * a map. This is considered a bug by Google developers. * @private * * @param {Object} options * Options for creating a map. */ function configCreateMap(options) { var elem = options.element, // when geolocator creates a map, it will set a `_geolocatorMapData` // property on the element. So we can use this map instance later, // when the same HTMLElement is passed to create a map. So check if // we have it here. mapData = elem._geolocatorMapData, map = mapData && mapData.instance || null, marker = mapData && mapData.marker || null, infoWindow = mapData && mapData.infoWindow || null, center = new google.maps.LatLng(options.center.latitude, options.center.longitude), mapOptions = { mapTypeId: options.mapTypeId, center: center, zoom: options.zoom, styles: options.styles || null }; // if we have a map, we'll just configure it. otherwise, we'll create // one. if (map) { map.setOptions(mapOptions); } else { map = new google.maps.Map(options.element, mapOptions); } // destroy marker and infoWindow if previously created for this element. if (infoWindow) infoWindow = null; if (marker && marker instanceof google.maps.Marker) { google.maps.event.clearInstanceListeners(marker); marker.setMap(null); marker = null; } // check the new options to see if we need to re-create a marker for // this. if (options.marker) { marker = new google.maps.Marker({ position: mapOptions.center, map: map }); if (options.title) { infoWindow = new google.maps.InfoWindow(); infoWindow.setContent(options.title); // infoWindow.open(map, marker); google.maps.event.addListener(marker, 'click', function () { infoWindow.open(map, marker); }); } } mapData = { element: elem, instance: map, marker: marker, infoWindow: infoWindow, options: mapOptions }; // set the reference on the element for later use, if needed. elem._geolocatorMapData = mapData; return mapData; } /** * Sets the `flag` and `staticMap` (if enabled) property of the given location. * @private * * @param {Object} location - Fetched location result. * @param {Object} options - initial options. */ function setLocationURLs(location, options) { if (!location || !location.address) return; var cc = void 0, address = location.address; if (_utils2.default.isString(address.countryCode) && address.countryCode.length === 2) { cc = address.countryCode; } else if (_utils2.default.isString(address.country) && address.country.length === 2) { cc = address.country; } if (!cc) return; location.flag = _enums2.default.URL.FLAG + cc.toLowerCase() + '.svg'; if (options.staticMap) { var opts = _utils2.default.isPlainObject(options.staticMap) ? _utils2.default.clone(options.staticMap) : {}; opts.center = location.coords; location.staticMap = geolocator.getStaticMap(opts); } } /** * Nests `createMap` callback within the given callback. * @private * * @param {Object} options * Method options. * @param {Function} callback * Parent callback. * * @returns {Function} - Nested callback. */ function callbackMap(options, callback) { return function cb(err, location) { if (err) return callback(_geo4.default.create(err), null); setLocationURLs(location, options); if (!options.map) return callback(null, location); options.map = getMapOpts(options.map, location); geolocator.createMap(options.map, function (error, map) { if (error) return callback(error, null); location.map = map; return callback(null, location); }); }; } /** * Sends a geocode or reverse-geocode request with the given options. * @private * * @param {Boolean} reverse * Whether to send reverse-geocode request. * @param {Object} options * Geocode options. * @param {Function} callback * Callback to be nested and executed with map callback. */ function _geocode(reverse, options, callback) { checkGoogleKey(); _geo2.default.geocode(reverse, geolocator._.config, options, callbackMap(options, callback)); } /** * Runs both an address and a timezone look-up for the given location. * @private * * @param {Object} location * Location object. * @param {Object} options * Method options. * @param {Function} callback * Parent callback. */ function fetchAddressAndTimezone(location, options, callback) { var loc = _utils2.default.clone(location, { own: false }); if (!options.addressLookup && !options.timezone) { return callback(null, loc); } function getTZ(cb) { geolocator.getTimeZone(loc.coords, function (err, timezone) { if (err) { return cb(err, null); } delete timezone.timestamp; loc.timezone = timezone; loc.timestamp = _utils2.default.time(); // update timestamp cb(null, loc); }); } if (options.addressLookup) { geolocator.reverseGeocode(loc.coords, function (err, result) { if (err) return callback(err, null); loc = _utils2.default.extend({}, result, loc); loc.address = result.address; loc.timestamp = _utils2.default.time(); // update timestamp if (!options.timezone) { callback(err, loc); } else { getTZ(callback); } }); } else if (options.timezone) { getTZ(callback); } else { callback(null, loc); } } /** * Gets the position with better accuracy. * See https://github.com/gwilson/getAccurateCurrentPosition#background * @private * * @param {Object} options * Locate options. * @param {Function} onPositionReceived * Success callback. * @param {Function} onPositionError * Error callback. */ function locateAccurate(options, onPositionReceived, onPositionError) { var loc = void 0, watcher = void 0, onProgress = !_utils2.default.isFunction(options.onProgress) ? _utils2.default.noop : options.onProgress; function complete() { if (!loc) { onPositionError(new _geo4.default(_geo4.default.Code.POSITION_UNAVAILABLE)); } else { onPositionReceived(loc); } } watcher = geolocator.watch(options, function (err, location) { if (err) { return watcher.clear(function () { onPositionError(err); }); } loc = location; // ignore the first event if not the only result; for more accuracy. if (watcher.cycle > 1 && loc.coords.accuracy <= options.desiredAccuracy) { watcher.clear(complete); } else { onProgress(loc); } }); watcher.clear(options.maximumWait + 100, complete); } function getStyles(options) { var conf = geolocator._.config; return !_utils2.default.isFilledArray(options.styles) ? _utils2.default.isFilledArray(conf.google.styles) ? conf.google.styles : null : options.styles; } // --------------------------- // INITIALIZE // --------------------------- /** * @private * @type {Object} */ geolocator._ = { config: _utils2.default.extend({}, defaultConfig), // Storage for global callbacks. cb: {} }; // setting default Geo-IP source, FreeGeoIP geolocator.setGeoIPSource({ provider: 'freegeoip', url: 'https://freegeoip.net/json', callbackParam: 'callback', schema: { ip: 'ip', coords: { latitude: 'latitude', longitude: 'longitude' }, address: { city: 'city', state: 'region_name', stateCode: 'region_code', postalCode: 'zip_code', countryCode: 'country_code', country: 'country_name', region: 'region_name' }, timezone: { id: 'time_zone' } } }); // --------------------------- // EXPORT // --------------------------- exports.default = geolocator; // --------------------------- // ADDITIONAL DOCUMENTATION // --------------------------- /** * `Coordinates` inner type that specifies the geographic position of the * device. The position is expressed as a set of geographic coordinates * together with information about heading and speed. * * This is generally returned as part of the * {@link ?api=geolocator#geolocator~Location|`Location` result object}. * * @typedef geolocator~Coordinates * @type Object * * @property {Number} latitude * Specifies the latitude estimate in decimal degrees. The value * range is [-90.00, +90.00]. * @property {Number} longitude * Specifies the longitude estimate in decimal degrees. The value * range is [-180.00, +180.00]. * @property {Number} altitude * Specifies the altitude estimate in meters above the WGS 84 * ellipsoid. * @property {Number} accuracy * Specifies the accuracy of the latitude and longitude estimates in * meters. * @property {Number} altitudeAccuracy * Specifies the accuracy of the altitude estimate in meters. * @property {Number} heading * Specifies the device's current direction of movement in degrees * counting clockwise relative to true north. * @property {Number} speed * Specifies the device's current ground speed in meters per second. */ /** * `Address` inner type that specifies the address of the fetched location. * The address is expressed as a set of political and locality components. * * This is generally returned as part of the * {@link ?api=geolocator#geolocator~Location|`Location` result object}. * * @typedef geolocator~Address * @type Object * * @property {String} commonName * Indicates a point of interest, a premise or colloquial area name for * the fetched location, if any. * @property {String} streetNumber * Indicates the precise street number of the fetched location, if any. * @property {String} street * Indicates the street name of the fetched location, if any. * @property {String} route * Indicates the route name of the fetched location, if any. * @property {String} neighborhood * Indicates the neighborhood name of the fetched location, if any. * @property {String} town * Indictes the town of the fetched location, if any. * @property {String} city * Indicates the city of the fetched location. * @property {String} region * Indicates the political region name of the fetched location, if any. * @property {String} postalCode * Indicates the postal code of the fetched location, if any. * @property {String} state * Indicates the state of the fetched location, if any. * @property {String} stateCode * Indicates the state code of the fetched location, if any. * @property {String} country * Indicates the national political entity of the fetched location. * @property {String} countryCode * Indicates the ISO alpha-2 country code of the fetched location. */ /** * `TimeZone` inner type that specifies time offset data for the fetched * location on the surface of the earth. * * This is generally returned as part of the * {@link ?api=geolocator#geolocator~Location|`Location` result object}. * * @typedef geolocator~TimeZone * @type Object * * @property {String} id * The ID of the time zone, such as `"America/Los_Angeles"` or * `"Australia/Sydney"`. These IDs are defined in the * {@link http://www.iana.org/time-zones|IANA Time Zone Database}, * which is also available in searchable format in Wikipedia's * {@link http://en.wikipedia.org/wiki/List_of_tz_database_time_zones|List of tz database time zones}. * @property {String} name * The long form name of the time zone. This field will be localized if * the Geolocator `language` is configured. e.g. `"Pacific Daylight Time"` * or `"Australian Eastern Daylight Time"`. * @property {String} abbr * The abbreviation of the time zone. * @property {Number} dstOffset * The offset for daylight-savings time in seconds. This will be zero * if the time zone is not in Daylight Savings Time during the specified * timestamp. * @property {Number} rawOffset * The offset from UTC (in seconds) for the given location. This does * not take into effect daylight savings. */ /** * `MapData` inner type that provides references to the components of a * created Google Maps `Map` and the containing DOM element. * * This is generally returned as part of the * {@link ?api=geolocator#geolocator~Location|`Location` result object}. * * @typedef geolocator~MapData * @type Object * * @property {HTMLElement} element * DOM element which a (Google) map is created within. * @property {google.maps.Map} instance * Instance of a Google Maps `Map` object. * @property {google.maps.Marker} marker * Instance of a Google Maps `Marker` object, if any. * @property {google.maps.InfoWindow} infoWindow * Instance of a Google Maps `InfoWindow` object, if any. * @property {Object} options * Arbitrary object of applied map options. */ /** * `Location` inner type that specifies geographic coordinates, address and * time zone information for the fetched location. * * This result object is passed to the callbacks of the corresponding * asynchronous Geolocator methods (such as `.locate()` method), as the second * argument. The contents of this object will differ for various Geolocator * methods, depending on the configured method options. * * @typedef geolocator~Location * @type Object * * @property {Coordinates} coords * Specifies the geographic location of the device. The location is * expressed as a set of geographic coordinates together with * information about heading and speed. * See {@link #geolocator~Coordinates|`geolocator~Coordinates` type} * for details. * @property {Address} address * Specifies the address of the fetched location. The address is * expressed as a set of political and locality components. * This property might be `undefined` if `addressLookup` option is not * enabled for the corresponding method. * See {@link #geolocator~Address|`geolocator~Address` type} * for details. * @property {String} formattedAddress * The human-readable address of this location. Often this address is * equivalent to the "postal address," which sometimes differs from * country to country. * @property {Boolean} targetReached * Specifies whether the defined target coordinates is reached. * This property is only available for * {@link #geolocator.watch|`geolocator.watch()`} method when `target` * option is defined. * @property {String} type * Type of the location. See * {@link #geolcoator.LocationType|`geolcoator.LocationType` enumeration} * for details. * @property {String} placeId * A unique identifier that can be used with other Google APIs. * @property {String} flag * URL of the country flag image, in SVG format. This property exists * only if address information is available. * @property {TimeZone} timezone * Specifies time offset data for the fetched location on the surface of * the earth. See {@link #geolocator~TimeZone|`geolocator~TimeZone` type} * for details. * @property {MapData} map * Provides references to the components of a created Google Maps `Map` * and the containing DOM element. See * {@link #geolocator~MapData|`geolocator~MapData` type} for details. * @property {String} staticMap * URL of a static Google map image, for the location. * @property {Number} timestamp * Specifies the time when the location information was retrieved and * the `Location` object created. */ /** * `MapOptions` inner type that specifies options for the map to be created. * * @typedef geolocator~MapOptions * @type Object * * @property {String|HTMLElement|Map} element * Either the ID of a DOM element or the element itself; * which the map will be created within; or a previously created * `google.maps.Map` instance. If a map instance is set, this * only will apply the options without re-creating it. * @property {Object} center * Center coordinates for the map to be created. * @property {Number} center.latitude * Latitude of the center point coordinates. * @property {Number} center.longitude * Longitude of the center point coordinates. * @property {String} mapTypeId * Type of the map to be created. * See {@link #geolocator.MapTypeId|`geolocator.MapTypeId` enumeration} * for possible values. * @property {String} title * Title text to be displayed within an `InfoWindow`, when the * marker is clicked. This only take effect if `marker` is * enabled. * @property {Boolean} marker * Whether to place a marker at the given coordinates. * If `title` is set, an `InfoWindow` will be opened when the * marker is clicked. * @property {Number} zoom * Zoom level to be set for the map. */ /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _utils = __webpack_require__(0); var _utils2 = _interopRequireDefault(_utils); var _fetch = __webpack_require__(3); var _fetch2 = _interopRequireDefault(_fetch); var _enums = __webpack_require__(1); var _enums2 = _interopRequireDefault(_enums); var _geo = __webpack_require__(2); var _geo2 = _interopRequireDefault(_geo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Helper methods. * * @license MIT * @copyright 2016, Onur Yıldırım (onur@cutepilot.com) * @type {Object} * @private */ var geoHelper = { toGoogleCoords: function toGoogleCoords(coords) { return { lat: coords.lat || coords.latitude, lng: coords.lng || coords.longitude }; }, fromGoogleCoords: function fromGoogleCoords(coords) { return { latitude: coords.latitude || coords.lat, longitude: coords.longitude || coords.lng }; }, // used for distance matrix origins and destinations toPointList: function toPointList(arr) { arr = _utils2.default.isArray(arr) ? arr : [arr]; return arr.map(function (o) { return _utils2.default.isString(o) ? o : geoHelper.toGoogleCoords(o); }); }, getGeocodeComps: function getGeocodeComps(comp) { return { route: comp.route, locality: comp.locality, administrative_area: comp.administrativeArea, // eslint-disable-line camelcase postal_code: comp.postalCode, // eslint-disable-line camelcase country: comp.country, region: comp.region }; }, // Geocode examples: // address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY // address=Winnetka&bounds=34.172684,-118.604794|34.236144,-118.500938&key=API_KEY // address=santa+cruz&components=country:ES&key=API_KEY // components=administrative_area:TX|country:US&key=API_KEY // Reverse Geocode examples: // latlng=40.714224,-73.961452&key=API_KEY // place_id=ChIJd8BlQ2BZwokRAFUEcm_qrcA&key=API_KEY buildGeocodeParams: function buildGeocodeParams(options, reverse) { var params = [], e = _utils2.default.encodeURI; if (reverse) { if (options.placeId) { params.push('place_id=' + options.placeId); } else if (options.latitude && options.longitude) { params.push('latlng=' + options.latitude + ',' + options.longitude); } } else { if (options.address) { params.push('address=' + e(options.address)); } var geoComps = geoHelper.getGeocodeComps(options); geoComps = _utils2.default.params(geoComps, { operator: ':', separator: '|' }); params.push('components=' + geoComps); var b = options.bounds; if (_utils2.default.isArray(b) && b.length === 4) { params.push('bounds=' + b[0] + ',' + b[1] + '|' + b[2] + ',' + b[3]); } else if (_utils2.default.isPlainObject(b) && Object.keys(b).length === 4) { params.push('bounds=' + b.southwestLat + ',' + b.southwestLng + '|' + b.northeastLat + ',' + b.northeastLng); } } params.push('language=' + options.language); params.push('key=' + options.key); return params.join('&'); }, // See https://developers.google.com/maps/documentation/geocoding/intro formatGeocodeResults: function formatGeocodeResults(results) { if (!_utils2.default.isArray(results) || results.length <= 0) { return { location: null, address: null, formattedAddress: '', type: null, // locationType placeId: '' }; } var i = void 0, c = void 0, o = {}, data = results[0], comps = data.address_components; for (i = 0; i < comps.length; i += 1) { c = comps[i]; if (c.types && c.types.length > 0) { o[c.types[0]] = c.long_name; o[c.types[0] + '_s'] = c.short_name; } } var geometry = data.geometry; return { coords: geometry && geometry.location ? { latitude: geometry.location.lat, longitude: geometry.location.lng } : null, address: { commonName: o.point_of_interest || o.premise || o.subpremise || o.colloquial_area || '', streetNumber: o.street_number || '', street: o.administrative_area_level_4 || o.administrative_area_level_3 || o.route || '', route: o.route || '', neighborhood: o.neighborhood || o.administrative_area_level_5 || o.administrative_area_level_4 || '', town: o.sublocality || o.administrative_area_level_2 || '', city: o.locality || o.administrative_area_level_1 || '', region: o.administrative_area_level_2 || o.administrative_area_level_1 || '', postalCode: o.postal_code || '', state: o.administrative_area_level_1 || '', stateCode: o.administrative_area_level_1_s || '', country: o.country || '', countryCode: o.country_s || '' }, formattedAddress: data.formatted_address, type: geometry.location_type || '', placeId: data.place_id, timestamp: _utils2.default.time() }; }, geocode: function geocode(reverse, conf, options, callback) { var opts = {}; if (_utils2.default.isString(options)) { opts = {}; var prop = reverse ? 'placeId' : 'address'; opts[prop] = options; } else if (_utils2.default.isPlainObject(options)) { opts = options; } else { throw new _geo2.default(_geo2.default.Code.INVALID_PARAMETERS); } if (reverse) { var coordsSet = _utils2.default.isNumber(options.latitude) && _utils2.default.isNumber(options.longitude); if (!_utils2.default.isString(options.placeId) && !coordsSet) { throw new _geo2.default(_geo2.default.Code.INVALID_PARAMETERS); } } opts = _utils2.default.extend({ key: conf.google.key || '', language: conf.language || 'en', raw: false }, opts); var query = geoHelper.buildGeocodeParams(opts, reverse), url = _utils2.default.setProtocol(_enums2.default.URL.GOOGLE_GEOCODE, conf.https), xhrOpts = { url: url + '?' + query }; _fetch2.default.xhr(xhrOpts, function (err, xhr) { if (err) return callback(_geo2.default.create(err), null); var response = _utils2.default.safeJsonParse(xhr.responseText), gErr = _geo2.default.fromResponse(response); if (gErr) return callback(gErr, null); response = options.raw ? response : geoHelper.formatGeocodeResults(response.results); callback(null, response); }); }, // See https://developers.google.com/maps/documentation/distance-matrix/intro // Raw Result Example: // { // "destination_addresses" : [ "San Francisco, CA, USA", "Victoria, BC, Canada" ], // "origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, WA, USA" ], // "rows" : [ // { // "elements" : [ // { // "distance" : { "text" : "1,704 km", "value" : 1704324 }, // "duration" : { "text" : "3 days 19 hours", "value" : 327061 // }, // "status" : "OK" // }, // { // "distance" : { "text" : "138 km", "value" : 138295 }, // "duration" : { "text" : "6 hours 44 mins", "value" : 24236 }, // "status" : "OK" // } // ] // }, // { // "elements" : [ // { // "distance" : { "text" : "1,452 km", "value" : 1451623 }, // "duration" : { "text" : "3 days 4 hours", "value" : 275062 }, // "status" : "OK" // }, // { // "distance" : { "text" : "146 km", "value" : 146496 }, // "duration" : { "text" : "2 hours 52 mins", "value" : 10324 }, // "status" : "OK" // } // ] // } // ], // "status" : "OK" // } // Formatted to: formatDistanceResults: function formatDistanceResults(results) { if (!_utils2.default.isPlainObject(results)) { return null; } var arr = [], origins = results.originAddresses, dests = results.destinationAddresses, rows = results.rows; // [ // { // from: 'Vancouver, BC, Canada', // to: 'San Francisco, CA, USA', // distance: { value: 1704107, text: "1,704 km" }, // duration: { value: 327025, text: "3 days 19 hours" }, // fare: { currency: "USD", value: 6, text: "$6.00" } // }, // ... // ] var e = void 0; origins.forEach(function (origin, oIndex) { dests.forEach(function (dest, dIndex) { e = rows[oIndex].elements[dIndex]; arr.push({ from: origin, to: dest, distance: e.distance, duration: e.duration, fare: e.fare, timestamp: _utils2.default.time() }); }); }); return arr; }, // Converts a map-styles object in to static map styles (formatted query-string params). // See https://developers.google.com/maps/documentation/static-maps/styling mapStylesToParams: function mapStylesToParams(styles) { if (!styles) return ''; if (!_utils2.default.isArray(styles)) styles = [styles]; var result = []; styles.forEach(function (v, i, a) { var style = ''; if (v.stylers) { // only if there is a styler object if (v.stylers.length > 0) { // Needs to have a style rule to be valid. style += (v.hasOwnProperty('featureType') ? 'feature:' + v.featureType : 'feature:all') + '|'; style += (v.hasOwnProperty('elementType') ? 'element:' + v.elementType : 'element:all') + '|'; v.stylers.forEach(function (val, i, a) { var propName = Object.keys(val)[0], propVal = val[propName].toString().replace('#', '0x'); style += propName + ':' + propVal + '|'; }); } } result.push('style=' + encodeURIComponent(style)); }); return result.join('&'); } }; exports.default = geoHelper; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _utils = __webpack_require__(0); var _utils2 = _interopRequireDefault(_utils); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var GeoWatcher = function () { function GeoWatcher(onChange, onError) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _classCallCheck(this, GeoWatcher); this.isCleared = false; this.cycle = 0; this._timer = null; this.id = navigator.geolocation.watchPosition(function (pos) { _this.cycle++; if (_utils2.default.isFunction(onChange)) onChange(pos); }, function (err) { _this.cycle++; if (_utils2.default.isFunction(onError)) onError(err); if (options.clearOnError) { _this.clear(); } }, options); } _createClass(GeoWatcher, [{ key: '_clear', value: function _clear() { navigator.geolocation.clearWatch(this.id); this.isCleared = true; this._timer = null; } }, { key: 'clear', value: function clear(delay, callback) { var _this2 = this; var d = _utils2.default.isNumber(delay) ? delay : 0, cb = _utils2.default.isFunction(callback) ? callback : _utils2.default.isFunction(delay) ? delay : null; // clear any previous timeout if (this._timer) { clearTimeout(this._timer); this._timer = null; } // check if watcher is not cleared if (!this.isCleared) { if (d === 0) { this._clear(); if (cb) cb(); return; } this._timer = setTimeout(function () { _this2._clear(); if (cb) cb(); }, d); } } }]); return GeoWatcher; }(); // --------------------------- // EXPORT // --------------------------- exports.default = GeoWatcher; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _geolocator = __webpack_require__(4); var _geolocator2 = _interopRequireDefault(_geolocator); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // See https://github.com/onury/geolocator/issues/42 if (typeof window !== 'undefined' && typeof window.geolocator === 'undefined') { window.geolocator = _geolocator2.default; } // export default geolocator; // http://stackoverflow.com/a/33683495/112731 module.exports = _geolocator2.default; /***/ }) /******/ ]); }); //# sourceMappingURL=geolocator.js.map
var program = require('../') , sinon = require('sinon').sandbox.create() , should = require('should'); sinon.stub(process, 'exit'); sinon.stub(process.stdout, 'write'); program .command('mycommand [options]', 'this is my command'); program.parse(['node', 'test']); program.name.should.be.a.Function; program.name().should.equal('test'); program.commands[0].name().should.equal('mycommand'); program.commands[1].name().should.equal('help'); var output = process.stdout.write.args[0]; output[0].should.containEql([ ' mycommand [options] this is my command' ].join('\n')); sinon.restore();
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'colorbutton', 'ms', { auto: 'Otomatik', bgColorTitle: 'Warna Latarbelakang', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White' }, more: 'Warna lain-lain...', panelTitle: 'Colors', textColorTitle: 'Warna Text' } );
/* * effect * author: ronglin * create date: 2011.2.10 */ /* * config parameters: * effectWin, host */ (function ($, ctx) { /* * effectClass */ var effectClass = function (config) { $.extend(this, config); //this.initialize(); }; effectClass.prototype = { effectWin: null, host: null, currentRule: null, _onload: null, _onselect: null, _onunload: null, _onpropertychange: null, _onselectorchange: null, _onpropertysort: null, _onpreview: null, _onpreviewend: null, constructor: effectClass, initialize: function () { // substribe events var self = this; this._onpreview = function (sender, set) { self.applyCss(set); }; this._onpreviewend = function (sender, set) { self.updateRule(self.currentRule); }; this._onpropertysort = function (sender, set) { self.updateRule(self.currentRule); }; this._onpropertychange = function (sender, set) { self.updateRule(self.currentRule); }; this._onselectorchange = function (sender, set) { self.applySelector(set.selector); }; this.host.onUnload.add(this._onunload = function () { self.removeRuleManager(); }); this.host.onLoad.add(this._onload = function () { self.clean(); }); this.host.onSelect.add(this._onselect = function (sender, set) { self.removeRuleSubscribe(); self.updateRule(set.rule, true); self.currentRule.onPreview.add(self._onpreview); self.currentRule.onPreviewEnd.add(self._onpreviewend); self.currentRule.onPropertySort.add(self._onpropertysort); self.currentRule.onPropertyChange.add(self._onpropertychange); self.currentRule.onSelectorChange.add(self._onselectorchange); }); }, updateRule: function (rule, onselect) { this.currentRule = rule || this.currentRule; if (this.currentRule && !onselect) { this.applyCss({ propertyText: this.currentRule.getPropertiesText() }); } }, applySelector: function (selector) { //TODO: }, clean: function () { if (this.ruleManager) { this.ruleManager.resetChanges(); } }, applyCss: function (set) { if (!this.ruleManager) { this.ruleManager = new pageRuleManager({ win: this.effectWin }); } set.selector = this.currentRule.getSelectorText(); this.ruleManager.applyCss(set); }, removeRuleManager: function () { if (this.ruleManager) { this.ruleManager.remove(); this.ruleManager = null; } }, removeRuleSubscribe: function () { if (this.currentRule) { this.currentRule.onPreview.remove(this._onpreview); this.currentRule.onPreviewEnd.remove(this._onpreviewend); this.currentRule.onPropertySort.remove(this._onpropertysort); this.currentRule.onPropertyChange.remove(this._onpropertychange); this.currentRule.onSelectorChange.remove(this._onselectorchange); } }, remove: function () { this.host.onLoad.remove(this._onload); this.host.onSelect.remove(this._onselect); this.host.onUnload.remove(this._onunload); this.removeRuleSubscribe(); this.removeRuleManager(); this.el.remove(); this.host = null; this.effectWin = null; } }; var pageRuleManager = function (config) { $.extend(this, config); this.initialize(); }; pageRuleManager.prototype = { win: null, changed: null, extendSheet: null, constructor: pageRuleManager, initialize: function () { this.changed = {}; }, applyCss: function (set) { // set { selector,propertyText } var selector = set.selector; var nospaceSel = ctx.nospace(selector); var sheets = this.win.document.styleSheets, effectList = []; for (var i = 0, slen = sheets.length; i < slen; i++) { var sheetItem = sheets[i]; try {// try catch for cross domain access issue var sheetRules = sheetItem.cssRules || sheetItem.rules; for (var j = 0, rlen = sheetRules.length; j < rlen; j++) { if (ctx.nospace(sheetRules.item(j).selectorText) === nospaceSel) { effectList.push({ rule: sheetRules.item(j), node: sheetItem.ownerNode || sheetItem.owningElement }); } } } catch (e) { } } var effectRule; if (effectList.length > 0) { effectRule = effectList[effectList.length - 1].rule; // use last one } if (effectRule) { var cssText = effectRule.style.cssText; var cache = this.changed[nospaceSel]; if (!cache) { this.changed[nospaceSel] = { cssText: [cssText], rules: [effectRule] }; } else { var index = -1, clen = cache.rules.length; for (var i = 0; i < clen; i++) { if (cache.rules[i] === effectRule) { index = i; } } if (index === -1) { cache.rules.push(effectRule); cache.cssText.push(cssText); } } } else { var extendSheet = this.getExtendSheet(); var extendRules = extendSheet.cssRules || extendSheet.rules; var insertIndex = extendRules.length; try {// catch unvalidate selector issue if (extendSheet.insertRule) { extendSheet.insertRule(selector + '{}', insertIndex); } else { extendSheet.addRule(selector, '', insertIndex); } } catch (ex) { } effectRule = extendRules[insertIndex]; } if (effectRule) { try {// catch unvalidate property issue if (set.name) { effectRule.style[ctx.cameName(set.name)] = (set.value || '') + (set.important ? '!important' : ''); } else if (set.propertyText) { effectRule.style.cssText = set.propertyText; } } catch (ex) { } } }, persistenceChanges: function () { this.changed = {}; if (this.extendSheet) {// persistence current referenced but not all nodes that has "visualstyle" attribute. var node = this.extendSheet.ownerNode || this.extendSheet.owningElement; if (node) { node.setAttribute('visualstyle', 'persisted'); } this.extendSheet = null; } }, resetChanges: function () { this.removeExtendSheet(); $.each(this.changed, function () { var len = this.rules.length; for (var i = 0; i < len; i++) { var cssText = this.cssText[i]; this.rules[i].style.cssText = cssText; } }); }, getExtendSheet: function () { if (this.extendSheet) { return this.extendSheet; } else { this.removeExtendSheet(); } var win = this.win, doc = win.document; var head = doc.getElementsByTagName('head')[0] || doc.body; var node = doc.createElement('style'); node.setAttribute('type', 'text/css'); node.setAttribute('visualstyle', 'temporary'); var cssText = '.test{}'; if ($.browser.msie) { head.appendChild(node); try { node.styleSheet.cssText = cssText; } catch (ex) { } } else { try { node.appendChild(doc.createTextNode(cssText)); } catch (ex) { node.cssText = cssText; } head.appendChild(node); } // ret this.extendSheet = node.styleSheet ? node.styleSheet : (node.sheet || doc.styleSheets[doc.styleSheets.length - 1]); return this.extendSheet; }, removeExtendSheet: function () { // remove referenced ownerNode if (this.extendSheet) { var ownerNode = this.extendSheet.ownerNode || this.extendSheet.owningElement; if (ownerNode) { ownerNode.parentNode.removeChild(ownerNode); } this.extendSheet = null; } // remove temporary nodes var nodes = this.win.document.getElementsByTagName('style'), node; for (var i = nodes.length - 1; i > -1; i--) { if ((node = nodes[i]) && node.getAttribute('visualstyle') === 'temporary') { node.parentNode.removeChild(node); } } // clear empty sheet // when sheet's owningElement was removed, it was setted to empty. var sheets = this.win.document.styleSheets; for (var i = sheets.length - 1; i > -1; i--) { if (!sheets[i]) { sheets.splice(i, 1); } } }, remove: function () { this.removeExtendSheet(); this.resetChanges(); this.changed = null; } }; // register ctx.effectClass = effectClass; } (jQuery, visualstyle));
/* * This file is part of the Tabulator package. * * (c) Oliver Folkerd <oliver.folkerd@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $.widget("ui.tabulator", { data:[],//array to hold data for table firstRender:true, //layout table widths correctly on first render mouseDrag:false, //mouse drag tracker; mouseDragWidth:false, //starting width of colum on mouse drag mouseDragElement:false, //column being dragged mouseDragOut:false, //catch to prevent mouseup on col drag triggering click on sort sortCurCol:null,//column name of currently sorted column sortCurDir:null,//column name of currently sorted column filterField:null, //field to be filtered on data render filterValue:null, //value to match on filter filterType:null, //filter type //setup options options: { backgroundColor: "#888", //background color of tabulator borderColor:"#999", //border to tablulator textSize: "14px", //table text size headerBackgroundColor:"#e6e6e6", //border to tablulator headerTextColor:"#555", //header text colour headerBorderColor:"#aaa", //header border color headerSeperatorColor:"#999", //header bottom seperator color headerMargin:"4px", rowBackgroundColor:"#fff", //table row background color rowBorderColor:"#aaa", //table border color rowTextColor:"#333", //table text color rowHoverBackground:"#bbb", //row background color on hover colMinWidth:"40px", //minimum global width for a column colResizable:true, //resizable columns height:false, //height of tabulator fitColumns:false, //fit colums to width of screen; movableCols:false, //enable movable columns movableRows:false, //enable movable rows movableRowHandle:"<div style='margin:0 10%; width:80%; height:3px; background:#666; margin-top:3px;'></div><div style='margin:0 10%; width:80%; height:3px; background:#666; margin-top:2px;'></div><div style='margin:0 10%; width:80%; height:3px; background:#666; margin-top:2px;'></div>", //handle for movable rows columns:[],//store for colum header info index:"id", sortable:true, //global default for sorting dateFormat: "dd/mm/yyyy", //date format to be used for sorting sortArrows:{ //colors for sorting arrows active: "#666", inactive: "#bbb", }, sortBy:"id", //defualt column to sort by sortDir:"desc", //default sort direction groupBy:false, //enable table grouping and set field to group by groupHeader:function(value, count, data){ //header layout function return value + "<span style='color:#d00; margin-left:10px;'>(" + count + " item)</span>"; }, editBoxColor:"#1D68CD", //color for edit boxes rowFormatter:false, //row formatter callback addRowPos:"bottom", //position to insert blank rows, top|bottom selectable:true, //highlight rows on hover ajaxURL:false, //url for ajax loading showLoader:true, //show loader while data loading loader:"<div style='display:inline-block; border:4px solid #333; border-radius:10px; background:#fff; font-weight:bold; font-size:16px; color:#000; padding:10px 20px;'>Loading Data</div>", //loader element loaderError:"<div style='display:inline-block; border:4px solid #D00; border-radius:10px; background:#fff; font-weight:bold; font-size:16px; color:#590000; padding:10px 20px;'>Loading Error</div>", //loader element rowClick:function(){}, //do action on row click rowAdded:function(){}, //do action on row add rowEdit:function(){}, //do action on row edit rowDelete:function(){}, //do action on row delete rowContext:function(){}, //context menu action dataLoaded:function(){}, //callback for when data has been Loaded rowMoved:function(){}, //callback for when row has moved colMoved:function(){}, //callback for when column has moved }, //loader blockout div loaderDiv: $("<div class='tablulator-loader' style='position:absolute; top:0; left:0; z-index:100; height:100%; width:100%; background:rgba(0,0,0,.4); text-align:center;'><div class='tabulator-loader-msg'></div></div>"), //show loader blockout div _showLoader:function(self, msg){ if(self.options.showLoader){ $(".tabulator-loader-msg", self.loaderDiv).empty().append(msg); $(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)}) self.element.append(self.loaderDiv); } }, _hideLoader:function(self){ $(".tablulator-loader", self.element).remove(); }, //event triggers //dataLoading:- callback for when data is being loaded //dataLoadError:- callback for when there is adata loading error //renderStarted:- callback for when table is starting to render //renderComplete:- callback for when table is rendered //sortStarted:- callback for when sorting has begun //sortComplete:- callback for when sorting is complete //constructor _create: function() { var self = this; var options = self.options; var element = self.element; options.textSize = isNaN(options.textSize) ? options.textSize : options.textSize + "px"; options.colMinWidth = isNaN(options.colMinWidth) ? options.colMinWidth : options.colMinWidth + "px"; options.textSizeNum = parseInt(options.textSize.replace("px","")); headerMargin = parseInt(options.headerMargin.replace("px","")); options.headerHeight = options.textSizeNum + (headerMargin*2) + 2; if(options.height){ options.height = isNaN(options.height) ? options.height : options.height + "px"; element.css({"height": options.height}); } element.addClass("tabulator"); element.css({ position:"relative", "box-sizing" : "border-box", "background-color": options.backgroundColor, "border": "1px solid " + options.borderColor, //"overflow-x":"auto", "overflow":"hidden", }) self.header = $("<div class='tabulator-header'></div>") self.header.css({ position:"relative", "background-color": options.headerBackgroundColor, "border-bottom":"1px solid " + options.headerSeperatorColor, "color": options.headerTextColor, "font-size":options.textSize, "font-weight":"bold", "white-space": "nowrap", "z-index":"1", "overflow":"visible", }); self.tableHolder = $("<div class='tabulator-tableHolder'></div>"); self.tableHolder.css({ "position":"absolute", "z-index":"1", "min-height":"calc(100% - " + (options.headerHeight + 1) + "px)", "max-height":"calc(100% - " + (options.headerHeight + 1) + "px)", "white-space": "nowrap", "overflow":"auto", "width":"100%", }); self.tableHolder.scroll(function(){ self.header.css({"margin-left": "-1" * $(this).scrollLeft()}); }); //create scrollable table holder self.table = $("<div class='tabulator-table'></div>"); self.table.css({ position:"relative", "font-size":options.textSize, "white-space": "nowrap", "z-index":"1", "display":"inline-block", "overflow":"visible", }); //create sortable arrow chevrons var arrow = $("<div class='tabulator-arrow'></div>"); arrow.css({ display: "inline-block", position: "absolute", top:"9px", right:"8px", width: 0, height: 0, "border-left": "6px solid transparent", "border-right": "6px solid transparent", "border-bottom": "6px solid " + options.sortArrows.inactive, }); //add column for row handle if movable rows enabled if(options.movableRows){ var handle = $('<div class="tabulator-col-row-handle" style="display:inline-block;">&nbsp</div>'); handle.css({ "width":"30px", "max-width":"30px", }) self.header.append(handle); } //setup movable columns if(options.movableCols){ self.header.sortable({ axis: "x", opacity:1, cancel:".tabulator-col-row-handle, .tabulator-col[data-field=''], .tabulator-col[data-field=undefined]", start: function(event, ui){ ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()}); }, change: function(event, ui){ ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()}); var field = ui.item.data("field"); var newPos = ui.placeholder.next(".tabulator-col").data("field") //cover situation where user moves back to original position if(newPos == field){ newPos = ui.placeholder.next(".tabulator-col").next(".tabulator-col").data("field") } $(".tabulator-row", self.table).each(function(){ if(newPos){ $(".tabulator-cell[data-field=" + field + "]", $(this)).insertBefore($(".tabulator-cell[data-field=" + newPos + "]", $(this))) }else{ $(this).append($(".tabulator-cell[data-field=" + field + "]", $(this))) } }) }, update: function(event, ui) { //update columns array with new positional data var fromField = ui.item.data("field") var toField = ui.item.next(".tabulator-col").data("field") console.log("to", toField) var from = null; var to = toField ? null : options.columns.length; console.log("to", to) $.each(options.columns, function(i, column) { if(column.field && column.field == fromField){ from = i; } if(column.field && column.field == toField){ to = i; } if(from !== null && to !== null){ return false; } }); console.log("brobbel", from + " - " + to) to = to > from ? to + 1 : to; options.columns.splice(to , 0, options.columns.splice(from, 1)[0]); //trigger callback options.colMoved(ui.item.data("field"), options.columns); }, }); } $.each(options.columns, function(i, column) { column.index = i; column.sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter; column.sortable = typeof(column.sortable) == "undefined" ? options.sortable : column.sortable; column.sortable = typeof(column.field) == "undefined" ? false : column.sortable; column.visible = typeof(column.visible) == "undefined" ? true : column.visible; if(options.sortBy == column.field){ var sortdir = " data-sortdir='" + options.sortDir + "' "; self.sortCurCol= column; self.sortCurDir = options.sortDir; }else{ var sortdir = ""; } var title = column.title ? column.title : "&nbsp"; var visibility = column.visible ? "inline-block" : "none"; var col = $('<div class="tabulator-col" style="display:' + visibility + '" data-index="' + i + '" data-field="' + column.field + '" data-sortable=' + column.sortable + sortdir + ' >' + title + '</div>'); if(typeof(column.width) != "undefined"){ column.width = isNaN(column.width) ? column.width : column.width + "px"; //format number col.data("width", column.width); col.css({width:column.width}); } //sort tabl click binding if(column.sortable){ col.on("click", function(){ if(!self.mouseDragOut){ //prevent accidental trigger my mouseup on column drag self._sortClick(column, col); //trigger sort } self.mouseDragOut = false; }) } self.header.append(col); }); element.append(self.header);// self.tableHolder.append(self.table); element.append(self.tableHolder); //layout headers $(".tabulator-col, .tabulator-col-row-handle", self.header).css({ "padding":"4px", "text-align":"left", "position":"relative", "border-right":"1px solid " + options.headerBorderColor, "box-sizing":"border-box", "user-select":"none", "white-space": "nowrap", "overflow": "hidden", "text-overflow": "ellipsis", "vertical-align": "bottom", }); //handle resizable columns if(self.options.colResizable){ //create resize handle var handle = $("<div class='tabulator-handle' style='position:absolute; right:0; top:0; bottom:0; width:5px;'></div>") handle.on("mousedown", function(e){ e.stopPropagation(); //prevent resize from interfereing with movable columns self.mouseDrag = e.screenX; self.mouseDragWidth = $(this).closest(".tabulator-col").outerWidth(); self.mouseDragElement = $(this).closest(".tabulator-col"); }) self.element.on("mousemove", function(e){ if(self.mouseDrag){ self.mouseDragElement.css({width: self.mouseDragWidth + (e.screenX - self.mouseDrag)}) self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth()); } }) self.element.on("mouseup", function(e){ if(self.mouseDrag){ e.stopPropagation(); e.stopImmediatePropagation(); self.mouseDragOut = true; self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth()); self.mouseDrag = false; self.mouseDragWidth = false; self.mouseDragElement = false; } }); handle.on("mouseover", function(){$(this).css({cursor:"ew-resize"})}) $(".tabulator-col", self.header).append(handle); } element.on("editval", ".tabulator-cell", function(e, value){ if($(this).is(":focus")){$(this).blur()} self._cellDataChange($(this), value); }) element.on("editcancel", ".tabulator-cell", function(e, value){ self._cellDataChange($(this), $(this).data("value")); }) //append sortable arrows to sortable headers $(".tabulator-col[data-sortable=true]", self.header).css({"padding-right":"25px"}) .data("sortdir", "desc") .on("mouseover", function(){$(this).css({cursor:"pointer", "background-color":"rgba(0,0,0,.1)"})}) .on("mouseout", function(){$(this).css({"background-color":"transparent"})}) .append(arrow.clone()); //render column headings self._colRender(); }, //set options _setOption: function(option, value) { $.Widget.prototype._setOption.apply( this, arguments ); }, //handle cell data change _cellDataChange: function(cell, value){ var self = this; var row = cell.closest(".tabulator-row"); //update cell data value cell.data("value", value); //update row data var rowData = row.data("data"); var hasChanged = rowData[cell.data("field")] != value; rowData[cell.data("field")] = value; row.data("data", rowData); if(rowData[self.options.index]){ //update tabulator data self.data[rowData[self.options.index]] = rowData; } //reformat cell data cell.html(self._formatCell(cell.data("formatter"), value, rowData, cell, row, cell.data("formatterParams"))) .css({"padding":"4px"}); if(hasChanged){ //triger event self.options.rowEdit(rowData[self.options.index], rowData, row); } self._styleRows(); }, //hide column hideCol: function(field){ var self = this; var column = false; $.each(self.options.columns, function(i, item) { console.log("field", item.field) if(item.field == field){ column = i; return false; } }); if(column === false){ return false; }else{ self.options.columns[column].visible = false; $(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide(); self._renderTable(); return true; } }, //show column showCol: function(field){ var self = this; var column = false; $.each(self.options.columns, function(i, item) { console.log("field", item.field) if(item.field == field){ column = i; return false; } }); if(column === false){ return false; }else{ self.options.columns[column].visible = true; $(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show().css({"display":"inline-block"}); self._renderTable(); return true; } }, //toggle column visibility toggleCol: function(field){ var self = this; var column = false; $.each(self.options.columns, function(i, item) { console.log("field", item.field) if(item.field == field){ column = i; return false; } }); if(column === false){ return false; }else{ self.options.columns[column].visible = !self.options.columns[column].visible; if(self.options.columns[column].visible){ $(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show().css({"display":"inline-block"}); }else{ $(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide(); } self._renderTable(); return true; } }, //delete row from table by id deleteRow: function(item){ var self = this; var id = typeof(item) == "number" ? item : item.data("data")[self.options.index]; if(self.data[id]){ //remove row from data self.data.splice(id, 1); } if(id){ //remove row from table $("[data-id=" + id + "]", self.element).remove(); }else{ //remove row from table item.remove(); } //style table rows self._styleRows(); //align column widths self._colRender(!self.firstRender); self._trigger("renderComplete"); self.options.rowDelete(id); }, //add blank row to table addRow:function(item){ var self = this; if(item){ item[self.options.index] = item[self.options.index]? item[self.options.index]: 0; }else{ item = {id:0} } //create blank row var row = self._renderRow(item); //append to top or bottom of table based on preference if(self.options.addRowPos == "top"){ self.table.prepend(row); }else{ self.table.append(row); } //style table rows self._styleRows(); //align column widths self._colRender(!self.firstRender); self._trigger("renderComplete"); //triger event self.options.rowAdded(item); }, //get array of data from the table getData:function(){ var self = this; var allData = []; //get all data from array /*self.data.forEach( function(item, i) { allData.push(item); });*/ //get all new elements from list /*$("[data-id=0]", self.element).each(function(){ allData.push($(this).data("data")); });*/ $(".tabulator-row", self.element).each(function(){ if($(this).data("id")){ allData.push(self.data[$(this).data("id")]); }else{ allData.push($(this).data("data")); } }); return allData; }, //load data setData:function(data){ this._trigger("dataLoading"); //show loader if needed this._showLoader(this, this.options.loader) if(typeof(data) === "string"){ if (data.indexOf("{") == 0 || data.indexOf("[") == 0){ //data is a json encoded string this._parseData(jQuery.parseJSON(data)); }else{ //assume data is url, make ajax call to url to get data this._getAjaxData(data); } }else{ if(data){ //asume data is already an object this._parseData(data); }else{ //no data provided, check if ajaxURL is present; if(this.options.ajaxURL){ this._getAjaxData(this.options.ajaxURL); }else{ //empty data this._parseData([]); } } } }, //clear data clear:function(){ this.table.empty(); this.data = []; this._renderTable(); }, //filter data in table setFilter:function(field, type, value){ var self = this; self._trigger("filterStarted"); //set filter if(field){ //set filter self.filterField = field; self.filterType = typeof(value) == "undefined" ? "=" : type; self.filterValue = typeof(value) == "undefined" ? type : value; }else{ //clear filter self.filterField = null; self.filterType = null; self.filterValue = null; } //render table this._renderTable(); }, //clear filter clearFilter:function(){ var self = this; self.filterField = null; self.filterType = null; self.filterValue = null; //render table this._renderTable(); }, //get current filter info getFilter:function(){ var self = this; if(self.filterField){ var filter = { "field":self.filterField, "type":self.filterType, "value":self.filterValue, }; return filter; }else{ return false; } }, //parse and index data _parseData:function(data){ var self = this; var newData = []; if(data.length){ if(typeof(data[0][self.options.index]) == "undefined"){ self.options.index = "_index"; $.each(data, function(i, item) { newData[i] = item; newData[i]["_index"] = i; }); }else{ $.each(data, function(i, item) { newData[item[self.options.index]] = item; }); } } self.data = newData; self.options.dataLoaded(data); self._renderTable(); }, //get json data via ajax _getAjaxData:function(url){ var self = this; var options = self.options; $.ajax({ url: url, type: "GET", async: true, dataType:'json', success: function (data) { self._parseData(data); }, error: function (xhr, ajaxOptions, thrownError) { console.log("Tablulator ERROR (ajax get): " + xhr.status + " - " + thrownError); self._trigger("dataLoadError", xhr, thrownError); self._showLoader(self, self.options.loaderError); }, }); }, //build table DOM _renderTable:function(){ var self = this; var options = self.options this._trigger("renderStarted"); //hide table while building self.table.hide(); //show loader if needed self._showLoader(self, self.options.loader) //clear data from table before loading new self.table.empty(); //build rows of table self.data.forEach( function(item, i) { //check if filter and only build row if if data matches filter if(!self.filterField || (self.filterField && self._filterRow(item))){ var row = self._renderRow(item); if(options.groupBy){ // if groups in use, render column in group var groupVal = typeof(options.groupBy) == "function" ? options.groupBy(item) : item[options.groupBy]; var group = $(".tabulator-group[data-value='" + groupVal + "']", self.table); //if group does not exist, build it if(group.length == 0){ group = self._renderGroup(groupVal); self.table.append(group); } $(".tabulator-group-body", group).append(row); }else{ //if not grouping output row to table self.table.append(row); } } }); //enable movable rows if(options.movableRows){ var moveBackground =""; var moveBorder =""; //sorter options var config = { handle:".tabulator-row-handle", opacity: 1, axis: "y", start: function(event, ui){ moveBorder = ui.item.css("border"); moveBackground = ui.item.css("background-color"); ui.item.css({ "border":"1px solid #000", "background":"#fff", }); }, stop: function(event, ui){ ui.item.css({ "border": moveBorder, "background":moveBackground, }); }, update: function(event, ui) { //restyle rows self._styleRows(); //clear sorter arrows $(".tabulator-col[data-sortable=true]", self.header).data("sortdir", "desc"); $(".tabulator-col .tabulator-arrow", self.header).css({ "border-top": "none", "border-bottom": "6px solid " + options.sortArrows.inactive, }) //trigger callback options.rowMoved(ui.item.data("id"), ui.item.data("data"), ui.item,ui.item.prevAll(".tabulator-row").length); }, } //if groups enabled, set sortable on groups, otherwise set it on main table if(options.groupBy){ $(".tabulator-group-body", self.table).sortable(config); }else{ self.table.sortable(config); } } if(options.groupBy){ $(".tabulator-group", self.table).each(function(){ self._renderGroupHeader($(this)); }); self._sortElement(self.table, {}, "asc", true); //sort groups } self.table.css({// "background-color":self.options.rowBackgroundColor, "color":self.options.rowTextColor, }); //style table rows self._styleRows(); //sort data if already sorted if(self.sortCurCol){ self._sorter(self.sortCurCol, self.sortCurDir); } //show table once loading complete self.table.show(); //align column widths self._colRender(!self.firstRender); //hide loader div self._hideLoader(self); self._trigger("renderComplete"); if(self.filterField){ self._trigger("filterComplete"); } }, //build group DOM _renderGroup:function(value){ var group = $("<div class='tabulator-group' data-value='" + value + "'><div class='tabulator-group-header'></div><div class='tabulator-group-body'></div></div>"); return group; }, //render group header _renderGroupHeader:function(group){ var self = this; //create sortable arrow chevrons var arrow = $("<div class='tabulator-arrow'></div>"); arrow.css({ display: "inline-block", "vertical-align":"middle", width: 0, height: 0, "margin-right":"10px", "margin-left":"5px", "border-left": "6px solid transparent", "border-right": "6px solid transparent", "border-top": "6px solid " + self.options.sortArrows.active, }) .data("show", true) .on("mouseover", function(){$(this).css({cursor:"pointer", "background-color":"rgba(0,0,0,.1)"})}) .on("mouseout", function(){$(this).css({"background-color":"transparent"})}) .on("click", function(){ if($(this).data("show")){ $(this).data("show", false); $(this).closest(".tabulator-group").find(".tabulator-group-body").slideUp(); $(this).css({ "margin-left":"8px", "margin-right":"13px", "border-top": "6px solid transparent", "border-bottom": "6px solid transparent", "border-right": "0", "border-left": "6px solid " + self.options.sortArrows.active, }) }else{ $(this).data("show", true); $(this).closest(".tabulator-group").find(".tabulator-group-body").slideDown(); $(this).css({ "margin-left":"5px", "margin-right":"10px", "border-left": "6px solid transparent", "border-right": "6px solid transparent", "border-top": "6px solid " + self.options.sortArrows.active, "border-bottom": "0", }) } }); var data = []; $(".tabulator-row", group).each(function(){ data.push($(this).data("data")); }); $(".tabulator-group-header", group) .css({ "background":"#ccc", "font-weight":"bold", "padding":"5px", "border-bottom":"1px solid #999", "border-top":"1px solid #999", "box-sizing":"border-box", }) .html(arrow) .append(self.options.groupHeader(group.data("value"), $(".tabulator-row", group).length, data)); }, //check if row data matches filter _filterRow:function(row){ var self = this; // if no filter set display row if(!self.filterField){ return true; } var value = row[self.filterField]; var term = self.filterValue; switch(self.filterType){ case "=": //equal to return value == term ? true : false; break; case "<": //less than return value < term ? true : false; break; case "<=": //less than or equal too return value <= term ? true : false; break; case ">": //greater than return value > term ? true : false; break; case ">=": //greater than or equal too return value >= term ? true : false; break; case "!=": //not equal to return value != term ? true : false; break; case "like": //text like return value.toLowerCase().indexOf(term.toLowerCase()) > -1 ? true : false; break; default: return false; } return false; }, //render individual rows _renderRow:function(item){ var self = this; var row = $('<div class="tabulator-row" data-id="' + item[self.options.index] + '"></div>'); //bind row data to row row.data("data", item); //bind row click events row.on("click", function(e){self._rowClick(e, row, item)}); row.on("contextmenu", function(e){self._rowContext(e, row, item)}); //add row handle if movable rows enabled if(self.options.movableRows){ var handle = $("<div class='tabulator-row-handle'></div>"); handle.append(self.options.movableRowHandle); handle.css({ "text-align": "center", "box-sizing":"border-box", "display":"inline-block", "vertical-align":"middle", "min-height":self.options.headerHeight + 2, "white-space":"nowrap", "overflow":"hidden", "text-overflow":"ellipsis", "padding":"4px", "width":"30px", "max-width":"30px", }) .on("mouseover", function(){$(this).css({cursor:"move", "background-color":"rgba(0,0,0,.1)"})}) row.append(handle); } $.each(self.options.columns, function(i, column) { //deal with values that arnt declared var value = typeof(item[column.field]) == 'undefined' ? "" : item[column.field]; // set empty values to not break search if(typeof(item[column.field]) == 'undefined'){ item[column.field] = ""; } //set column text alignment var align = typeof(column.align) == 'undefined' ? "left" : column.align; //allow tabbing on editable cells var tabbable = column.editable || column.editor ? "tabindex='0'" : ""; var cell = $("<div class='tabulator-cell' " + tabbable + " data-index='" + i + "' data-field='" + column.field + "' data-value='" + self._safeString(value) + "' ></div>"); var visibility = column.visible ? "inline-block" : "none"; cell.css({ "text-align": align, "box-sizing":"border-box", "display":visibility, "vertical-align":"middle", "min-height":self.options.headerHeight + 2, "white-space":"nowrap", "overflow":"hidden", "text-overflow":"ellipsis", "padding":"4px", }) //mark cell as editable var editor = false; //match editor if one exists if (column.editable || column.editor){ if(column.editor){ editor = column.editor; }else{ editor = self.editors[column.formatter] ? column.formatter: "input"; } } cell.data("editor", editor); //format cell contents cell.data("formatter", column.formatter); cell.data("formatterParams", column.formatterParams); cell.html(self._formatCell(column.formatter, value, item, cell, row, column.formatterParams)); //bind cell click function if(typeof(column.onClick) == "function"){ cell.on("click", function(e){self._cellClick(e, cell)}); }else{ //handle input replacement on editable cells if(cell.data("editor")){ cell.on("focus", function(e){ e.stopPropagation(); cell.css({padding: "0", border:"1px solid " + self.options.editBoxColor}) var editorFunc = typeof(cell.data("editor")) == "string" ? self.editors[cell.data("editor")] : cell.data("editor"); var cellEditor = editorFunc(cell, cell.data("value")); cell.empty(); cell.append(cellEditor); //prevent editing from tirggering rowClick event cell.children().click(function(e){ e.stopPropagation(); }) }); } } row.append(cell); }); return row; }, //get number of elements in dataset dataCount:function(){ return this.data.length; }, //redraw list without updating data redraw:function(){ var self = this //redraw columns if(self.options.fitColumns){ self._colRender(); } //reposition loader if present if(self.element.innerHeight() > 0){ $(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)}) } }, //resize a colum to specified width _resizeCol:function(index, width){ $(".tabulator-cell[data-index=" + index + "], .tabulator-col[data-index=" + index + "]",this.element).css({width:width}) }, //layout coluns on first render _colRender:function(fixedwidth){ var self = this; var options = self.options; var table = self.table; var header = self.header; var element = self.element; self.firstRender = false; if(fixedwidth && !options.fitColumns){ //it columns have been resized and now data needs to match them //free sized table $.each(options.columns, function(i, column) { colWidth = $(".tabulator-col[data-index=" + i + "]", element).outerWidth(); var col = $(".tabulator-cell[data-index=" + i + "]", element); col.css({width:colWidth}); }); }else{ if(options.fitColumns){ //resize columns to fit in window if(self.options.fitColumns){ $(".tabulator-row", self.table).css({ "width":"100%", }) } var totWidth = options.movableRows ? self.element.innerWidth() - 30 : self.element.innerWidth(); var colCount = 0; var colWidth = totWidth / colCount; var widthIdeal = 0; var widthIdealCount = 0; $.each(options.columns, function(i, column) { if(column.visible){ colCount++; if(column.width){ var thisWidth = typeof(column.width) == "string" ? parseInt(column.width) : column.width; widthIdeal += thisWidth; widthIdealCount++; } } }); var proposedWidth = Math.floor((totWidth - widthIdeal) / (colCount - widthIdealCount)) if(proposedWidth >= parseInt(options.colMinWidth)){ $.each(options.columns, function(i, column) { if(column.visible){ var newWidth = column.width ? column.width : proposedWidth; var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i + "]",element); col.css({width:newWidth}); } }); }else{ var col = $(".tabulator-cell, .tabulator-col",element); col.css({width:colWidth}); } }else{ //free sized table $.each(options.columns, function(i, column) { var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i+ "]",element) if(column.width){ //reseize to match specified column width max = column.width; }else{ //resize columns to widest element var max = 0; col.each(function(){ max = $(this).outerWidth() > max ? $(this).outerWidth() : max }); if(options.colMinWidth){ max = max < options.colMinWidth ? options.colMinWidth : max; } } col.css({width:max}); }); }// } }, //style rows of the table _styleRows:function(){ var self = this; //fixes IE rendering bug on table redraw $(".tabulator-tableHolder", self.element).css({height:$(".tabulator-table", self.element).height()}); $(".tabulator-row", self.table).css({"background-color":"transparent"}) //hover over rows if(self.options.selectable){ $(".tabulator-row", self.table) .on("mouseover", function(){$(this).css({cursor:"pointer", "background-color":self.options.rowHoverBackground})}) .on("mouseout", function(){ $(this).css({"background-color":"transparent"}); if(self.options.rowFormatter){ self.options.rowFormatter($(this), $(this).data("data")); } }) } //color odd rows $(".tabulator-row:nth-of-type(even)", self.table).css({ "background-color": "rgba(0,0,0,.1);" //shade even numbered rows }) .on("mouseout", function(){ $(this).css({"background-color": "rgba(0,0,0,.08);"}) if(self.options.rowFormatter){ self.options.rowFormatter($(this), $(this).data("data")); } }); //make sure odd rows revert back to color after hover //add column borders to rows $(".tabulator-cell, .tabulator-row-handle", self.table).css({ "border":"none", "border-right":"1px solid " + self.options.rowBorderColor, }); if(!self.options.height){ self.element.css({height:self.table.outerHeight() + self.options.headerHeight + 3}) } //apply row formatter if(self.options.rowFormatter){ $(".tabulator-row", self.table).each(function(){ self.options.rowFormatter($(this), $(this).data("data")); }); } }, //format cell contents _formatCell:function(formatter, value, data, cell, row, formatterParams){ var formatter = typeof(formatter) == "undefined" ? "plaintext" : formatter; formatter = typeof(formatter) == "string" ? this.formatters[formatter] : formatter; return formatter(value, data, cell, row, this.options, formatterParams); }, //carry out action on row click _rowClick: function(e, row, data){ this.options.rowClick(e, row.data("id"), data, row); }, //carry out action on row context _rowContext: function(e, row, data){ e.preventDefault(); this.options.rowContext(e, row.data("id"), data, row); }, //carry out action on cell click _cellClick: function(e, cell){ var column = this.options.columns.filter(function(column) { return column.index == cell.data("index"); }); column[0].onClick(e, cell, cell.data("value"), cell.closest(".tabulator-row").data("data") ); }, //return escaped string for attribute _safeString: function(value){ return String(value).replace(/'/g, "&#39;"); }, _sortClick: function(column, element){ var self = this; if (element.data("sortdir") == "desc"){ element.data("sortdir", "asc"); }else{ element.data("sortdir", "desc"); } self.sort(column, element.data("sortdir")); }, // public sorter sort: function(sortList, dir){ var self = this; var header = self.header; var options = this.options; if(!Array.isArray(sortList)){ sortList = [{field: sortList, dir:dir}]; } $.each(sortList, function(i, item) { //convert colmun name to column object if(typeof(item.field) == "string"){ $.each(options.columns, function(i, col) { if(col.field == item.field){ item.field = col; return false; } }); } //reset all column sorts $(".tabulator-col[data-sortable=true][data-field!=" + item.field.field + "]", self.header).data("sortdir", "desc"); $(".tabulator-col .tabulator-arrow", self.header).css({ "border-top": "none", "border-bottom": "6px solid " + options.sortArrows.inactive, }) var element = $(".tabulator-col[data-field='" + item.field.field + "']", header); if (dir == "asc"){ $(".tabulator-arrow", element).css({ "border-top": "none", "border-bottom": "6px solid " + options.sortArrows.active, }); }else{ $(".tabulator-arrow", element).css({ "border-top": "6px solid " + options.sortArrows.active, "border-bottom": "none", }); } self._sorter(item.field, item.dir, sortList, i); }); }, //sort table _sorter: function(column, dir, sortList, i){ var self = this; var table = self.table; var options = self.options; var data = self.data; self._trigger("sortStarted"); self.sortCurCol = column; self.sortCurDir = dir; if(options.groupBy){ if(options.groupBy == column.field){ self._sortElement(table, column, dir, true); }else{ $(".tabulator-group", table).each(function(){ self._sortElement($(this), column, dir, false, sortList, i); }); } }else{ self._sortElement(table, column, dir, false, sortList, i); } //style table rows self._styleRows(); self._trigger("sortComplete"); }, //sort elements within table _sortElement:function(element, column, dir, sortGroups, sortList, i){ var self = this; var row = sortGroups ? ".tabulator-group" : ".tabulator-row"; $(row, element).sort(function(a,b) { var result = self._processSorter(a, b, column, dir, sortGroups); //if results match recurse through previous searchs to be sure if(result == 0 && i){ for(var j = i-1; j>= 0; j--){ result = self._processSorter(a, b, sortList[j].field, sortList[j].dir, sortGroups); if(result != 0){ break; } } } return result; }).appendTo(element); }, _processSorter:function(a, b, column, dir, sortGroups){ var self = this; //switch elements depending on search direction el1 = dir == "asc" ? $(a) : $(b); el2 = dir == "asc" ? $(b) : $(a); if(sortGroups){ el1 = el1.data("value"); el2 = el2.data("value"); }else{ el1 = el1.data("data")[column.field]; el2 = el2.data("data")[column.field]; } //workaround to format dates correctly a = column.sorter == "date" ? self._formatDate(el1) : el1; b = column.sorter == "date" ? self._formatDate(el2) : el2; //run sorter var sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter; sorter = typeof(sorter) == "string" ? self.sorters[sorter] : sorter; return sorter(a, b); }, //format date for date comparison _formatDate:function(dateString){ var format = this.options.dateFormat var ypos = format.indexOf("yyyy"); var mpos = format.indexOf("mm"); var dpos = format.indexOf("dd"); if(dateString){ var formattedString = dateString.substring(ypos, ypos+4) + "-" + dateString.substring(mpos, mpos+2) + "-" + dateString.substring(dpos, dpos+2); var newDate = Date.parse(formattedString) }else{ var newDate = 0; } return isNaN(newDate) ? 0 : newDate; }, //custom data sorters sorters:{ number:function(a, b){ //sort numbers return parseFloat(String(a).replace(",","")) - parseFloat(String(b).replace(",","")); }, string:function(a, b){ //sort strings return String(a).toLowerCase().localeCompare(String(b).toLowerCase()); }, date:function(a, b){ //sort dates return a - b; }, boolean:function(a, b){ //sort booleans el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0; el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0; return el1 - el2 }, alphanum:function(as, bs) { var a, b, a1, b1, i= 0, L, rx= /(\d+)|(\D+)/g, rd= /\d/; if(isFinite(as) && isFinite(bs)) return as - bs; a= String(as).toLowerCase(); b= String(bs).toLowerCase(); if(a=== b) return 0; if(!(rd.test(a) && rd.test(b))) return a> b? 1: -1; a= a.match(rx); b= b.match(rx); L= a.length> b.length? b.length: a.length; while(i < L){ a1= a[i]; b1= b[i++]; if(a1!== b1){ if(isFinite(a1) && isFinite(b1)){ if(a1.charAt(0)=== "0") a1= "." + a1; if(b1.charAt(0)=== "0") b1= "." + b1; return a1 - b1; } else return a1> b1? 1: -1; } } return a.length > b.length; }, }, //custom data formatters formatters:{ plaintext:function(value, data, cell, row, options, formatterParams){ //plain text value return value; }, money:function(value, data, cell, row, options, formatterParams){ var number = parseFloat(value).toFixed(2); var number = number.split('.'); var integer = number[0]; var decimal = number.length > 1 ? '.' + number[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(integer)) { integer = integer.replace(rgx, '$1' + ',' + '$2'); } return integer + decimal; }, email:function(value, data, cell, row, options, formatterParams){ return "<a href='mailto:" + value + "'>" + value + "</a>"; }, link:function(value, data, cell, row, options, formatterParams){ return "<a href='" + value + "'>" + value + "</a>"; }, tick:function(value, data, cell, row, options, formatterParams){ var tick = '<svg enable-background="new 0 0 24 24" height="' + options.textSize + '" width="' + options.textSize + '" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>'; if(value === true || value === 'true' || value === 'True' || value === 1){ return tick; }else{ return ""; } }, tickCross:function(value, data, cell, row, options, formatterParams){ var tick = '<svg enable-background="new 0 0 24 24" height="' + options.textSize + '" width="' + options.textSize + '" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>'; var cross = '<svg enable-background="new 0 0 24 24" height="' + options.textSize + '" width="' + options.textSize + '" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>'; if(value === true || value === 'true' || value === 'True' || value === 1){ return tick; }else{ return cross; } }, star:function(value, data, cell, row, options, formatterParams){ var maxStars = formatterParams && formatterParams.stars ? formatterParams.stars : 5; var stars=$("<span style='vertical-align:middle;'></span>"); value = parseInt(value) < maxStars ? parseInt(value) : maxStars; var starActive = $('<svg width="' + options.textSize + '" height="' + options.textSize + '" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#FFEA00" stroke="#C1AB60" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>'); var starInactive = $('<svg width="' + options.textSize + '" height="' + options.textSize + '" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#D2D2D2" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>'); for(i=1;i<= maxStars;i++){ var nextStar = i <= value ? starActive : starInactive; stars.append(nextStar.clone()); } cell.css({ "white-space": "nowrap", "overflow": "hidden", "text-overflow": "ellipsis", }) return stars.html(); }, progress:function(value, data, cell, row, options, formatterParams){ //progress bar //set default parameters var max = formatterParams && formatterParams.max ? formatterParams.max : 100; var min = formatterParams && formatterParams.min ? formatterParams.min : 0; var color = formatterParams && formatterParams.color ? formatterParams.color : "#2DC214"; //make sure value is in range value = parseFloat(value) <= max ? parseFloat(value) : max; value = parseFloat(value) >= min ? parseFloat(value) : min; //workout percentage var percent = (max - min) / 100; value = Math.round((value - min) / percent); cell.css({ "min-width":"30px", }); return "<div style='margin-top:3px; height:10px; width:" + value + "%; background-color:" + color + "; display:inline-block; vertical-align:middle;' data-max='" + max + "' data-min='" + min + "'></div>" }, }, //custom data editors editors:{ input:function(cell, value){ //create and style input var input = $("<input type='text'/>"); input.css({ "border":"1px", "background":"transparent", "padding":"4px", "width":"100%", "box-sizing":"border-box", }) .val(value); setTimeout(function(){ input.focus(); },100) //submit new value on blur input.on("change blur", function(e){ cell.trigger("editval", input.val()); }); //submit new value on enter input.on("keydown", function(e){ if(e.keyCode == 13){ cell.trigger("editval", input.val()); } }); return input; }, number:function(cell, value){ //create and style input var input = $("<input type='number'/>"); input.css({ "border":"1px", "background":"transparent", "padding":"4px", "width":"100%", "box-sizing":"border-box", }) .val(value); setTimeout(function(){ input.focus(); },100) //submit new value on blur input.on("blur", function(e){ cell.trigger("editval", input.val()); }); //submit new value on enter input.on("keydown", function(e){ if(e.keyCode == 13){ cell.trigger("editval", input.val()); } }); return input; }, star:function(cell, value){ var maxStars = $("svg", cell).length; var size = $("svg:first", cell).attr("width"); var stars=$("<div style='vertical-align:middle; padding:4px; display:inline-block; vertical-align:middle;'></div>"); value = parseInt(value) < maxStars ? parseInt(value) : maxStars; var starActive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-active" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>'); var starInactive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-inactive" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>'); for(i=1;i<= maxStars;i++){ var nextStar = i <= value ? starActive : starInactive; stars.append(nextStar.clone()); } //change number of active stars var starChange = function(element){ if($(".tabulator-star-active", element.closest("div")).length != element.prevAll("svg").length + 1){ element.prevAll("svg").replaceWith(starActive.clone()); element.nextAll("svg").replaceWith(starInactive.clone()); element.replaceWith(starActive.clone()); } } stars.on("mouseover", "svg", function(e){ e.stopPropagation(); starChange($(this)); }) stars.on("mouseover", function(e){ $("svg", $(this)).replaceWith(starInactive.clone()); }); stars.on("click", function(e){ $(this).closest(".tabulator-cell").trigger("editval", 0); }); stars.on("click", "svg", function(e){ var val = $(this).prevAll("svg").length + 1; cell.trigger("editval", val); }); cell.css({ "white-space": "nowrap", "overflow": "hidden", "text-overflow": "ellipsis", }) cell.on("blur", function(){ $(this).trigger("editcancel"); }); //allow key based navigation cell.on("keydown", function(e){ switch(e.keyCode){ case 39: //right arrow starChange($(".tabulator-star-inactive:first", stars)) break; case 37: //left arrow var prevstar = $(".tabulator-star-active:last", stars).prev("svg") if(prevstar.length){ starChange(prevstar) }else{ $("svg", stars).replaceWith(starInactive.clone()); } break; case 13: //enter cell.trigger("editval", $(".tabulator-star-active", stars).length); break; } }); return stars; }, progress:function(cell, value){ //set default parameters var max = $("div", cell).data("max"); var min = $("div", cell).data("min"); //make sure value is in range value = parseFloat(value) <= max ? parseFloat(value) : max; value = parseFloat(value) >= min ? parseFloat(value) : min; //workout percentage var percent = (max - min) / 100; value = Math.round((value - min) / percent); cell.css({ padding:"0 4px", }); var newVal = function(){ var newval = (percent * Math.round(bar.outerWidth() / (cell.width()/100))) + min; cell.trigger("editval", newval); } var bar = $("<div style='margin-top:7px; height:10px; width:" + value + "%; background-color:#488CE9; display:inline-block; vertical-align:middle; position:relative; max-width:100%; min-width:0%;' data-max='" + max + "' data-min='" + min + "'></div>"); var handle = $("<div class='taulator-progress-handle' style='position:absolute; right:0; top:0; bottom:0; width:5px;'></div>"); bar.append(handle); handle.on("mousedown", function(e){ bar.data("mouseDrag", e.screenX); bar.data("mouseDragWidth", bar.outerWidth()); }) handle.on("mouseover", function(){$(this).css({cursor:"ew-resize"})}) cell.on("mousemove", function(e){ if(bar.data("mouseDrag")){ bar.css({width: bar.data("mouseDragWidth") + (e.screenX - bar.data("mouseDrag"))}) } }) cell.on("mouseup", function(e){ if(bar.data("mouseDrag")){ e.stopPropagation(); e.stopImmediatePropagation(); bar.data("mouseDragOut", true); bar.data("mouseDrag", false); bar.data("mouseDragWidth", false); newVal(); } }); //allow key based navigation cell.on("keydown", function(e){ switch(e.keyCode){ case 39: //right arrow bar.css({"width" : bar.width() + cell.width()/100}); break; case 37: //left arrow bar.css({"width" : bar.width() - cell.width()/100}); break; case 13: //enter newVal(); break; } }); cell.on("blur", function(){ $(this).trigger("editcancel"); }); return bar; }, tickCross:function(cell, value){ //create and style input var input = $("<input type='checkbox'/>"); input.css({ "border":"1px", "background":"transparent", "margin-top":"5px", "box-sizing":"border-box", }) .val(value); setTimeout(function(){ input.focus(); },100) if(value === true || value === 'true' || value === 'True' || value === 1){ input.prop("checked", true) }else{ input.prop("checked", false) } //submit new value on blur input.on("change blur", function(e){ cell.trigger("editval", input.is(":checked")); }); //submit new value on enter input.on("keydown", function(e){ if(e.keyCode == 13){ cell.trigger("editval", input.is(":checked")); } }); return input; }, tick:function(cell, value){ //create and style input var input = $("<input type='checkbox'/>"); input.css({ "border":"1px", "background":"transparent", "margin-top":"5px", "box-sizing":"border-box", }) .val(value); setTimeout(function(){ input.focus(); },100) if(value === true || value === 'true' || value === 'True' || value === 1){ input.prop("checked", true) }else{ input.prop("checked", false) } //submit new value on blur input.on("change blur", function(e){ cell.trigger("editval", input.is(":checked")); }); //submit new value on enter input.on("keydown", function(e){ if(e.keyCode == 13){ cell.trigger("editval", input.is(":checked")); } }); return input; }, }, //deconstructor destroy: function() { }, });
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Observable_1 = require('../Observable'); var root_1 = require('../util/root'); var SymbolShim_1 = require('../util/SymbolShim'); var tryCatch_1 = require('../util/tryCatch'); var errorObject_1 = require('../util/errorObject'); var IteratorObservable = (function (_super) { __extends(IteratorObservable, _super); function IteratorObservable(iterator, project, thisArg, scheduler) { _super.call(this); this.project = project; this.thisArg = thisArg; this.scheduler = scheduler; if (iterator == null) { throw new Error('iterator cannot be null.'); } if (project && typeof project !== 'function') { throw new Error('When provided, `project` must be a function.'); } this.iterator = getIterator(iterator); } IteratorObservable.create = function (iterator, project, thisArg, scheduler) { return new IteratorObservable(iterator, project, thisArg, scheduler); }; IteratorObservable.dispatch = function (state) { var index = state.index, hasError = state.hasError, thisArg = state.thisArg, project = state.project, iterator = state.iterator, subscriber = state.subscriber; if (hasError) { subscriber.error(state.error); return; } var result = iterator.next(); if (result.done) { subscriber.complete(); return; } if (project) { result = tryCatch_1.tryCatch(project).call(thisArg, result.value, index); if (result === errorObject_1.errorObject) { state.error = errorObject_1.errorObject.e; state.hasError = true; } else { subscriber.next(result); state.index = index + 1; } } else { subscriber.next(result.value); state.index = index + 1; } if (subscriber.isUnsubscribed) { return; } this.schedule(state); }; IteratorObservable.prototype._subscribe = function (subscriber) { var index = 0; var _a = this, iterator = _a.iterator, project = _a.project, thisArg = _a.thisArg, scheduler = _a.scheduler; if (scheduler) { subscriber.add(scheduler.schedule(IteratorObservable.dispatch, 0, { index: index, thisArg: thisArg, project: project, iterator: iterator, subscriber: subscriber })); } else { do { var result = iterator.next(); if (result.done) { subscriber.complete(); break; } else if (project) { result = tryCatch_1.tryCatch(project).call(thisArg, result.value, index++); if (result === errorObject_1.errorObject) { subscriber.error(errorObject_1.errorObject.e); break; } subscriber.next(result); } else { subscriber.next(result.value); } if (subscriber.isUnsubscribed) { break; } } while (true); } }; return IteratorObservable; })(Observable_1.Observable); exports.IteratorObservable = IteratorObservable; var StringIterator = (function () { function StringIterator(str, idx, len) { if (idx === void 0) { idx = 0; } if (len === void 0) { len = str.length; } this.str = str; this.idx = idx; this.len = len; } StringIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function () { return (this); }; StringIterator.prototype.next = function () { return this.idx < this.len ? { done: false, value: this.str.charAt(this.idx++) } : { done: true, value: undefined }; }; return StringIterator; })(); var ArrayIterator = (function () { function ArrayIterator(arr, idx, len) { if (idx === void 0) { idx = 0; } if (len === void 0) { len = toLength(arr); } this.arr = arr; this.idx = idx; this.len = len; } ArrayIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function () { return this; }; ArrayIterator.prototype.next = function () { return this.idx < this.len ? { done: false, value: this.arr[this.idx++] } : { done: true, value: undefined }; }; return ArrayIterator; })(); function getIterator(obj) { var i = obj[SymbolShim_1.SymbolShim.iterator]; if (!i && typeof obj === 'string') { return new StringIterator(obj); } if (!i && obj.length !== undefined) { return new ArrayIterator(obj); } if (!i) { throw new TypeError('Object is not iterable'); } return obj[SymbolShim_1.SymbolShim.iterator](); } var maxSafeInteger = Math.pow(2, 53) - 1; function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function numberIsFinite(value) { return typeof value === 'number' && root_1.root.isFinite(value); } function sign(value) { var valueAsNumber = +value; if (valueAsNumber === 0) { return valueAsNumber; } if (isNaN(valueAsNumber)) { return valueAsNumber; } return valueAsNumber < 0 ? -1 : 1; } //# sourceMappingURL=IteratorObservable.js.map
YUI.add('yui-log-nodejs', function (Y, NAME) { var sys = require(process.binding('natives').util ? 'util' : 'sys'), hasColor = false; try { var stdio = require("stdio"); hasColor = stdio.isStderrATTY(); } catch (ex) { hasColor = true; } Y.config.useColor = hasColor; Y.consoleColor = function(str, num) { if (!this.config.useColor) { return str; } if (!num) { num = '32'; } return "\u001b[" + num +"m" + str + "\u001b[0m"; }; var logFn = function(str, t, m) { var id = '', lvl, mLvl; if (this.id) { id = '[' + this.id + ']:'; } t = t || 'info'; m = (m) ? this.consoleColor(' (' + m.toLowerCase() + '):', 35) : ''; if (str === null) { str = 'null'; } if ((typeof str === 'object') || str instanceof Array) { try { //Should we use this? if (str.tagName || str._yuid || str._query) { str = str.toString(); } else { str = sys.inspect(str); } } catch (e) { //Fail catcher } } lvl = '37;40'; mLvl = ((str) ? '' : 31); t = t+''; //Force to a string.. switch (t.toLowerCase()) { case 'error': lvl = mLvl = 31; break; case 'warn': lvl = 33; break; case 'debug': lvl = 34; break; } if (typeof str === 'string') { if (str && str.indexOf("\n") !== -1) { str = "\n" + str; } } // output log messages to stderr sys.error(this.consoleColor(t.toLowerCase() + ':', lvl) + m + ' ' + this.consoleColor(str, mLvl)); }; if (!Y.config.logFn) { Y.config.logFn = logFn; } }, '3.18.0');
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); const ImportDependency = require("./ImportDependency"); module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { constructor(request, range, module, loc) { super(null, module, loc); this.range = range; let dep = new ImportDependency(request, this); dep.loc = loc; this.addDependency(dep); } };
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueMaterial"] = factory(); else root["VueMaterial"] = factory(); })(this, (function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 461); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { var functional = options.functional var existing = functional ? options.render : options.beforeCreate if (!functional) { // inject component registration as beforeCreate hook options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } else { // register for functioal component in vue file options.render = function renderWithStyleInjection (h, context) { hook.call(context) return existing(h, context) } } } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }), /***/ 1: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Theme mixin // Grab the closest ancestor component's `md-theme` attribute OR grab the // `md-name` attribute from an `<md-theme>` component. function getAncestorThemeName(component) { if (!component) { return null; } var name = component.mdTheme; if (!name && component.$options._componentTag === 'md-theme') { name = component.mdName; } return name || getAncestorThemeName(component.$parent); } exports.default = { props: { mdTheme: String }, computed: { mdEffectiveTheme: function mdEffectiveTheme() { return getAncestorThemeName(this) || this.$material.currentTheme; }, themeClass: function themeClass() { return this.$material.prefix + this.mdEffectiveTheme; } }, watch: { mdTheme: function mdTheme(value) { this.$material.useTheme(value); } }, beforeMount: function beforeMount() { var localTheme = this.mdTheme; this.$material.useTheme(localTheme ? localTheme : 'default'); } }; module.exports = exports['default']; /***/ }), /***/ 210: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdIcon = __webpack_require__(211); var _mdIcon2 = _interopRequireDefault(_mdIcon); var _mdIcon3 = __webpack_require__(215); var _mdIcon4 = _interopRequireDefault(_mdIcon3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-icon', _mdIcon2.default); Vue.material.styles.push(_mdIcon4.default); } module.exports = exports['default']; /***/ }), /***/ 211: /***/ (function(module, exports, __webpack_require__) { var disposed = false function injectStyle (ssrContext) { if (disposed) return __webpack_require__(212) } var Component = __webpack_require__(0)( /* script */ __webpack_require__(213), /* template */ __webpack_require__(214), /* styles */ injectStyle, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) Component.options.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdIcon/mdIcon.vue" if (Component.esModule && Object.keys(Component.esModule).some((function (key) {return key !== "default" && key.substr(0, 2) !== "__"}))) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] mdIcon.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-2423dfc4", Component.options) } else { hotAPI.reload("data-v-2423dfc4", Component.options) } module.hot.dispose((function (data) { disposed = true })) })()} module.exports = Component.exports /***/ }), /***/ 212: /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 213: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(1); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var registeredIcons = {}; // // // // // // // // // // // // exports.default = { name: 'md-icon', props: { mdSrc: String, mdIconset: { type: String, default: 'material-icons' } }, data: function data() { return { svgContent: null, imageSrc: null }; }, mixins: [_mixin2.default], watch: { mdSrc: function mdSrc() { this.svgContent = null; this.imageSrc = null; this.checkSrc(); } }, methods: { isImage: function isImage(mimetype) { return mimetype.indexOf('image') >= 0; }, isSVG: function isSVG(mimetype) { return mimetype.indexOf('svg') >= 0; }, setSVGContent: function setSVGContent(value) { var _this = this; this.svgContent = value; this.$nextTick((function () { _this.$el.children[0].removeAttribute('fill'); })); }, loadSVG: function loadSVG() { if (!registeredIcons[this.mdSrc]) { var request = new XMLHttpRequest(); var self = this; request.open('GET', this.mdSrc, true); request.onload = function () { var mimetype = this.getResponseHeader('content-type'); if (this.status >= 200 && this.status < 400 && self.isImage(mimetype)) { if (self.isSVG(mimetype)) { registeredIcons[self.mdSrc] = this.response; self.setSVGContent(this.response); } else { self.loadImage(); } } else { console.warn('The file ' + self.mdSrc + ' is not a valid image.'); } }; request.send(); } else { this.setSVGContent(registeredIcons[this.mdSrc]); } }, loadImage: function loadImage() { this.imageSrc = this.mdSrc; }, checkSrc: function checkSrc() { if (this.mdSrc) { if (this.mdSrc.indexOf('.svg') >= 0) { this.loadSVG(); } else { this.loadImage(); } } } }, mounted: function mounted() { this.checkSrc(); } }; module.exports = exports['default']; /***/ }), /***/ 214: /***/ (function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return (_vm.svgContent) ? _c('i', { staticClass: "md-icon", class: [_vm.themeClass], domProps: { "innerHTML": _vm._s(_vm.svgContent) } }) : (_vm.imageSrc) ? _c('md-image', { staticClass: "md-icon", class: [_vm.themeClass], attrs: { "md-src": _vm.imageSrc } }) : _c('i', { staticClass: "md-icon", class: [_vm.themeClass, _vm.mdIconset], attrs: { "aria-hidden": !!_vm.mdIconset } }, [_vm._t("default")], 2) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-2423dfc4", module.exports) } } /***/ }), /***/ 215: /***/ (function(module, exports) { module.exports = ".THEME_NAME.md-icon.md-primary {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-icon.md-accent {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-icon.md-warn {\n color: WARN-COLOR; }\n" /***/ }), /***/ 461: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(210); /***/ }) /******/ }); }));
/** * Regression plugin. * * Uses regression-js library by Tom Alexander * http://tom-alexander.github.io/regression-js/ */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import * as regression from "regression"; import { Plugin } from "../../core/utils/Plugin"; import { registry } from "../../core/Registry"; import { EventDispatcher } from "../../core/utils/EventDispatcher"; import * as $object from "../../core/utils/Object"; import * as $type from "../../core/utils/Type"; ; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * A module which automatically calculates data for for trend lines using * various regression algorithms. * * By pushing an instance of [[Regression]] into `plugin` list of * any [[XYSeries]], it automatically recalculates and overrides its * data to show regression trend line, inestead of the source values. * * Example: * * ```TypeScript * let regseries = chart.series.push(new am4charts.LineSeries()); * regseries.dataFields.valueY = "value"; * regseries.dataFields.dateX = "date"; * * let reg = regseries.plugins.push(new am4plugins_regression.Regression()); * reg.method = "polynomial"; * ``` * ```JavaScript * var regseries = chart.series.push(new am4charts.LineSeries()); * regseries.dataFields.valueY = "value"; * regseries.dataFields.dateX = "date"; * * var reg = regseries.plugins.push(new am4plugins_regression.Regression()); * reg.method = "polynomial"; * ``` * ```JSON * { * // ... * "series": [{ * // ... * }, { * "type": "LineSeries", * "dataFields": { * "valueY": "value", * "dateX": "date" * }, * "plugins": [{ * "type": "Regression", * "method": "polynomial" * }] * }] * } * ``` * * @since 4.2.2 */ var Regression = /** @class */ (function (_super) { __extends(Regression, _super); /** * Constructor */ function Regression() { var _this = // Nothing to do here _super.call(this) || this; /** * An [[EventDispatcher]] instance. * * @since 4.3.14 */ _this.events = new EventDispatcher(); /** * Method */ _this._method = "linear"; /** * Options */ _this._options = {}; /** * Simplify output data. */ _this._simplify = false; /** * Reorder data after calculation */ _this._reorder = false; /** * Hash of the data original data. Used to check whether we need to * recalculate, or the data did not change. */ _this._originalDataHash = ""; /** * Should skip next "beforedatavalidated" event? */ _this._skipValidatedEvent = false; return _this; } Regression.prototype.init = function () { _super.prototype.init.call(this); this.processSeries(); }; /** * Decorates series with required events and adapters used to hijack its * data. */ Regression.prototype.processSeries = function () { var _this = this; this.invalidateData(); // Invalidate calculated data whenever data updates this._disposers.push(this.target.events.on("beforedatavalidated", function (ev) { if (_this._skipValidatedEvent) { _this._skipValidatedEvent = false; return; } // Update data _this.saveOriginalData(); _this.calcData(); })); if (this.target.chart) { this._disposers.push(this.target.chart.events.on("beforedatavalidated", function (ev) { _this.target.invalidateData(); })); } // Add data adapter this.target.adapter.add("data", function () { if (_this._data === undefined) { _this.calcData(); } return _this._data; }); // Save original series data this.saveOriginalData(); }; /** * Saves series' original data and (re)adds data adapter. */ Regression.prototype.saveOriginalData = function () { // Temporarily disable the data adapter this.target.adapter.disableKey("data"); // Save if (this.target.data && this.target.data.length) { this._originalData = this.target.data; } // Re-enabled the adapter this.target.adapter.enableKey("data"); }; /** * Invalidates data. */ Regression.prototype.invalidateData = function () { this._data = undefined; }; /** * Calculates regression series data. */ Regression.prototype.calcData = function () { this._data = []; var series = this.target; // Get series' data (global or series own) var seriesData = this._originalData; if (!seriesData || seriesData.length == 0) { seriesData = this.target.baseSprite.data; } // Determine if this line is pivoted (horizontal value axis) // If both axes are value, we consider the line to be horizontal. var pivot = series.dataFields.valueX && !series.dataFields.valueY ? true : false; var valueField = pivot ? series.dataFields.valueX : series.dataFields.valueY; var positionField = pivot ? series.dataFields.valueY : series.dataFields.valueX; // Assemble series' own data var newData = []; var _loop_1 = function (i) { var item = {}; $object.each(this_1.target.dataFields, function (key, val) { item[val] = seriesData[i][val]; }); if ($type.hasValue(item[valueField])) { newData.push(item); } }; var this_1 = this; for (var i = 0; i < seriesData.length; i++) { _loop_1(i); } // Order data points if (this.reorder) { newData.sort(function (a, b) { if (a[positionField] > b[positionField]) { return 1; } else if (a[positionField] < b[positionField]) { return -1; } else { return 0; } }); } // Build matrix for the regression function var matrix = []; //const pivot = series.dataFields.valueX && !series.dataFields.valueY ? true : false; for (var i = 0; i < newData.length; i++) { var x = series.dataFields.valueX && pivot ? newData[i][series.dataFields.valueX] : i; var y = series.dataFields.valueY && !pivot ? newData[i][series.dataFields.valueY] : i; matrix.push(pivot ? [y, x] : [x, y]); } // Calculate regression values var result = []; switch (this.method) { case "polynomial": result = regression.polynomial(matrix, this.options); break; default: result = regression.linear(matrix, this.options); } // Set results this.result = result; // Invoke event var hash = btoa(JSON.stringify(newData)); if (hash != this._originalDataHash) { this.events.dispatchImmediately("processed", { type: "processed", target: this }); } this._originalDataHash = hash; // Build data this._data = []; var _loop_2 = function (i) { if (this_2.simplify && i) { i = result.points.length - 1; } var item = {}; $object.each(this_2.target.dataFields, function (key, val) { if ((key == "valueY" && !pivot) || (key == "valueX" && pivot)) { item[val] = result.points[i][1]; } else { item[val] = newData[i][val]; } }); this_2._data.push(item); out_i_1 = i; }; var this_2 = this, out_i_1; for (var i = 0; i < result.points.length; i++) { _loop_2(i); i = out_i_1; } }; Object.defineProperty(Regression.prototype, "method", { /** * @return Method */ get: function () { return this._method; }, /** * Method to calculate regression. * * Supported values: "linear" (default), "polynomial". * * @default linear * @param value Method */ set: function (value) { if (this._method != value) { this._method = value; this.invalidateData(); } }, enumerable: true, configurable: true }); Object.defineProperty(Regression.prototype, "options", { /** * @return Options */ get: function () { return this._options; }, /** * Regression output options. * * Below are default values. * * ```JSON * { * order: 2, * precision: 2, * } * ``` * * @see {@link https://github.com/Tom-Alexander/regression-js#configuration-options} About options * @param value Options */ set: function (value) { if (this._options != value) { this._options = value; this.invalidateData(); } }, enumerable: true, configurable: true }); Object.defineProperty(Regression.prototype, "simplify", { /** * @return Simplify? */ get: function () { return this._simplify; }, /** * Simplify regression line data? If set to `true` it will use only two * result data points: first and last. * * NOTE: this does make sense with "linear" method only. * * @default false * @since 4.2.3 * @param value Simplify? */ set: function (value) { if (this._simplify != value) { this._simplify = value; this.invalidateData(); } }, enumerable: true, configurable: true }); Object.defineProperty(Regression.prototype, "reorder", { /** * @return Reorder data? */ get: function () { return this._reorder; }, /** * Orders data points after calculation. This can make sense in scatter plot * scenarios where data points can come in non-linear fashion. * * @default false * @since 4.2.3 * @param value Reorder data? */ set: function (value) { if (this._reorder != value) { this._reorder = value; this.invalidateData(); } }, enumerable: true, configurable: true }); return Regression; }(Plugin)); export { Regression }; /** * Register class in system, so that it can be instantiated using its name from * anywhere. * * @ignore */ registry.registeredClasses["Regression"] = Regression; //# sourceMappingURL=Regression.js.map
'use strict'; module.exports = { app: { title: 'MEAN.JS', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'mongodb, express, angularjs, node.js, mongoose, passport', googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID' }, port: process.env.PORT || 3000, host: process.env.HOST || '0.0.0.0', templateEngine: 'swig', // Session Cookie settings sessionCookie: { // session expiration is set by default to 24 hours maxAge: 24 * (60 * 60 * 1000), // httpOnly flag makes sure the cookie is only accessed // through the HTTP protocol and not JS/browser httpOnly: true, // secure cookie should be turned to true to provide additional // layer of security so that the cookie is set only when working // in HTTPS mode. secure: false }, // sessionSecret should be changed for security measures and concerns sessionSecret: process.env.SESSION_SECRET || 'MEAN', // sessionKey is set to the generic sessionId key used by PHP applications // for obsecurity reasons sessionKey: 'sessionId', sessionCollection: 'sessions', logo: 'modules/core/client/img/brand/logo.png', favicon: 'modules/core/client/img/brand/favicon.ico', uploads: { profileUpload: { dest: './modules/users/client/img/profile/uploads/', // Profile upload destination path limits: { fileSize: 1*1024*1024 // Max file size in bytes (1 MB) } } } };
import { JOSENotSupported } from '../util/errors.js'; export default function subtleRsaEs(alg) { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return 'RSA-OAEP'; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } }
/** * The MIT License (MIT) * * Copyright (c) 2015 Famous Industries Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; /** * Collection to map keyboard codes in plain english * * @class KeyCodes * @static */ module.exports = { 0: 48, 1: 49, 2: 50, 3: 51, 4: 52, 5: 53, 6: 54, 7: 55, 8: 56, 9: 57, a: 97, b: 98, c: 99, d: 100, e: 101, f: 102, g: 103, h: 104, i: 105, j: 106, k: 107, l: 108, m: 109, n: 110, o: 111, p: 112, q: 113, r: 114, s: 115, t: 116, u: 117, v: 118, w: 119, x: 120, y: 121, z: 122, A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77, N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90, ENTER : 13, LEFT_ARROW: 37, RIGHT_ARROW: 39, UP_ARROW: 38, DOWN_ARROW: 40, SPACE: 32, SHIFT: 16, TAB: 9 };
module.exports = function (fn, delay, execAsap) { var timeout; // Keep a reference to the timeout outside the function return function () { // Keep the functions execution context and arguments in tact var that = this, args = arguments; // If we already have a function ready to execute, clear it // Else if we are allowed to execute immediately, call the function if (timeout) { clearTimeout(timeout); } else if (execAsap) { fn.apply(that, args); } timeout = setTimeout(function () { execAsap || fn.apply(that, args); timeout = null; }, delay || 100); }; };
export { default } from './Alert';
"use strict"; let x = "x"; function named_fn(a, b) { if (true) { (function() { console.log(x); })(); } // let x must be renamed or else it will shadow the reference on line 5 for (let x = 0; x < 2; x++) { console.log(x); } } named_fn();
/** * @fileoverview Generated externs. DO NOT EDIT! * @externs */ /** @const */ var shaka = {}; /** @const */ shaka.media = {}; /** @const */ shaka.hls = {}; /** @const */ shaka.offline = {}; /** @const */ shaka.util = {}; /** @const */ shaka.polyfill = {}; /** @const */ shaka.media.TextEngine = {}; /** @const */ shaka.util.StringUtils = {}; /** @const */ shaka.net = {}; /** @const */ shaka.util.Uint8ArrayUtils = {}; /** @const */ shaka.cast = {}; /** @const */ shaka.abr = {}; /** @const */ shaka.dash = {}; /** @const */ shaka.media.ManifestParser = {}; /** * An interface to standardize how objects are destroyed. * @interface */ shaka.util.IDestroyable = function() {}; /** * Destroys the object, releasing all resources and shutting down all * operations. Returns a Promise which is resolved when destruction is * complete. This Promise should never be rejected. * @return {!Promise} */ shaka.util.IDestroyable.prototype.destroy = function() {}; /** * @param {string} mimeType * @param {!shakaExtern.TextParserPlugin} plugin */ shaka.media.TextEngine.registerParser = function(mimeType, plugin) {}; /** * @param {string} mimeType */ shaka.media.TextEngine.unregisterParser = function(mimeType) {}; /** * Creates a cue using the best platform-specific interface available. * @param {number} startTime * @param {number} endTime * @param {string} payload * @return {TextTrackCue} or null if the parameters were invalid. */ shaka.media.TextEngine.makeCue = function(startTime, endTime, payload) {}; /** * Creates a new Error. * @param {shaka.util.Error.Severity} severity * @param {shaka.util.Error.Category} category * @param {shaka.util.Error.Code} code * @param {...*} var_args * @constructor * @struct * @extends {Error} */ shaka.util.Error = function(severity, category, code, var_args) {}; /** * @type {shaka.util.Error.Severity} */ shaka.util.Error.prototype.severity; /** * @const {shaka.util.Error.Category} */ shaka.util.Error.prototype.category; /** * @const {shaka.util.Error.Code} */ shaka.util.Error.prototype.code; /** * @const {!Array.<*>} */ shaka.util.Error.prototype.data; /** * @enum {number} */ shaka.util.Error.Severity = { 'RECOVERABLE': 1, 'CRITICAL': 2 }; /** * @enum {number} */ shaka.util.Error.Category = { 'NETWORK': 1, 'TEXT': 2, 'MEDIA': 3, 'MANIFEST': 4, 'STREAMING': 5, 'DRM': 6, 'PLAYER': 7, 'CAST': 8, 'STORAGE': 9 }; /** * @enum {number} */ shaka.util.Error.Code = { 'UNSUPPORTED_SCHEME': 1000, 'BAD_HTTP_STATUS': 1001, 'HTTP_ERROR': 1002, 'TIMEOUT': 1003, 'MALFORMED_DATA_URI': 1004, 'UNKNOWN_DATA_URI_ENCODING': 1005, 'REQUEST_FILTER_ERROR': 1006, 'RESPONSE_FILTER_ERROR': 1007, 'INVALID_TEXT_HEADER': 2000, 'INVALID_TEXT_CUE': 2001, 'UNABLE_TO_DETECT_ENCODING': 2003, 'BAD_ENCODING': 2004, 'INVALID_XML': 2005, 'INVALID_MP4_TTML': 2007, 'INVALID_MP4_VTT': 2008, 'BUFFER_READ_OUT_OF_BOUNDS': 3000, 'JS_INTEGER_OVERFLOW': 3001, 'EBML_OVERFLOW': 3002, 'EBML_BAD_FLOATING_POINT_SIZE': 3003, 'MP4_SIDX_WRONG_BOX_TYPE': 3004, 'MP4_SIDX_INVALID_TIMESCALE': 3005, 'MP4_SIDX_TYPE_NOT_SUPPORTED': 3006, 'WEBM_CUES_ELEMENT_MISSING': 3007, 'WEBM_EBML_HEADER_ELEMENT_MISSING': 3008, 'WEBM_SEGMENT_ELEMENT_MISSING': 3009, 'WEBM_INFO_ELEMENT_MISSING': 3010, 'WEBM_DURATION_ELEMENT_MISSING': 3011, 'WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING': 3012, 'WEBM_CUE_TIME_ELEMENT_MISSING': 3013, 'MEDIA_SOURCE_OPERATION_FAILED': 3014, 'MEDIA_SOURCE_OPERATION_THREW': 3015, 'VIDEO_ERROR': 3016, 'QUOTA_EXCEEDED_ERROR': 3017, 'UNABLE_TO_GUESS_MANIFEST_TYPE': 4000, 'DASH_INVALID_XML': 4001, 'DASH_NO_SEGMENT_INFO': 4002, 'DASH_EMPTY_ADAPTATION_SET': 4003, 'DASH_EMPTY_PERIOD': 4004, 'DASH_WEBM_MISSING_INIT': 4005, 'DASH_UNSUPPORTED_CONTAINER': 4006, 'DASH_PSSH_BAD_ENCODING': 4007, 'DASH_NO_COMMON_KEY_SYSTEM': 4008, 'DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED': 4009, 'DASH_CONFLICTING_KEY_IDS': 4010, 'UNPLAYABLE_PERIOD': 4011, 'RESTRICTIONS_CANNOT_BE_MET': 4012, 'NO_PERIODS': 4014, 'HLS_PLAYLIST_HEADER_MISSING': 4015, 'INVALID_HLS_TAG': 4016, 'HLS_INVALID_PLAYLIST_HIERARCHY': 4017, 'DASH_DUPLICATE_REPRESENTATION_ID': 4018, 'HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND': 4020, 'HLS_COULD_NOT_GUESS_MIME_TYPE': 4021, 'HLS_MASTER_PLAYLIST_NOT_PROVIDED': 4022, 'HLS_REQUIRED_ATTRIBUTE_MISSING': 4023, 'HLS_REQUIRED_TAG_MISSING': 4024, 'HLS_COULD_NOT_GUESS_CODECS': 4025, 'HLS_KEYFORMATS_NOT_SUPPORTED': 4026, 'INVALID_STREAMS_CHOSEN': 5005, 'NO_RECOGNIZED_KEY_SYSTEMS': 6000, 'REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE': 6001, 'FAILED_TO_CREATE_CDM': 6002, 'FAILED_TO_ATTACH_TO_VIDEO': 6003, 'INVALID_SERVER_CERTIFICATE': 6004, 'FAILED_TO_CREATE_SESSION': 6005, 'FAILED_TO_GENERATE_LICENSE_REQUEST': 6006, 'LICENSE_REQUEST_FAILED': 6007, 'LICENSE_RESPONSE_REJECTED': 6008, 'ENCRYPTED_CONTENT_WITHOUT_DRM_INFO': 6010, 'NO_LICENSE_SERVER_GIVEN': 6012, 'OFFLINE_SESSION_REMOVED': 6013, 'EXPIRED': 6014, 'LOAD_INTERRUPTED': 7000, 'CAST_API_UNAVAILABLE': 8000, 'NO_CAST_RECEIVERS': 8001, 'ALREADY_CASTING': 8002, 'UNEXPECTED_CAST_ERROR': 8003, 'CAST_CANCELED_BY_USER': 8004, 'CAST_CONNECTION_TIMED_OUT': 8005, 'CAST_RECEIVER_APP_UNAVAILABLE': 8006, 'STORAGE_NOT_SUPPORTED': 9000, 'INDEXED_DB_ERROR': 9001, 'OPERATION_ABORTED': 9002, 'REQUESTED_ITEM_NOT_FOUND': 9003, 'MALFORMED_OFFLINE_URI': 9004, 'CANNOT_STORE_LIVE_OFFLINE': 9005, 'STORE_ALREADY_IN_PROGRESS': 9006, 'NO_INIT_DATA_FOR_OFFLINE': 9007 }; /** * Creates an InitSegmentReference, which provides the location to an * initialization segment. * @param {function():!Array.<string>} uris * A function that creates the URIs of the resource containing the segment. * @param {number} startByte The offset from the start of the resource to the * start of the segment. * @param {?number} endByte The offset from the start of the resource to the * end of the segment, inclusive. null indicates that the segment extends * to the end of the resource. * @constructor * @struct */ shaka.media.InitSegmentReference = function(uris, startByte, endByte) {}; /** * Creates a SegmentReference, which provides the start time, end time, and * location to a media segment. * @param {number} position The segment's position within a particular Period. * The following should hold true between any two SegmentReferences from the * same Period, r1 and r2: * IF r2.position > r1.position THEN * [ (r2.startTime > r1.startTime) OR * (r2.startTime == r1.startTime AND r2.endTime >= r1.endTime) ] * @param {number} startTime The segment's start time in seconds, relative to * the start of a particular Period. * @param {number} endTime The segment's end time in seconds, relative to * the start of a particular Period. The segment ends the instant before * this time, so |endTime| must be strictly greater than |startTime|. * @param {function():!Array.<string>} uris * A function that creates the URIs of the resource containing the segment. * @param {number} startByte The offset from the start of the resource to the * start of the segment. * @param {?number} endByte The offset from the start of the resource to the * end of the segment, inclusive. null indicates that the segment extends * to the end of the resource. * @constructor * @struct */ shaka.media.SegmentReference = function(position, startTime, endTime, uris, startByte, endByte) {}; /** * Creates a PresentationTimeline. * @param {?number} presentationStartTime The wall-clock time, in seconds, * when the presentation started or will start. Only required for live. * @param {number} presentationDelay The delay to give the presentation, in * seconds. Only required for live. * @see {shakaExtern.Manifest} * @see {@tutorial architecture} * @constructor * @struct */ shaka.media.PresentationTimeline = function(presentationStartTime, presentationDelay) {}; /** * @return {number} The presentation's duration in seconds. * Infinity indicates that the presentation continues indefinitely. */ shaka.media.PresentationTimeline.prototype.getDuration = function() {}; /** * Sets the presentation's duration. * @param {number} duration The presentation's duration in seconds. * Infinity indicates that the presentation continues indefinitely. */ shaka.media.PresentationTimeline.prototype.setDuration = function(duration) {}; /** * @return {?number} The presentation's start time in seconds. */ shaka.media.PresentationTimeline.prototype.getPresentationStartTime = function() {}; /** * Sets the clock offset, which is the the difference between the client's clock * and the server's clock, in milliseconds (i.e., serverTime = Date.now() + * clockOffset). * @param {number} offset The clock offset, in ms. */ shaka.media.PresentationTimeline.prototype.setClockOffset = function(offset) {}; /** * Sets the presentation's static flag. * @param {boolean} isStatic If true, the presentation is static, meaning all * segments are available at once. */ shaka.media.PresentationTimeline.prototype.setStatic = function(isStatic) {}; /** * Gets the presentation's segment availability duration, which is the amount * of time, in seconds, that the start of a segment remains available after the * live-edge moves past the end of that segment. Infinity indicates that * segments remain available indefinitely. For example, if your live * presentation has a 5 minute DVR window and your segments are 10 seconds long * then the segment availability duration should be 4 minutes and 50 seconds. * @return {number} The presentation's segment availability duration. */ shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityDuration = function() {}; /** * Sets the presentation's segment availability duration. The segment * availability duration should only be set for live. * @param {number} segmentAvailabilityDuration The presentation's new segment * availability duration in seconds. */ shaka.media.PresentationTimeline.prototype.setSegmentAvailabilityDuration = function(segmentAvailabilityDuration) {}; /** * Gives PresentationTimeline a Stream's segments so it can size and position * the segment availability window, and account for missing segment * information. This function should be called once for each Stream (no more, * no less). * @param {number} periodStartTime * @param {!Array.<!shaka.media.SegmentReference>} references */ shaka.media.PresentationTimeline.prototype.notifySegments = function(periodStartTime, references) {}; /** * Gives PresentationTimeline a Stream's maximum segment duration so it can * size and position the segment availability window. This function should be * called once for each Stream (no more, no less), but does not have to be * called if notifySegments() is called instead for a particular stream. * @param {number} maxSegmentDuration The maximum segment duration for a * particular stream. */ shaka.media.PresentationTimeline.prototype.notifyMaxSegmentDuration = function(maxSegmentDuration) {}; /** * @return {boolean} True if the presentation is live; otherwise, return * false. */ shaka.media.PresentationTimeline.prototype.isLive = function() {}; /** * @return {boolean} True if the presentation is in progress (meaning not live, * but also not completely available); otherwise, return false. */ shaka.media.PresentationTimeline.prototype.isInProgress = function() {}; /** * Gets the presentation's current segment availability start time. Segments * ending at or before this time should be assumed to be unavailable. * @return {number} The current segment availability start time, in seconds, * relative to the start of the presentation. */ shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityStart = function() {}; /** * Gets the presentation's current segment availability start time, offset by * the given amount. This is used to ensure that we don't "fall" back out of * the availability window while we are buffering. * @param {number} offset The offset to add to the start time. * @return {number} The current segment availability start time, in seconds, * relative to the start of the presentation. */ shaka.media.PresentationTimeline.prototype.getSafeAvailabilityStart = function(offset) {}; /** * Gets the presentation's current segment availability end time. Segments * starting after this time should be assumed to be unavailable. * @return {number} The current segment availability end time, in seconds, * relative to the start of the presentation. Always returns the * presentation's duration for video-on-demand. */ shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityEnd = function() {}; /** * Gets the seek range end. * @return {number} */ shaka.media.PresentationTimeline.prototype.getSeekRangeEnd = function() {}; /** * NetworkingEngine wraps all networking operations. This accepts plugins that * handle the actual request. A plugin is registered using registerScheme. * Each scheme has at most one plugin to handle the request. * @param {function(number, number)=} opt_onSegmentDownloaded Called * when a segment is downloaded. Passed the duration, in milliseconds, that * the request took; and the total number of bytes transferred. * @struct * @constructor * @implements {shaka.util.IDestroyable} */ shaka.net.NetworkingEngine = function(opt_onSegmentDownloaded) {}; /** * Request types. Allows a filter to decide which requests to read/alter. * @enum {number} */ shaka.net.NetworkingEngine.RequestType = { 'MANIFEST': 0, 'SEGMENT': 1, 'LICENSE': 2, 'APP': 3 }; /** * Registers a scheme plugin. This plugin will handle all requests with the * given scheme. If a plugin with the same scheme already exists, it is * replaced. * @param {string} scheme * @param {shakaExtern.SchemePlugin} plugin */ shaka.net.NetworkingEngine.registerScheme = function(scheme, plugin) {}; /** * Removes a scheme plugin. * @param {string} scheme */ shaka.net.NetworkingEngine.unregisterScheme = function(scheme) {}; /** * Registers a new request filter. All filters are applied in the order they * are registered. * @param {shakaExtern.RequestFilter} filter */ shaka.net.NetworkingEngine.prototype.registerRequestFilter = function(filter) {}; /** * Removes a request filter. * @param {shakaExtern.RequestFilter} filter */ shaka.net.NetworkingEngine.prototype.unregisterRequestFilter = function(filter) {}; /** * Clear all request filters. */ shaka.net.NetworkingEngine.prototype.clearAllRequestFilters = function() {}; /** * Registers a new response filter. All filters are applied in the order they * are registered. * @param {shakaExtern.ResponseFilter} filter */ shaka.net.NetworkingEngine.prototype.registerResponseFilter = function(filter) {}; /** * Removes a response filter. * @param {shakaExtern.ResponseFilter} filter */ shaka.net.NetworkingEngine.prototype.unregisterResponseFilter = function(filter) {}; /** * Clear all response filters. */ shaka.net.NetworkingEngine.prototype.clearAllResponseFilters = function() {}; /** * @override */ shaka.net.NetworkingEngine.prototype.destroy = function() {}; /** * Makes a network request and returns the resulting data. * @param {shaka.net.NetworkingEngine.RequestType} type * @param {shakaExtern.Request} request * @return {!Promise.<shakaExtern.Response>} */ shaka.net.NetworkingEngine.prototype.request = function(type, request) {}; /** * Creates a string from the given buffer as UTF-8 encoding. * @param {?BufferSource} data * @return {string} * @throws {shaka.util.Error} */ shaka.util.StringUtils.fromUTF8 = function(data) {}; /** * Creates a string from the given buffer as UTF-16 encoding. * @param {?BufferSource} data * @param {boolean} littleEndian true to read little endian, false to read big. * @return {string} * @throws {shaka.util.Error} */ shaka.util.StringUtils.fromUTF16 = function(data, littleEndian) {}; /** * Creates a string from the given buffer, auto-detecting the encoding that is * being used. If it cannot detect the encoding, it will throw an exception. * @param {?BufferSource} data * @return {string} * @throws {shaka.util.Error} */ shaka.util.StringUtils.fromBytesAutoDetect = function(data) {}; /** * Creates a ArrayBuffer from the given string, converting to UTF-8 encoding. * @param {string} str * @return {!ArrayBuffer} */ shaka.util.StringUtils.toUTF8 = function(str) {}; /** * Convert a Uint8Array to a base64 string. The output will always use the * alternate encoding/alphabet also known as "base64url". * @param {!Uint8Array} arr * @param {boolean=} opt_padding If true, pad the output with equals signs. * Defaults to true. * @return {string} */ shaka.util.Uint8ArrayUtils.toBase64 = function(arr, opt_padding) {}; /** * Convert a base64 string to a Uint8Array. Accepts either the standard * alphabet or the alternate "base64url" alphabet. * @param {string} str * @return {!Uint8Array} */ shaka.util.Uint8ArrayUtils.fromBase64 = function(str) {}; /** * Convert a hex string to a Uint8Array. * @param {string} str * @return {!Uint8Array} */ shaka.util.Uint8ArrayUtils.fromHex = function(str) {}; /** * Convert a Uint8Array to a hex string. * @param {!Uint8Array} arr * @return {string} */ shaka.util.Uint8ArrayUtils.toHex = function(arr) {}; /** * Compare two Uint8Arrays for equality. * @param {Uint8Array} arr1 * @param {Uint8Array} arr2 * @return {boolean} */ shaka.util.Uint8ArrayUtils.equal = function(arr1, arr2) {}; /** * Concatenate Uint8Arrays. * @param {...Uint8Array} var_args * @return {Uint8Array} */ shaka.util.Uint8ArrayUtils.concat = function(var_args) {}; /** * <p> * This defines the default ABR manager for the Player. An instance of this * class is used when no ABR manager is given. * </p> * <p> * The behavior of this class is to take throughput samples using * segmentDownloaded to estimate the current network bandwidth. Then it will * use that to choose the streams that best fit the current bandwidth. It will * always pick the highest bandwidth variant it thinks can be played. * </p> * <p> * After the initial choice (in chooseStreams), this class will call * switchCallback() when there is a better choice. switchCallback() will not * be called more than once per * ({@link shaka.abr.SimpleAbrManager.SWITCH_INTERVAL_MS}). * </p> * <p> * This does not adapt for text streams, it will always select the first one. * </p> * @constructor * @struct * @implements {shakaExtern.AbrManager} */ shaka.abr.SimpleAbrManager = function() {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.stop = function() {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.init = function(switchCallback) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.chooseStreams = function(mediaTypesToUpdate) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.enable = function() {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.disable = function() {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.segmentDownloaded = function(deltaTimeMs, numBytes) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.getBandwidthEstimate = function() {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.setDefaultEstimate = function(estimate) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.setRestrictions = function(restrictions) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.setVariants = function(variants) {}; /** * @override */ shaka.abr.SimpleAbrManager.prototype.setTextStreams = function(streams) {}; /** * Registers a manifest parser by file extension. * @param {string} extension The file extension of the manifest. * @param {shakaExtern.ManifestParser.Factory} parserFactory The factory * used to create parser instances. */ shaka.media.ManifestParser.registerParserByExtension = function(extension, parserFactory) {}; /** * Registers a manifest parser by MIME type. * @param {string} mimeType The MIME type of the manifest. * @param {shakaExtern.ManifestParser.Factory} parserFactory The factory * used to create parser instances. */ shaka.media.ManifestParser.registerParserByMime = function(mimeType, parserFactory) {}; /** * Creates a DataViewReader, which abstracts a DataView object. * @param {!DataView} dataView The DataView. * @param {shaka.util.DataViewReader.Endianness} endianness The endianness. * @struct * @constructor */ shaka.util.DataViewReader = function(dataView, endianness) {}; /** * Endianness. * @enum {number} */ shaka.util.DataViewReader.Endianness = { BIG_ENDIAN: 0, LITTLE_ENDIAN: 1 }; /** * @return {boolean} True if the reader has more data, false otherwise. */ shaka.util.DataViewReader.prototype.hasMoreData = function() {}; /** * Gets the current byte position. * @return {number} */ shaka.util.DataViewReader.prototype.getPosition = function() {}; /** * Gets the byte length of the DataView. * @return {number} */ shaka.util.DataViewReader.prototype.getLength = function() {}; /** * Reads an unsigned 8 bit integer, and advances the reader. * @return {number} The integer. * @throws {shaka.util.Error} when reading past the end of the data view. */ shaka.util.DataViewReader.prototype.readUint8 = function() {}; /** * Reads an unsigned 16 bit integer, and advances the reader. * @return {number} The integer. * @throws {shaka.util.Error} when reading past the end of the data view. */ shaka.util.DataViewReader.prototype.readUint16 = function() {}; /** * Reads an unsigned 32 bit integer, and advances the reader. * @return {number} The integer. * @throws {shaka.util.Error} when reading past the end of the data view. */ shaka.util.DataViewReader.prototype.readUint32 = function() {}; /** * Reads a signed 32 bit integer, and advances the reader. * @return {number} The integer. * @throws {shaka.util.Error} when reading past the end of the data view. */ shaka.util.DataViewReader.prototype.readInt32 = function() {}; /** * Reads an unsigned 64 bit integer, and advances the reader. * @return {number} The integer. * @throws {shaka.util.Error} when reading past the end of the data view or * when reading an integer too large to store accurately in JavaScript. */ shaka.util.DataViewReader.prototype.readUint64 = function() {}; /** * Reads the specified number of raw bytes. * @param {number} bytes The number of bytes to read. * @return {!Uint8Array} * @throws {shaka.util.Error} when reading past the end of the data view. */ shaka.util.DataViewReader.prototype.readBytes = function(bytes) {}; /** * Skips the specified number of bytes. * @param {number} bytes The number of bytes to skip. * @throws {shaka.util.Error} when skipping past the end of the data view. */ shaka.util.DataViewReader.prototype.skip = function(bytes) {}; /** * Keeps reading until it reaches a byte that equals to zero. The text is * assumed to be UTF-8. * @return {string} */ shaka.util.DataViewReader.prototype.readTerminatedString = function() {}; /** * Create a new MP4 Parser * @struct * @constructor */ shaka.util.Mp4Parser = function() {}; /** * @typedef {{ * parser: !shaka.util.Mp4Parser, * start: number, * size: number, * version: ?number, * flags: ?number, * reader: !shaka.util.DataViewReader * }} * @property {!shaka.util.Mp4Parser} parser * The parser that parsed this box. The parser can be used to parse child * boxes where the configuration of the current parser is needed to parsed * other boxes. * @property {number} start * The start of this box (before the header) in the original buffer. This * start position is the absolute position. * @property {number} size * The size of this box (including the header). * @property {?number} version * The version for a full box, null for basic boxes. * @property {?number} flags * The flags for a full box, null for basic boxes. * @property {!shaka.util.DataViewReader} reader * The reader for this box is only for this box. Reading or not reading to * the end will have no affect on the parser reading other sibling boxes. */ shaka.util.Mp4Parser.ParsedBox; /** * @typedef {function(!shaka.util.Mp4Parser.ParsedBox)} */ shaka.util.Mp4Parser.CallbackType; /** * Delcare a box type as a Box. * @param {string} type * @param {!shaka.util.Mp4Parser.CallbackType} definition * @return {!shaka.util.Mp4Parser} */ shaka.util.Mp4Parser.prototype.box = function(type, definition) {}; /** * Declare a box type as a Full Box. * @param {string} type * @param {!shaka.util.Mp4Parser.CallbackType} definition * @return {!shaka.util.Mp4Parser} */ shaka.util.Mp4Parser.prototype.fullBox = function(type, definition) {}; /** * Parse the given data using the added callbacks. * @param {!ArrayBuffer} data */ shaka.util.Mp4Parser.prototype.parse = function(data) {}; /** * Parse the next box on the current level. * @param {number} absStart The absolute start position in the original * byte array * @param {!shaka.util.DataViewReader} reader */ shaka.util.Mp4Parser.prototype.parseNext = function(absStart, reader) {}; /** * A callback that tells the Mp4 parser to treat the body of a box as a series * of boxes. The number of boxes is limited by the size of the parent box. * @param {!shaka.util.Mp4Parser.ParsedBox} box */ shaka.util.Mp4Parser.children = function(box) {}; /** * A callback that tells the Mp4 parser to treat the body of a box as a sample * description. A sample description box has a fixed number of children. The * number of children is represented by a 4 byte unsigned integer. Each child * is a box. * @param {!shaka.util.Mp4Parser.ParsedBox} box */ shaka.util.Mp4Parser.sampleDescription = function(box) {}; /** * Create a callback that tells the Mp4 parser to treat the body of a box as a * binary blob and how to handle it. * @param {!function(!Uint8Array)} callback * @return {!shaka.util.Mp4Parser.CallbackType} */ shaka.util.Mp4Parser.allData = function(callback) {}; /** * A work-alike for EventTarget. Only DOM elements may be true EventTargets, * but this can be used as a base class to provide event dispatch to non-DOM * classes. Only FakeEvents should be dispatched. * @struct * @constructor * @implements {EventTarget} */ shaka.util.FakeEventTarget = function() {}; /** * These are the listener types defined in the closure extern for EventTarget. * @typedef {EventListener|function(!Event):(boolean|undefined)} */ shaka.util.FakeEventTarget.ListenerType; /** * Add an event listener to this object. * @param {string} type The event type to listen for. * @param {shaka.util.FakeEventTarget.ListenerType} listener The callback or * listener object to invoke. * @param {(EventListenerOptions|boolean)=} opt_options Ignored. * @override */ shaka.util.FakeEventTarget.prototype.addEventListener = function(type, listener, opt_options) {}; /** * Remove an event listener from this object. * @param {string} type The event type for which you wish to remove a listener. * @param {shaka.util.FakeEventTarget.ListenerType} listener The callback or * listener object to remove. * @param {(EventListenerOptions|boolean)=} opt_options Ignored. * @override */ shaka.util.FakeEventTarget.prototype.removeEventListener = function(type, listener, opt_options) {}; /** * Dispatch an event from this object. * @param {!Event} event The event to be dispatched from this object. * @return {boolean} True if the default action was prevented. * @override */ shaka.util.FakeEventTarget.prototype.dispatchEvent = function(event) {}; /** * Construct a Player. * @param {!HTMLMediaElement} video Any existing TextTracks attached to this * element that were not created by Shaka will be disabled. A new TextTrack * may be created to display captions or subtitles. * @param {function(shaka.Player)=} opt_dependencyInjector Optional callback * which is called to inject mocks into the Player. Used for testing. * @constructor * @struct * @implements {shaka.util.IDestroyable} * @extends {shaka.util.FakeEventTarget} */ shaka.Player = function(video, opt_dependencyInjector) {}; /** * After destruction, a Player object cannot be used again. * @override */ shaka.Player.prototype.destroy = function() {}; /** * @const {string} */ shaka.Player.version; /** * Registers a plugin callback that will be called with support(). The * callback will return the value that will be stored in the return value from * support(). * @param {string} name * @param {function():*} callback */ shaka.Player.registerSupportPlugin = function(name, callback) {}; /** * Return whether the browser provides basic support. If this returns false, * Shaka Player cannot be used at all. In this case, do not construct a Player * instance and do not use the library. * @return {boolean} */ shaka.Player.isBrowserSupported = function() {}; /** * Probes the browser to determine what features are supported. This makes a * number of requests to EME/MSE/etc which may result in user prompts. This * should only be used for diagnostics. * NOTE: This may show a request to the user for permission. * @see https://goo.gl/ovYLvl * @return {!Promise.<shakaExtern.SupportType>} */ shaka.Player.probeSupport = function() {}; /** * Load a manifest. * @param {string} manifestUri * @param {number=} opt_startTime Optional start time, in seconds, to begin * playback. Defaults to 0 for VOD and to the live edge for live. * @param {shakaExtern.ManifestParser.Factory=} opt_manifestParserFactory * Optional manifest parser factory to override auto-detection or use an * unregistered parser. * @return {!Promise} Resolved when the manifest has been loaded and playback * has begun; rejected when an error occurs or the call was interrupted by * destroy(), unload() or another call to load(). */ shaka.Player.prototype.load = function(manifestUri, opt_startTime, opt_manifestParserFactory) {}; /** * Configure the Player instance. * The config object passed in need not be complete. It will be merged with * the existing Player configuration. * Config keys and types will be checked. If any problems with the config * object are found, errors will be reported through logs. * @param {!Object} config This should follow the form of * {@link shakaExtern.PlayerConfiguration}, but you may omit any field you do * not wish to change. */ shaka.Player.prototype.configure = function(config) {}; /** * Return a copy of the current configuration. Modifications of the returned * value will not affect the Player's active configuration. You must call * player.configure() to make changes. * @return {shakaExtern.PlayerConfiguration} */ shaka.Player.prototype.getConfiguration = function() {}; /** * Reset configuration to default. */ shaka.Player.prototype.resetConfiguration = function() {}; /** * @return {HTMLMediaElement} A reference to the HTML Media Element passed * in during initialization. */ shaka.Player.prototype.getMediaElement = function() {}; /** * @return {shaka.net.NetworkingEngine} A reference to the Player's networking * engine. Applications may use this to make requests through Shaka's * networking plugins. */ shaka.Player.prototype.getNetworkingEngine = function() {}; /** * @return {?string} If a manifest is loaded, returns the manifest URI given in * the last call to load(). Otherwise, returns null. */ shaka.Player.prototype.getManifestUri = function() {}; /** * @return {boolean} True if the current stream is live. False otherwise. */ shaka.Player.prototype.isLive = function() {}; /** * @return {boolean} True if the current stream is in-progress VOD. * False otherwise. */ shaka.Player.prototype.isInProgress = function() {}; /** * Get the seekable range for the current stream. * @return {{start: number, end: number}} */ shaka.Player.prototype.seekRange = function() {}; /** * Get the key system currently being used by EME. This returns the empty * string if not using EME. * @return {string} */ shaka.Player.prototype.keySystem = function() {}; /** * Get the DrmInfo used to initialize EME. This returns null when not using * EME. * @return {?shakaExtern.DrmInfo} */ shaka.Player.prototype.drmInfo = function() {}; /** * The next known expiration time for any EME session. If the sessions never * expire, or there are no EME sessions, this returns Infinity. * @return {number} */ shaka.Player.prototype.getExpiration = function() {}; /** * @return {boolean} True if the Player is in a buffering state. */ shaka.Player.prototype.isBuffering = function() {}; /** * Unload the current manifest and make the Player available for re-use. * @return {!Promise} Resolved when streaming has stopped and the previous * content, if any, has been unloaded. */ shaka.Player.prototype.unload = function() {}; /** * Gets the current effective playback rate. If using trick play, it will * return the current trick play rate; otherwise, it will return the video * playback rate. * @return {number} */ shaka.Player.prototype.getPlaybackRate = function() {}; /** * Skip through the content without playing. Simulated using repeated seeks. * Trick play will be canceled automatically if the playhead hits the beginning * or end of the seekable range for the content. * @param {number} rate The playback rate to simulate. For example, a rate of * 2.5 would result in 2.5 seconds of content being skipped every second. * To trick-play backward, use a negative rate. */ shaka.Player.prototype.trickPlay = function(rate) {}; /** * Cancel trick-play. */ shaka.Player.prototype.cancelTrickPlay = function() {}; /** * Return a list of variant and text tracks available for the current Period. * If there are multiple Periods, then you must seek to the Period before * being able to switch. * @return {!Array.<shakaExtern.Track>} * @deprecated Use getVariantTracks() or getTextTracks() */ shaka.Player.prototype.getTracks = function() {}; /** * Select a specific track. For variant tracks, this disables adaptation. * Note that AdaptationEvents are not fired for manual track selections. * @param {shakaExtern.Track} track * @param {boolean=} opt_clearBuffer * @deprecated Use selectVariantTrack() or selectTextTrack() */ shaka.Player.prototype.selectTrack = function(track, opt_clearBuffer) {}; /** * Return a list of variant tracks available for the current * Period. If there are multiple Periods, then you must seek to the Period * before being able to switch. * @return {!Array.<shakaExtern.Track>} */ shaka.Player.prototype.getVariantTracks = function() {}; /** * Return a list of text tracks available for the current * Period. If there are multiple Periods, then you must seek to the Period * before being able to switch. * @return {!Array.<shakaExtern.Track>} */ shaka.Player.prototype.getTextTracks = function() {}; /** * Select a specific text track. Note that AdaptationEvents are not * fired for manual track selections. * @param {shakaExtern.Track} track */ shaka.Player.prototype.selectTextTrack = function(track) {}; /** * Select a specific track. Note that AdaptationEvents are not fired for manual * track selections. * @param {shakaExtern.Track} track * @param {boolean=} opt_clearBuffer */ shaka.Player.prototype.selectVariantTrack = function(track, opt_clearBuffer) {}; /** * Return a list of audio languages available for the current * Period. * @return {!Array.<string>} */ shaka.Player.prototype.getAudioLanguages = function() {}; /** * Return a list of text languages available for the current * Period. * @return {!Array.<string>} */ shaka.Player.prototype.getTextLanguages = function() {}; /** * Sets currentAudioLanguage to the selected language and chooses * new variant in that language if need be. * @param {!string} language */ shaka.Player.prototype.selectAudioLanguage = function(language) {}; /** * Sets currentTextLanguage to the selected language and chooses * new text stream in that language if need be. * @param {!string} language */ shaka.Player.prototype.selectTextLanguage = function(language) {}; /** * @return {boolean} True if the current text track is visible. */ shaka.Player.prototype.isTextTrackVisible = function() {}; /** * Set the visibility of the current text track, if any. * @param {boolean} on */ shaka.Player.prototype.setTextTrackVisibility = function(on) {}; /** * Returns current playhead time as a Date. * @return {Date} */ shaka.Player.prototype.getPlayheadTimeAsDate = function() {}; /** * Return playback and adaptation stats. * @return {shakaExtern.Stats} */ shaka.Player.prototype.getStats = function() {}; /** * Adds the given text track to the current Period. Load() must resolve before * calling. The current Period or the presentation must have a duration. This * returns a Promise that will resolve when the track can be switched to and * will resolve with the track that was created. * @param {string} uri * @param {string} language * @param {string} kind * @param {string} mime * @param {string=} opt_codec * @return {!Promise.<shakaExtern.Track>} */ shaka.Player.prototype.addTextTrack = function(uri, language, kind, mime, opt_codec) {}; /** * Set the maximum resolution that the platform's hardware can handle. * This will be called automatically by shaka.cast.CastReceiver to enforce * limitations of the Chromecast hardware. * @param {number} width * @param {number} height */ shaka.Player.prototype.setMaxHardwareResolution = function(width, height) {}; /** * Creates a SegmentIndex. * @param {!Array.<!shaka.media.SegmentReference>} references The list of * SegmentReferences, which must be sorted first by their start times * (ascending) and second by their end times (ascending), and have * continuous, increasing positions. * @constructor * @struct * @implements {shaka.util.IDestroyable} */ shaka.media.SegmentIndex = function(references) {}; /** * @override */ shaka.media.SegmentIndex.prototype.destroy = function() {}; /** * Finds the position of the segment for the given time, in seconds, relative * to the start of a particular Period. Returns the position of the segment * with the largest end time if more than one segment is known for the given * time. * @param {number} time * @return {?number} The position of the segment, or null * if the position of the segment could not be determined. */ shaka.media.SegmentIndex.prototype.find = function(time) {}; /** * Gets the SegmentReference for the segment at the given position. * @param {number} position The position of the segment. * @return {shaka.media.SegmentReference} The SegmentReference, or null if * no such SegmentReference exists. */ shaka.media.SegmentIndex.prototype.get = function(position) {}; /** * Merges the given SegmentReferences. Supports extending the original * references only. Will not replace old references or interleave new ones. * @param {!Array.<!shaka.media.SegmentReference>} references The list of * SegmentReferences, which must be sorted first by their start times * (ascending) and second by their end times (ascending), and have * continuous, increasing positions. */ shaka.media.SegmentIndex.prototype.merge = function(references) {}; /** * Removes all SegmentReferences that end before the given time. * @param {number} time The time in seconds. */ shaka.media.SegmentIndex.prototype.evict = function(time) {}; /** * @namespace * @summary A networking plugin to handle data URIs. * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs * @param {string} uri * @param {shakaExtern.Request} request * @return {!Promise.<shakaExtern.Response>} */ shaka.net.DataUriPlugin = function(uri, request) {}; /** * Creates a new HLS parser. * @struct * @constructor * @implements {shakaExtern.ManifestParser} */ shaka.hls.HlsParser = function() {}; /** * @override */ shaka.hls.HlsParser.prototype.configure = function(config) {}; /** * @override */ shaka.hls.HlsParser.prototype.start = function(uri, playerInterface) {}; /** * @override */ shaka.hls.HlsParser.prototype.stop = function() {}; /** * @override */ shaka.hls.HlsParser.prototype.update = function() {}; /** * @override */ shaka.hls.HlsParser.prototype.onExpirationUpdated = function(sessionId, expiration) {}; /** * @namespace * @summary A plugin that handles requests for offline content. * @param {string} uri * @param {shakaExtern.Request} request * @return {!Promise.<shakaExtern.Response>} */ shaka.offline.OfflineScheme = function(uri, request) {}; /** * Install all polyfills. */ shaka.polyfill.installAll = function() {}; /** * Registers a new polyfill to be installed. * @param {function()} polyfill */ shaka.polyfill.register = function(polyfill) {}; /** * This manages persistent offline data including storage, listing, and deleting * stored manifests. Playback of offline manifests are done using Player * using the special URI (e.g. 'offline:12'). * First, check support() to see if offline is supported by the platform. * Second, configure() the storage object with callbacks to your application. * Third, call store(), remove(), or list() as needed. * When done, call destroy(). * @param {shaka.Player} player * The player instance to pull configuration data from. * @struct * @constructor * @implements {shaka.util.IDestroyable} */ shaka.offline.Storage = function(player) {}; /** * Gets whether offline storage is supported. Returns true if offline storage * is supported for clear content. Support for offline storage of encrypted * content will not be determined until storage is attempted. * @return {boolean} */ shaka.offline.Storage.support = function() {}; /** * @override */ shaka.offline.Storage.prototype.destroy = function() {}; /** * Sets configuration values for Storage. This is not associated with * Player.configure and will not change Player. * There are two important callbacks configured here: one for download progress, * and one to decide which tracks to store. * The default track selection callback will store the largest SD video track. * Provide your own callback to choose the tracks you want to store. * @param {shakaExtern.OfflineConfiguration} config */ shaka.offline.Storage.prototype.configure = function(config) {}; /** * Stores the given manifest. If the content is encrypted, and encrypted * content cannot be stored on this platform, the Promise will be rejected with * error code 6001, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE. * @param {string} manifestUri The URI of the manifest to store. * @param {!Object} appMetadata An arbitrary object from the application that * will be stored along-side the offline content. Use this for any * application-specific metadata you need associated with the stored content. * For details on the data types that can be stored here, please refer to * https://goo.gl/h62coS * @param {!shakaExtern.ManifestParser.Factory=} opt_manifestParserFactory * @return {!Promise.<shakaExtern.StoredContent>} A Promise to a structure * representing what was stored. The "offlineUri" member is the URI that * should be given to Player.load() to play this piece of content offline. * The "appMetadata" member is the appMetadata argument you passed to store(). */ shaka.offline.Storage.prototype.store = function(manifestUri, appMetadata, opt_manifestParserFactory) {}; /** * Removes the given stored content. * @param {shakaExtern.StoredContent} content * @return {!Promise} */ shaka.offline.Storage.prototype.remove = function(content) {}; /** * Lists all the stored content available. * @return {!Promise.<!Array.<shakaExtern.StoredContent>>} A Promise to an * array of structures representing all stored content. The "offlineUri" * member of the structure is the URI that should be given to Player.load() * to play this piece of content offline. The "appMetadata" member is the * appMetadata argument you passed to store(). */ shaka.offline.Storage.prototype.list = function() {}; /** * A proxy to switch between local and remote playback for Chromecast in a way * that is transparent to the app's controls. * @constructor * @struct * @param {!HTMLMediaElement} video The local video element associated with the * local Player instance. * @param {!shaka.Player} player A local Player instance. * @param {string} receiverAppId The ID of the cast receiver application. * @implements {shaka.util.IDestroyable} * @extends {shaka.util.FakeEventTarget} */ shaka.cast.CastProxy = function(video, player, receiverAppId) {}; /** * Destroys the proxy and the underlying local Player. * @param {boolean=} opt_forceDisconnect If true, force the receiver app to shut * down by disconnecting. Does nothing if not connected. * @override */ shaka.cast.CastProxy.prototype.destroy = function(opt_forceDisconnect) {}; /** * Get a proxy for the video element that delegates to local and remote video * elements as appropriate. * @suppress {invalidCasts} to cast proxy Objects to unrelated types * @return {HTMLMediaElement} */ shaka.cast.CastProxy.prototype.getVideo = function() {}; /** * Get a proxy for the Player that delegates to local and remote Player objects * as appropriate. * @suppress {invalidCasts} to cast proxy Objects to unrelated types * @return {shaka.Player} */ shaka.cast.CastProxy.prototype.getPlayer = function() {}; /** * @return {boolean} True if the cast API is available and there are receivers. */ shaka.cast.CastProxy.prototype.canCast = function() {}; /** * @return {boolean} True if we are currently casting. */ shaka.cast.CastProxy.prototype.isCasting = function() {}; /** * @return {string} The name of the Cast receiver device, if isCasting(). */ shaka.cast.CastProxy.prototype.receiverName = function() {}; /** * @return {!Promise} Resolved when connected to a receiver. Rejected if the * connection fails or is canceled by the user. */ shaka.cast.CastProxy.prototype.cast = function() {}; /** * Set application-specific data. * @param {Object} appData Application-specific data to relay to the receiver. */ shaka.cast.CastProxy.prototype.setAppData = function(appData) {}; /** * Show a dialog where user can choose to disconnect from the cast connection. */ shaka.cast.CastProxy.prototype.suggestDisconnect = function() {}; /** * Force the receiver app to shut down by disconnecting. */ shaka.cast.CastProxy.prototype.forceDisconnect = function() {}; /** * A receiver to communicate between the Chromecast-hosted player and the * sender application. * @constructor * @struct * @param {!HTMLMediaElement} video The local video element associated with the * local Player instance. * @param {!shaka.Player} player A local Player instance. * @param {function(Object)=} opt_appDataCallback A callback to handle * application-specific data passed from the sender. * @param {function(string):string=} opt_contentIdCallback A callback to * retrieve manifest URI from the provided content id. * @implements {shaka.util.IDestroyable} * @extends {shaka.util.FakeEventTarget} */ shaka.cast.CastReceiver = function(video, player, opt_appDataCallback, opt_contentIdCallback) {}; /** * @return {boolean} True if the cast API is available and there are receivers. */ shaka.cast.CastReceiver.prototype.isConnected = function() {}; /** * @return {boolean} True if the receiver is not currently doing loading or * playing anything. */ shaka.cast.CastReceiver.prototype.isIdle = function() {}; /** * Destroys the underlying Player, then terminates the cast receiver app. * @override */ shaka.cast.CastReceiver.prototype.destroy = function() {}; /** * Creates a new DASH parser. * @struct * @constructor * @implements {shakaExtern.ManifestParser} */ shaka.dash.DashParser = function() {}; /** * @override */ shaka.dash.DashParser.prototype.configure = function(config) {}; /** * @override */ shaka.dash.DashParser.prototype.start = function(uri, playerInterface) {}; /** * @override */ shaka.dash.DashParser.prototype.stop = function() {}; /** * @override */ shaka.dash.DashParser.prototype.update = function() {}; /** * @override */ shaka.dash.DashParser.prototype.onExpirationUpdated = function(sessionId, expiration) {}; /** * @namespace * @summary A networking plugin to handle http and https URIs via XHR. * @param {string} uri * @param {shakaExtern.Request} request * @return {!Promise.<shakaExtern.Response>} */ shaka.net.HttpPlugin = function(uri, request) {};
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class DelegatedExportsDependency extends NullDependency { constructor(originModule, exports) { super(); this.originModule = originModule; this.exports = exports; } get type() { return "delegated exports"; } getReference() { return { module: this.originModule, importedNames: true }; } getExports() { return { exports: this.exports }; } } module.exports = DelegatedExportsDependency;
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":34,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":9,"../lib/Shim.IE8":33}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":29,"./Shared":32}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":29,"./Shared":32}],5:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * If the document contains a primary key field (based on the * collections's primary key) then the database will search for * an existing document with a matching id. If a matching * document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with * new data. Any keys that do not currently exist on the document * will be added to the document. * * If the document does not contain an id or the id passed does * not match an existing document, an insert is performed instead. * If no id is present a new primary key id is provided for the * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this, updated || []); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } else { if (callback) { callback.call(this, updated || []); } } } else { if (callback) { callback.call(this, updated || []); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$splicePull': // Check that the target key is not undefined if (doc[i] !== undefined) { // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update[i].$index; if (tempIndex !== undefined) { // Check for in bounds index if (tempIndex < doc[i].length) { this._updateSplicePull(doc[i], tempIndex); updated = true; } } else { throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePull from a key that is not an array! (' + i + ')'); } } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = this.objectId(); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other * variants and handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":8,"./Index2d":12,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":28,"./Path":29,"./ReactorIO":30,"./Shared":32}],7:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":6,"./Shared":32}],8:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var //Overload = require('./Overload'), Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, id, clause) { this._dataSource = dataSource; this._id = id; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'id'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; /** * Drops the condition and removes it from memory. * @returns {Condition} */ Condition.prototype.drop = function () { this.stop(); delete this._dataSource.when[this._id]; return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":32}],9:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":10,"./Metrics.js":16,"./Overload":28,"./Shared":32}],10:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":16,"./Overload":28,"./Shared":32}],11:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":11,"./Path":29,"./Shared":32}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":29,"./Shared":32}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":29,"./Shared":32}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk] !== undefined && val[pk] !== null) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":32}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":27,"./Shared":32}],17:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],18:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Gets / sets the flag that will enable / disable chain reactor sending * from this instance. Chain reactor sending is enabled by default on all * instances. * @param {Boolean} val True or false to enable or disable chain sending. * @returns {*} */ chainEnabled: function (val) { if (val !== undefined) { this._chainDisabled = !val; return this; } return !this._chainDisabled; }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain && !this._chainDisabled); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain && !this._chainDisabled) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],19:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":28,"./Serialiser":31}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, id, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } } return this; }, 'string, *, function': function (event, id, listener) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } }, 'string, *': function (event, id) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } } }), emit: function (event, data) { this._listeners = this._listeners || {}; this._emitting = true; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":28}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$fastIn': if (test instanceof Array) { // Source is a string or number, use indexOf to identify match in array return test.indexOf(source) !== -1; } else { console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":28}],26:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Removes an item from the passed array at the specified index. * @param {Array} arr The array to remove from. * @param {Number} index The index of the item to remove. * @param {Number} count The number of items to remove. * @private */ _updateSplicePull: function (arr, index, count) { if (!count) { count = 1; } arr.splice(index, count); }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":29,"./Shared":32}],28:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":32}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":32}],31:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],32:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.831', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Tags":24,"./Mixin.Triggers":25,"./Mixin.Updating":26,"./Overload":28}],33:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); //Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function (query, update, options, callback) { var finalQuery = { $and: [this.query(), query] }; this._from.update.call(this._from, finalQuery, update, options, callback); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * @see Mixin.Triggers::addTrigger() */ View.prototype.addTrigger = function () { return this._data.addTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeTrigger() */ View.prototype.removeTrigger = function () { return this._data.removeTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::ignoreTriggers() */ View.prototype.ignoreTriggers = function () { return this._data.ignoreTriggers.apply(this._data, arguments); }; /** * @see Mixin.Triggers::addLinkIO() */ View.prototype.addLinkIO = function () { return this._data.addLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeLinkIO() */ View.prototype.removeLinkIO = function () { return this._data.removeLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::willTrigger() */ View.prototype.willTrigger = function () { return this._data.willTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::processTrigger() */ View.prototype.processTrigger = function () { return this._data.processTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::_triggerIndexOf() */ View.prototype._triggerIndexOf = function () { return this._data._triggerIndexOf.apply(this._data, arguments); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this.decouple(this._querySettings.query); }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this.decouple(this._querySettings); } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":28,"./ReactorIO":30,"./Shared":32}]},{},[1]);
var klaw = require('klaw') module.exports = { walk: klaw }
module.exports = checkReturnTypes; module.exports.tags = ['return', 'returns']; module.exports.scopes = ['function']; module.exports.options = { checkReturnTypes: {allowedValues: [true]} }; /** * Checking returns types * * @param {(FunctionDeclaration|FunctionExpression)} node * @param {DocTag} tag * @param {Function} err */ function checkReturnTypes(node, tag, err) { // try to check returns types if (!tag.type || !tag.type.valid) { return; } var returnsArgumentStatements = this._getReturnStatementsForNode(node); returnsArgumentStatements.forEach(function(argument) { if (!tag.type.match(argument)) { err('Wrong returns value', argument); } }); }
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), Grid = _dereq_('../lib/Grid'), NodeApiClient = _dereq_('../lib/NodeApiClient'), BinaryLog = _dereq_('../lib/BinaryLog'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":9,"../lib/Shim.IE8":41}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":34,"./Shared":40}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, ReactorIO, Collection, CollectionInit, Db, DbInit, BinaryLog; Shared = _dereq_('./Shared'); BinaryLog = function () { this.init.apply(this, arguments); }; BinaryLog.prototype.init = function (parent) { var self = this; self._logCounter = 0; self._parent = parent; self.size(1000); }; Shared.addModule('BinaryLog', BinaryLog); Shared.mixin(BinaryLog.prototype, 'Mixin.Common'); Shared.mixin(BinaryLog.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryLog.prototype, 'Mixin.Events'); Collection = Shared.modules.Collection; Db = Shared.modules.Db; ReactorIO = Shared.modules.ReactorIO; CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; Shared.synthesize(BinaryLog.prototype, 'name'); Shared.synthesize(BinaryLog.prototype, 'size'); BinaryLog.prototype.attachIO = function () { var self = this; if (!self._io) { self._log = new Collection(self._parent.name() + '-BinaryLog', {capped: true, size: self.size()}); // Override the log collection's id generator so it is linear self._log.objectId = function (id) { if (!id) { id = ++self._logCounter; } return id; }; self._io = new ReactorIO(self._parent, self, function (chainPacket) { self._log.insert({ type: chainPacket.type, data: chainPacket.data }); // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); } }; BinaryLog.prototype.detachIO = function () { var self = this; if (self._io) { self._log.drop(); self._io.drop(); delete self._log; delete self._io; } }; Collection.prototype.init = function () { CollectionInit.apply(this, arguments); this._binaryLog = new BinaryLog(this); }; Shared.finishModule('BinaryLog'); module.exports = BinaryLog; },{"./Shared":40}],5:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":34,"./Shared":40}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = new Overload('Collection.prototype.setData', { '*': function (data) { return this.$main.call(this, data, {}); }, '*, object': function (data, options) { return this.$main.call(this, data, options); }, '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Index2d":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":7,"./Shared":40}],9:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } } } else { return true; } return false; }; /** * Creates a new document instance or returns an existing * instance if one already exists with the passed name. * @func document * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.document = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof FdbDocument) { if (name.state() !== 'droppped') { return name; } else { name = name.name(); } } if (this._document && this._document[name]) { return this._document[name]; } this._document = this._document || {}; this._document[name] = new FdbDocument(name).db(this); self.emit('create', self._document[name], 'document', name); return this._document[name]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":7,"./Shared":40}],12:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],13:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; delete this._listeners; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { template: [ '<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">', '<input type="search" class="form-control gridFilterSearch" placeholder="Search...">', '<span class="input-group-btn">', '<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>', '</span>', '</li>', '<li role="presentation" class="divider"></li>', '<li role="presentation" data-val="$all">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox" checked>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":32,"./Shared":40}],15:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":5,"./Path":34,"./Shared":40}],17:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":34,"./Shared":40}],18:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":40}],19:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":31,"./Shared":40}],20:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],21:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],22:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":32,"./Serialiser":39}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":32}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],26:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],27:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":32}],29:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],30:[function(_dereq_,module,exports){ "use strict"; // Tell JSHint about EventSource /*global EventSource */ // Import external names locally var Shared = _dereq_('./Shared'), Core, CoreInit, Collection, NodeApiClient, Overload; NodeApiClient = function () { this.init.apply(this, arguments); }; /** * The init method that can be overridden or extended. * @param {Core} core The ForerunnerDB core instance. */ NodeApiClient.prototype.init = function (core) { var self = this; self._core = core; self.rootPath('/fdb'); }; Shared.addModule('NodeApiClient', NodeApiClient); Shared.mixin(NodeApiClient.prototype, 'Mixin.Common'); Shared.mixin(NodeApiClient.prototype, 'Mixin.Events'); Shared.mixin(NodeApiClient.prototype, 'Mixin.ChainReactor'); Core = Shared.modules.Core; CoreInit = Core.prototype.init; Collection = Shared.modules.Collection; Overload = Shared.overload; Shared.synthesize(NodeApiClient.prototype, 'rootPath'); /** * Set the url of the server to use for API. * @name server * @param {String} host The server host name including protocol. E.g. * "https://0.0.0.0". * @param {String} port The server port number e.g. "8080". */ NodeApiClient.prototype.server = function (host, port) { if (host !== undefined) { if (host.substr(host.length - 1, 1) === '/') { // Strip trailing / host = host.substr(0, host.length - 1); } if (port !== undefined) { this._server = host + ":" + port; } else { this._server = host; } this._host = host; this._port = port; return this; } if (port !== undefined) { return { host: this._host, port: this._port, url: this._server }; } else { return this._server; } }; NodeApiClient.prototype.http = function (method, url, data, options, callback) { var self = this, finalUrl, sessionData, bodyData, xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4) { if (xmlHttp.status === 200) { // Tell the callback about success if (xmlHttp.responseText) { callback(false, self.jParse(xmlHttp.responseText)); } else { callback(false, {}); } } else if (xmlHttp.status === 204) { callback(false, {}); } else { // Tell the callback about the error callback(xmlHttp.status, xmlHttp.responseText); // Emit the error code self.emit('httpError', xmlHttp.status, xmlHttp.responseText); } } }; switch (method) { case 'GET': case 'DELETE': case 'HEAD': // Check for global auth if (this._sessionData) { data = data !== undefined ? data : {}; // Add the session data to the key specified data[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (data !== undefined ? '?' + self.jStringify(data) : ''); bodyData = null; break; case 'POST': case 'PUT': case 'PATCH': // Check for global auth if (this._sessionData) { sessionData = {}; // Add the session data to the key specified sessionData[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (sessionData !== undefined ? '?' + self.jStringify(sessionData) : ''); bodyData = (data !== undefined ? self.jStringify(data) : null); break; default: return false; } xmlHttp.open(method, finalUrl, true); xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlHttp.send(bodyData); return this; }; // Define HTTP helper methods NodeApiClient.prototype.head = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('HEAD', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.get = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('GET', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.put = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PUT', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.post = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('POST', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.patch = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PATCH', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.postPatch = function (path, id, data, options, callback) { var self = this; // Determine if the item exists or not this.head(path + '/' + id, undefined, {}, function (err, headData) { if (err) { if (err === 404) { // Item does not exist, run post return self.http('POST', self.server() + self._rootPath + path, data, options, callback); } else { callback(err, data); } } else { // Item already exists, run patch return self.http('PATCH', self.server() + self._rootPath + path + '/' + id, data, options, callback); } }); }; NodeApiClient.prototype.delete = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('DELETE', this.server() + this._rootPath + path, data, options, callback); } }); /** * Gets/ sets a global object that will be sent up with client * requests to the API or REST server. * @param {String} key The key to send the session object up inside. * @param {*} obj The object / value to send up with all requests. If * a request has its own data to send up, this session data will be * mixed in to the request data under the specified key. */ NodeApiClient.prototype.session = function (key, obj) { if (key !== undefined && obj !== undefined) { this._sessionData = { key: key, obj: obj }; return this; } return this._sessionData; }; /** * Initiates a client connection to the API server. * @param collectionInstance * @param path * @param query * @param options * @param callback */ NodeApiClient.prototype.sync = function (collectionInstance, path, query, options, callback) { var self = this, source, finalPath, queryParams, queryString = '', connecting = true; if (this.debug()) { console.log(this.logIdentifier() + ' Connecting to API server ' + this.server() + this._rootPath + path); } finalPath = this.server() + this._rootPath + path + '/_sync'; // Check for global auth if (this._sessionData) { queryParams = queryParams || {}; if (this._sessionData.key) { // Add the session data to the key specified queryParams[this._sessionData.key] = this._sessionData.obj; } else { // Add the session data to the root query object Shared.mixin(queryParams, this._sessionData.obj); } } if (query) { queryParams = queryParams || {}; queryParams.$query = query; } if (options) { queryParams = queryParams || {}; if (options.$initialData === undefined) { options.$initialData = true; } queryParams.$options = options; } if (queryParams) { queryString = this.jStringify(queryParams); finalPath += '?' + queryString; } source = new EventSource(finalPath); collectionInstance.__apiConnection = source; source.addEventListener('open', function (e) { if (!options || (options && options.$initialData)) { // The connection is open, grab the initial data self.get(path, queryParams, function (err, data) { if (!err) { collectionInstance.upsert(data); } }); } }, false); source.addEventListener('error', function (e) { if (source.readyState === 2) { // The connection is dead, remove the connection collectionInstance.unSync(); } if (connecting) { connecting = false; callback(e); } }, false); source.addEventListener('insert', function(e) { var data = self.jParse(e.data); collectionInstance.insert(data.dataSet); }, false); source.addEventListener('update', function(e) { var data = self.jParse(e.data); collectionInstance.update(data.query, data.update); }, false); source.addEventListener('remove', function(e) { var data = self.jParse(e.data); collectionInstance.remove(data.query); }, false); if (callback) { source.addEventListener('connected', function (e) { if (connecting) { connecting = false; callback(false); } }, false); } }; Collection.prototype.sync = new Overload({ /** * Sync with this collection on the server-side. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'function': function (callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, function': function (collectionName, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, function': function (query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, function': function (objectType, objectName, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, function': function (collectionName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, function': function (objectType, objectName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, object, function': function (query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, object, function': function (collectionName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, object, function': function (objectType, objectName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, options, callback); }, '$main': function (path, query, options, callback) { var self = this; if (this._db && this._db._core) { // Kill any existing sync connection this.unSync(); // Create new sync connection this._db._core.api.sync(this, path, query, options, callback); // Hook on drop to call unsync this.on('drop', function () { self.unSync(); }); } else { throw(this.logIdentifier() + ' Cannot sync for an anonymous collection! (Collection must be attached to a database)'); } } }); /** * Disconnects an existing connection to a sync server. * @returns {boolean} True if a connection existed, false * if no connection existed. */ Collection.prototype.unSync = function () { if (this.__apiConnection) { if (this.__apiConnection.readyState !== 2) { this.__apiConnection.close(); } delete this.__apiConnection; return true; } return false; }; Collection.prototype.http = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, callback); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); Collection.prototype.autoHttp = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, 'string, string, function': function (method, collectionName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + collectionName, undefined, undefined, {}, callback); }, 'string, string, string, function': function (method, objType, objName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, undefined, undefined, {}, callback); }, 'string, string, string, object, function': function (method, objType, objName, queryObj, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, undefined, {}, callback); }, 'string, string, string, object, object, function': function (method, objType, objName, queryObj, queryOptions, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, queryOptions, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { var self = this; if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._db._core.api._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, function (err, data) { var i; if (!err && data) { // Check the type of method we used and operate on the collection accordingly switch (method) { // Find insert case 'GET': self.insert(data); break; // Insert case 'POST': if (data.inserted && data.inserted.length) { self.insert(data.inserted); } break; // Update overwrite case 'PUT': case 'PATCH': if (data instanceof Array) { // Update each document for (i = 0; i < data.length; i++) { self.updateById(data[i]._id, {$overwrite: data[i]}); } } else { // Update single document self.updateById(data._id, {$overwrite: data}); } break; // Remove case 'DELETE': self.remove(data); break; default: // Nothing to do with this method break; } } // Send the data back to the callback callback(err, data); }); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); // Override the Core init to instantiate the plugin Core.prototype.init = function () { CoreInit.apply(this, arguments); this.api = new NodeApiClient(this); }; Shared.finishModule('NodeApiClient'); module.exports = NodeApiClient; },{"./Shared":40}],31:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":34,"./Shared":40}],32:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof Overview) { return name; } if (this._overview && this._overview[name]) { return this._overview[name]; } this._overview = this._overview || {}; this._overview[name] = new Overview(name).db(this); self.emit('create', self._overview[name], 'overview', name); return this._overview[name]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":7,"./Document":11,"./Shared":40}],34:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":40}],35:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,"async":43,"localforage":79}],36:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":40,"pako":80}],37:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":40,"crypto-js":52}],38:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":40}],39:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],40:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.713', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],42:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":78}],44:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":46}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],47:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":46}],48:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":46}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":46,"./hmac":51,"./sha1":70}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":45,"./core":46}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":46}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":46}],54:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":46}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":45,"./core":46}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby jhruby.web@gmail.com */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":45,"./core":46}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":45,"./core":46}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":45,"./core":46}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":45,"./core":46}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":45,"./core":46}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":45,"./core":46}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":45,"./core":46}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":45,"./core":46}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":45,"./core":46}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":46,"./hmac":51,"./sha1":70}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":46}],70:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":46}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":46,"./sha256":72}],72:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":46}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":46,"./x64-core":77}],74:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":46,"./x64-core":77}],76:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":46}],78:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(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; clearTimeout(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) { setTimeout(drainQueue, 0); } }; // 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.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; }; },{}],79:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":78}],80:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":81,"./lib/inflate":82,"./lib/utils/common":83,"./lib/zlib/constants":86}],81:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":83,"./utils/strings":84,"./zlib/deflate.js":88,"./zlib/messages":93,"./zlib/zstream":95}],82:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":83,"./utils/strings":84,"./zlib/constants":86,"./zlib/gzheader":89,"./zlib/inflate.js":91,"./zlib/messages":93,"./zlib/zstream":95}],83:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],84:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":83}],85:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],86:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],87:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],88:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":83,"./adler32":85,"./crc32":87,"./messages":93,"./trees":94}],89:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],90:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],91:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":83,"./adler32":85,"./crc32":87,"./inffast":90,"./inftrees":92}],92:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":83}],93:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],94:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":83}],95:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[1]);
'use strict'; var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var sysPath = require('path'); var each = require('async-each'); var anymatch = require('anymatch'); var globparent = require('glob-parent'); var isglob = require('is-glob'); var arrify = require('arrify'); var isAbsolute = require('path-is-absolute'); var NodeFsHandler = require('./lib/nodefs-handler'); var FsEventsHandler = require('./lib/fsevents-handler'); // Public: Main class. // Watches files & directories for changes. // // * _opts - object, chokidar options hash // // Emitted events: // `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` // // Examples // // var watcher = new FSWatcher() // .add(directories) // .on('add', function(path) {console.log('File', path, 'was added');}) // .on('change', function(path) {console.log('File', path, 'was changed');}) // .on('unlink', function(path) {console.log('File', path, 'was removed');}) // .on('all', function(event, path) {console.log(path, ' emitted ', event);}) // function FSWatcher(_opts) { var opts = {}; // in case _opts that is passed in is a frozen object if (_opts) for (var opt in _opts) opts[opt] = _opts[opt]; this._watched = Object.create(null); this._closers = Object.create(null); this._ignoredPaths = Object.create(null); Object.defineProperty(this, '_globIgnored', { get: function() { return Object.keys(this._ignoredPaths); } }); this.closed = false; this._throttled = Object.create(null); this._symlinkPaths = Object.create(null); function undef(key) { return opts[key] === undefined; } // Set up default options. if (undef('persistent')) opts.persistent = true; if (undef('ignoreInitial')) opts.ignoreInitial = false; if (undef('ignorePermissionErrors')) opts.ignorePermissionErrors = false; if (undef('interval')) opts.interval = 100; if (undef('binaryInterval')) opts.binaryInterval = 300; this.enableBinaryInterval = opts.binaryInterval !== opts.interval; // Enable fsevents on OS X when polling isn't explicitly enabled. if (undef('useFsEvents')) opts.useFsEvents = !opts.usePolling; // If we can't use fsevents, ensure the options reflect it's disabled. if (!FsEventsHandler.canUse()) opts.useFsEvents = false; // Use polling on Mac if not using fsevents. // Other platforms use non-polling fs.watch. if (undef('usePolling') && !opts.useFsEvents) { opts.usePolling = process.platform === 'darwin'; } // Editor atomic write normalization enabled by default with fs.watch if (undef('atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; if (opts.atomic) this._pendingUnlinks = Object.create(null); if (undef('followSymlinks')) opts.followSymlinks = true; this._isntIgnored = function(path, stat) { return !this._isIgnored(path, stat); }.bind(this); var readyCalls = 0; this._emitReady = function() { if (++readyCalls >= this._readyCount) { this._emitReady = Function.prototype; // use process.nextTick to allow time for listener to be bound process.nextTick(this.emit.bind(this, 'ready')); } }.bind(this); this.options = opts; // You’re frozen when your heart’s not open. Object.freeze(opts); } FSWatcher.prototype = Object.create(EventEmitter.prototype); // Common helpers // -------------- // Private method: Normalize and emit events // // * event - string, type of event // * path - string, file or directory path // * val[1..3] - arguments to be passed with event // // Returns the error if defined, otherwise the value of the // FSWatcher instance's `closed` flag FSWatcher.prototype._emit = function(event, path, val1, val2, val3) { if (this.options.cwd) path = sysPath.relative(this.options.cwd, path); var args = [event, path]; if (val3 !== undefined) args.push(val1, val2, val3); else if (val2 !== undefined) args.push(val1, val2); else if (val1 !== undefined) args.push(val1); if (this.options.atomic) { if (event === 'unlink') { this._pendingUnlinks[path] = args; setTimeout(function() { Object.keys(this._pendingUnlinks).forEach(function(path) { this.emit.apply(this, this._pendingUnlinks[path]); this.emit.apply(this, ['all'].concat(this._pendingUnlinks[path])); delete this._pendingUnlinks[path]; }.bind(this)); }.bind(this), 100); return this; } else if (event === 'add' && this._pendingUnlinks[path]) { event = args[0] = 'change'; delete this._pendingUnlinks[path]; } } if (event === 'change') { if (!this._throttle('change', path, 50)) return this; } var emitEvent = function() { this.emit.apply(this, args); if (event !== 'error') this.emit.apply(this, ['all'].concat(args)); }.bind(this); if ( this.options.alwaysStat && val1 === undefined && (event === 'add' || event === 'addDir' || event === 'change') ) { fs.stat(path, function(error, stats) { // Suppress event when fs.stat fails, to avoid sending undefined 'stat' if (error || !stats) return; args.push(stats); emitEvent(); }); } else { emitEvent(); } return this; }; // Private method: Common handler for errors // // * error - object, Error instance // // Returns the error if defined, otherwise the value of the // FSWatcher instance's `closed` flag FSWatcher.prototype._handleError = function(error) { var code = error && error.code; var ipe = this.options.ignorePermissionErrors; if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && (!ipe || (code !== 'EPERM' && code !== 'EACCES')) ) this.emit('error', error); return error || this.closed; }; // Private method: Helper utility for throttling // // * action - string, type of action being throttled // * path - string, path being acted upon // * timeout - int, duration of time to suppress duplicate actions // // Returns throttle tracking object or false if action should be suppressed FSWatcher.prototype._throttle = function(action, path, timeout) { if (!(action in this._throttled)) { this._throttled[action] = Object.create(null); } var throttled = this._throttled[action]; if (path in throttled) return false; function clear() { delete throttled[path]; clearTimeout(timeoutObject); } var timeoutObject = setTimeout(clear, timeout); throttled[path] = {timeoutObject: timeoutObject, clear: clear}; return throttled[path]; }; // Private method: Determines whether user has asked to ignore this path // // * path - string, path to file or directory // * stats - object, result of fs.stat // // Returns boolean FSWatcher.prototype._isIgnored = function(path, stats) { if ( this.options.atomic && /\..*\.(sw[px])$|\~$|\.subl.*\.tmp/.test(path) ) return true; if (!this._userIgnored) { var cwd = this.options.cwd; var ignored = this.options.ignored; if (cwd && ignored) { ignored = arrify(ignored).map(function (path) { if (typeof path !== 'string') return path; return isAbsolute(path) ? path : sysPath.join(cwd, path); }); } this._userIgnored = anymatch(this._globIgnored .concat(ignored) .concat(arrify(ignored) .filter(function(path) { return typeof path === 'string' && !isglob(path); }).map(function(path) { return path + '/**/*'; }) ) ); } return this._userIgnored([path, stats]); }; // Private method: Provides a set of common helpers and properties relating to // symlink and glob handling // // * path - string, file, directory, or glob pattern being watched // * depth - int, at any depth > 0, this isn't a glob // // Returns object containing helpers for this path FSWatcher.prototype._getWatchHelpers = function(path, depth) { path = path.replace(/^\.[\/\\]/, ''); var watchPath = depth ? path : globparent(path); var hasGlob = watchPath !== path; var globFilter = hasGlob ? anymatch(path) : false; var entryPath = function(entry) { return sysPath.join(watchPath, sysPath.relative(watchPath, entry.fullPath)); } var filterPath = function(entry) { return (!hasGlob || globFilter(entryPath(entry))) && this._isntIgnored(entryPath(entry), entry.stat) && (this.options.ignorePermissionErrors || this._hasReadPermissions(entry.stat)); }.bind(this); var getDirParts = function(path) { if (!hasGlob) return false; var parts = sysPath.relative(watchPath, path).split(/[\/\\]/); return parts; } var dirParts = getDirParts(path); if (dirParts && dirParts.length > 1) dirParts.pop(); var filterDir = function(entry) { if (hasGlob) { var entryParts = getDirParts(entry.fullPath); var globstar = false; var unmatchedGlob = !dirParts.every(function(part, i) { if (part === '**') globstar = true; return globstar || !entryParts[i] || anymatch(part, entryParts[i]); }); } return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat); }.bind(this); return { followSymlinks: this.options.followSymlinks, statMethod: this.options.followSymlinks ? 'stat' : 'lstat', path: path, watchPath: watchPath, entryPath: entryPath, hasGlob: hasGlob, globFilter: globFilter, filterPath: filterPath, filterDir: filterDir }; } // Directory helpers // ----------------- // Private method: Provides directory tracking objects // // * directory - string, path of the directory // // Returns the directory's tracking object FSWatcher.prototype._getWatchedDir = function(directory) { var dir = sysPath.resolve(directory); var watcherRemove = this._remove.bind(this); if (!(dir in this._watched)) this._watched[dir] = { _items: Object.create(null), add: function(item) {this._items[item] = true;}, remove: function(item) { delete this._items[item]; if (!this.children().length) { fs.readdir(dir, function(err) { if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir)); }); } }, has: function(item) {return item in this._items;}, children: function() {return Object.keys(this._items);} }; return this._watched[dir]; }; // File helpers // ------------ // Private method: Check for read permissions // Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405 // // * stats - object, result of fs.stat // // Returns boolean FSWatcher.prototype._hasReadPermissions = function(stats) { return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10)); }; // Private method: Handles emitting unlink events for // files and directories, and via recursion, for // files and directories within directories that are unlinked // // * directory - string, directory within which the following item is located // * item - string, base path of item/directory // // Returns nothing FSWatcher.prototype._remove = function(directory, item) { // if what is being deleted is a directory, get that directory's paths // for recursive deleting and cleaning of watched object // if it is not a directory, nestedDirectoryChildren will be empty array var path = sysPath.join(directory, item); var fullPath = sysPath.resolve(path); var isDirectory = this._watched[path] || this._watched[fullPath]; // prevent duplicate handling in case of arriving here nearly simultaneously // via multiple paths (such as _handleFile and _handleDir) if (!this._throttle('remove', path, 100)) return; // if the only watched file is removed, watch for its return var watchedDirs = Object.keys(this._watched); if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) { this.add(directory, item, true); } // This will create a new entry in the watched object in either case // so we got to do the directory check beforehand var nestedDirectoryChildren = this._getWatchedDir(path).children(); // Recursively remove children directories / files. nestedDirectoryChildren.forEach(function(nestedItem) { this._remove(path, nestedItem); }, this); // Check if item was on the watched list and remove it var parent = this._getWatchedDir(directory); var wasTracked = parent.has(item); parent.remove(item); // The Entry will either be a directory that just got removed // or a bogus entry to a file, in either case we have to remove it delete this._watched[path]; delete this._watched[fullPath]; var eventName = isDirectory ? 'unlinkDir' : 'unlink'; if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); }; // Public method: Adds paths to be watched on an existing FSWatcher instance // * paths - string or array of strings, file/directory paths and/or globs // * _origAdd - private boolean, for handling non-existent paths to be watched // * _internal - private boolean, indicates a non-user add // Returns an instance of FSWatcher for chaining. FSWatcher.prototype.add = function(paths, _origAdd, _internal) { var cwd = this.options.cwd; this.closed = false; paths = arrify(paths); if (cwd) paths = paths.map(function(path) { if (isAbsolute(path)) { return path; } else if (path[0] === '!') { return '!' + sysPath.join(cwd, path.substring(1)); } else { return sysPath.join(cwd, path); } }); // set aside negated glob strings paths = paths.filter(function(path) { if (path[0] === '!') this._ignoredPaths[path.substring(1)] = true; else { // if a path is being added that was previously ignored, stop ignoring it delete this._ignoredPaths[path]; delete this._ignoredPaths[path + '/**/*']; // reset the cached userIgnored anymatch fn // to make ignoredPaths changes effective this._userIgnored = null; return true; } }, this); if (this.options.useFsEvents && FsEventsHandler.canUse()) { if (!this._readyCount) this._readyCount = paths.length; if (this.options.persistent) this._readyCount *= 2; paths.forEach(this._addToFsEvents, this); } else { if (!this._readyCount) this._readyCount = 0; this._readyCount += paths.length; each(paths, function(path, next) { this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) { if (res) this._emitReady(); next(err, res); }.bind(this)); }.bind(this), function(error, results) { results.forEach(function(item) { if (!item) return; this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); }, this); }.bind(this)); } return this; }; // Public method: Close watchers or start ignoring events from specified paths. // * paths - string or array of strings, file/directory paths and/or globs // Returns instance of FSWatcher for chaining. FSWatcher.prototype.unwatch = function(paths) { if (this.closed) return this; paths = arrify(paths); paths.forEach(function(path) { if (this._closers[path]) { this._closers[path](); delete this._closers[path]; this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path)); } else { //convert to absolute path path = sysPath.resolve(path); this._ignoredPaths[path] = true; if (path in this._watched) { this._ignoredPaths[path + '/**/*'] = true; } // reset the cached userIgnored anymatch fn // to make ignoredPaths changes effective this._userIgnored = null; } }, this); return this; }; // Public method: Close watchers and remove all listeners from watched paths. // Returns instance of FSWatcher for chaining. FSWatcher.prototype.close = function() { if (this.closed) return this; this.closed = true; Object.keys(this._closers).forEach(function(watchPath) { this._closers[watchPath](); delete this._closers[watchPath]; }, this); this._watched = Object.create(null); this.removeAllListeners(); return this; }; // Attach watch handler prototype methods function importHandler(handler) { Object.keys(handler.prototype).forEach(function(method) { FSWatcher.prototype[method] = handler.prototype[method]; }); } importHandler(NodeFsHandler); if (FsEventsHandler.canUse()) importHandler(FsEventsHandler); // Export FSWatcher class exports.FSWatcher = FSWatcher; // Public function: Instantiates watcher with paths to be tracked. // * paths - string or array of strings, file/directory paths and/or globs // * options - object, chokidar options // Returns an instance of FSWatcher for chaining. exports.watch = function(paths, options) { return new FSWatcher(options).add(paths); };
'use strict'; module.exports = { set: function (v) { this.setProperty('-webkit-column-rule', v); }, get: function () { return this.getPropertyValue('-webkit-column-rule'); }, enumerable: true };
/*! * inferno-component v1.0.0-beta1 * (c) 2016 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.InfernoComponent = factory()); }(this, (function () { 'use strict'; var Lifecycle = function Lifecycle() { this._listeners = []; }; Lifecycle.prototype.addListener = function addListener (callback) { this._listeners.push(callback); }; Lifecycle.prototype.trigger = function trigger () { var this$1 = this; for (var i = 0; i < this._listeners.length; i++) { this$1._listeners[i](); } }; var NO_OP = '$NO_OP'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; function isArray(obj) { return obj instanceof Array; } function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isNull(obj) { return obj === null; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var ChildrenTypes = { NON_KEYED: 1, KEYED: 2, NODE: 3, TEXT: 4, UNKNOWN: 5 }; var NodeTypes = { ELEMENT: 1, OPT_ELEMENT: 2, TEXT: 3, FRAGMENT: 4, OPT_BLUEPRINT: 5, COMPONENT: 6, PLACEHOLDER: 7 }; function createVFragment(children, childrenType) { return { children: children, childrenType: childrenType || ChildrenTypes.UNKNOWN, dom: null, pointer: null, type: NodeTypes.FRAGMENT }; } function createVPlaceholder() { return { dom: null, type: NodeTypes.PLACEHOLDER }; } var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'; var componentCallbackQueue = new Map(); function addToQueue(component, force, callback) { // TODO this function needs to be revised and improved on var queue = componentCallbackQueue.get(component); if (!queue) { queue = []; componentCallbackQueue.set(component, queue); requestAnimationFrame(function () { applyState(component, force, function () { for (var i = 0; i < queue.length; i++) { queue[i](); } }); componentCallbackQueue.delete(component); component._processingSetState = false; }); } if (callback) { queue.push(callback); } } function queueStateChanges(component, newState, callback) { if (isFunction(newState)) { newState = newState(component.state); } for (var stateKey in newState) { component._pendingState[stateKey] = newState[stateKey]; } if (!component._pendingSetState) { component._pendingSetState = true; if (component._processingSetState || callback) { addToQueue(component, false, callback); } else { component._processingSetState = true; applyState(component, false, callback); component._processingSetState = false; } } else { component.state = Object.assign({}, component.state, component._pendingState); component._pendingState = {}; } } function applyState(component, force, callback) { if ((!component._deferSetState || force) && !component._blockRender) { component._pendingSetState = false; var pendingState = component._pendingState; var prevState = component.state; var nextState = Object.assign({}, prevState, pendingState); var props = component.props; var context = component.context; component._pendingState = {}; var nextInput = component._updateComponent(prevState, nextState, props, props, context, force); if (nextInput === NO_OP) { nextInput = component._lastInput; } else if (isArray(nextInput)) { nextInput = createVFragment(nextInput, null); } else if (isNullOrUndef(nextInput)) { nextInput = createVPlaceholder(); } var lastInput = component._lastInput; var parentDom = lastInput.dom.parentNode; var subLifecycle = new Lifecycle(); var childContext = component.getChildContext(); if (!isNullOrUndef(childContext)) { childContext = Object.assign({}, context, component._childContext, childContext); } else { childContext = Object.assign({}, context, component._childContext); } component._lastInput = nextInput; component._patch(lastInput, nextInput, parentDom, subLifecycle, childContext, component._isSVG, false); component._vComponent.dom = nextInput.dom; component._componentToDOMNodeMap.set(component, nextInput.dom); component.componentDidUpdate(props, prevState); subLifecycle.trigger(); if (!isNullOrUndef(callback)) { callback(); } } } var Component$1 = function Component$1(props, context) { this.state = {}; this.refs = {}; this._processingSetState = false; this._blockRender = false; this._blockSetState = false; this._deferSetState = false; this._pendingSetState = false; this._pendingState = {}; this._lastInput = null; this._vComponent = null; this._unmounted = true; this._childContext = null; this._patch = null; this._isSVG = false; this._componentToDOMNodeMap = null; /** @type {object} */ this.props = props || {}; /** @type {object} */ this.context = context || {}; if (!this.componentDidMount) { this.componentDidMount = null; } }; Component$1.prototype.render = function render (nextProps, nextContext) { }; Component$1.prototype.forceUpdate = function forceUpdate (callback) { if (this._unmounted) { throw Error(noOp); } applyState(this, true, callback); }; Component$1.prototype.setState = function setState (newState, callback) { if (this._unmounted) { throw Error(noOp); } if (this._blockSetState === false) { queueStateChanges(this, newState, callback); } else { { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.componentWillMount = function componentWillMount () { }; Component$1.prototype.componentWillUnmount = function componentWillUnmount () { }; Component$1.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState, prevContext) { }; Component$1.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps, nextState, context) { return true; }; Component$1.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps, context) { }; Component$1.prototype.componentWillUpdate = function componentWillUpdate (nextProps, nextState, nextContext) { }; Component$1.prototype.getChildContext = function getChildContext () { }; Component$1.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force) { if (this._unmounted === true) { throw new Error('You can\'t update an unmounted component!'); } if (!isNullOrUndef(nextProps) && isNullOrUndef(nextProps.children)) { nextProps.children = prevProps.children; } if (prevProps !== nextProps || prevState !== nextState || force) { if (prevProps !== nextProps) { this._blockRender = true; this.componentWillReceiveProps(nextProps, context); this._blockRender = false; if (this._pendingSetState) { nextState = Object.assign({}, nextState, this._pendingState); this._pendingSetState = false; this._pendingState = {}; } } var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState, context); if (shouldUpdate !== false || force) { this._blockSetState = true; this.componentWillUpdate(nextProps, nextState, context); this._blockSetState = false; this.props = nextProps; this.state = nextState; this.context = context; return this.render(nextProps, context); } } return NO_OP; }; return Component$1; })));
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="none" d="M304 291v67.3l120.5-110.5L304 133.3v61.9l-13.7 2c-33.7 4.8-63.8 14.5-89.5 28.8-23.2 12.9-43.5 30-60.4 50.8-17.4 21.4-31.6 47-42.7 77.1 16-14.1 32.7-25.6 51.2-34.7 38-18.9 83.5-28.2 139.1-28.2h16z"/><path d="M448 248L288 96v85.3C138.7 202.7 85.3 309.3 64 416c53.3-74.7 117.3-108.8 224-108.8v87.5L448 248zm-299.1 71.2c-18.5 9.2-35.2 20.6-51.2 34.7 11.1-30.2 25.3-55.7 42.7-77.1 16.9-20.8 37.2-37.9 60.4-50.8 25.7-14.3 55.8-24 89.5-28.8L304 196v-64l120.5 115.8L304 360v-68l-16-1c-55.6 0-101.1 9.3-139.1 28.2z"/></svg>','ios-share-alt-outline');
/*! * FileInput Romanian Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * @author Ciprian Voicu <pictoru@autoportret.ro> * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['ro'] = { fileSingle: 'fișier', filePlural: 'fișiere', browseLabel: 'Răsfoiește &hellip;', removeLabel: 'Șterge', removeTitle: 'Curăță fișierele selectate', cancelLabel: 'Renunță', cancelTitle: 'Anulează încărcarea curentă', uploadLabel: 'Încarcă', uploadTitle: 'Încarcă fișierele selectate', msgNo: 'Nu', msgNoFilesSelected: '', msgCancelled: 'Anulat', msgZoomModalHeading: 'Previzualizare detaliată', msgSizeTooLarge: 'Fișierul "{name}" (<b>{size} KB</b>) depășește limita maximă de încărcare de <b>{maxSize} KB</b>.', msgFilesTooLess: 'Trebuie să selectezi cel puțin <b>{n}</b> {files} pentru a încărca.', msgFilesTooMany: 'Numărul fișierelor pentru încărcare <b>({n})</b> depășește limita maximă de <b>{m}</b>.', msgFileNotFound: 'Fișierul "{name}" nu a fost găsit!', msgFileSecured: 'Restricții de securitate previn citirea fișierului "{name}".', msgFileNotReadable: 'Fișierul "{name}" nu se poate citi.', msgFilePreviewAborted: 'Fișierului "{name}" nu poate fi previzualizat.', msgFilePreviewError: 'A intervenit o eroare în încercarea de citire a fișierului "{name}".', msgInvalidFileType: 'Tip de fișier incorect pentru "{name}". Sunt suportate doar fișiere de tipurile "{types}".', msgInvalidFileExtension: 'Extensie incorectă pentru "{name}". Sunt suportate doar extensiile "{extensions}".', msgUploadAborted: 'Fișierul Încărcarea a fost întrerupt', msgValidationError: 'Eroare de validare', msgLoading: 'Se încarcă fișierul {index} din {files} &hellip;', msgProgress: 'Se încarcă fișierul {index} din {files} - {name} - {percent}% încărcat.', msgSelected: '{n} {files} încărcate', msgFoldersNotAllowed: 'Se poate doar trăgând fișierele! Se renunță la {n} dosar(e).', msgImageWidthSmall: 'Lățimea de fișier de imagine "{name}" trebuie să fie de cel puțin {size px.', msgImageHeightSmall: 'Înălțimea fișier imagine "{name}" trebuie să fie de cel puțin {size} px.', msgImageWidthLarge: 'Lățimea de fișier de imagine "{name}" nu poate depăși {size} px.', msgImageHeightLarge: 'Înălțimea fișier imagine "{name}" nu poate depăși {size} px.', msgImageResizeError: 'Nu a putut obține dimensiunile imaginii pentru a redimensiona.', msgImageResizeException: 'Eroare la redimensionarea imaginii.<pre>{errors}</pre>', dropZoneTitle: 'Trage fișierele aici &hellip;', dropZoneClickTitle: '<br>(or click to select {files})', fileActionSettings: { removeTitle: 'Scoateți fișier', uploadTitle: 'Incarca fisier', zoomTitle: 'Vezi detalii', dragTitle: 'Move / Rearrange', indicatorNewTitle: 'Nu a încărcat încă', indicatorSuccessTitle: 'încărcat', indicatorErrorTitle: 'Încărcați eroare', indicatorLoadingTitle: 'Se încarcă ...' }, previewZoomButtonTitles: { prev: 'View previous file', next: 'View next file', toggleheader: 'Toggle header', fullscreen: 'Toggle full screen', borderless: 'Toggle borderless mode', close: 'Close detailed preview' } }; })(window.jQuery);
/** * Super simple wysiwyg editor on Bootstrap v0.6.13 * http://summernote.org/ * * summernote.js * Copyright 2013-2015 Alan Hong. and other contributors * summernote may be freely distributed under the MIT license./ * * Date: 2015-07-25T02:27Z */ (function (factory) { /* global define */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals: jQuery factory(window.jQuery); } }(function ($) { if (!Array.prototype.reduce) { /** * Array.prototype.reduce polyfill * * @param {Function} callback * @param {Value} [initialValue] * @return {Value} * * @see http://goo.gl/WNriQD */ Array.prototype.reduce = function (callback) { var t = Object(this), len = t.length >>> 0, k = 0, value; if (arguments.length === 2) { value = arguments[1]; } else { while (k < len && !(k in t)) { k++; } if (k >= len) { throw new TypeError('Reduce of empty array with no initial value'); } value = t[k++]; } for (; k < len; k++) { if (k in t) { value = callback(value, t[k], k, t); } } return value; }; } if ('function' !== typeof Array.prototype.filter) { /** * Array.prototype.filter polyfill * * @param {Function} func * @return {Array} * * @see http://goo.gl/T1KFnq */ Array.prototype.filter = function (func) { var t = Object(this), len = t.length >>> 0; var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (func.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (!Array.prototype.map) { /** * Array.prototype.map polyfill * * @param {Function} callback * @return {Array} * * @see https://goo.gl/SMWaMK */ Array.prototype.map = function (callback, thisArg) { var T, A, k; if (this === null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } A = new Array(len); k = 0; while (k < len) { var kValue, mappedValue; if (k in O) { kValue = O[k]; mappedValue = callback.call(T, kValue, k, O); A[k] = mappedValue; } k++; } return A; }; } var isSupportAmd = typeof define === 'function' && define.amd; /** * returns whether font is installed or not. * * @param {String} fontName * @return {Boolean} */ var isFontInstalled = function (fontName) { var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; var $tester = $('<div>').css({ position: 'absolute', left: '-9999px', top: '-9999px', fontSize: '200px' }).text('mmmmmmmmmwwwwwww').appendTo(document.body); var originalWidth = $tester.css('fontFamily', testFontName).width(); var width = $tester.css('fontFamily', fontName + ',' + testFontName).width(); $tester.remove(); return originalWidth !== width; }; var userAgent = navigator.userAgent; var isMSIE = /MSIE|Trident/i.test(userAgent); var browserVersion; if (isMSIE) { var matches = /MSIE (\d+[.]\d+)/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } matches = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } } /** * @class core.agent * * Object which check platform and agent * * @singleton * @alternateClassName agent */ var agent = { /** @property {Boolean} [isMac=false] true if this agent is Mac */ isMac: navigator.appVersion.indexOf('Mac') > -1, /** @property {Boolean} [isMSIE=false] true if this agent is a Internet Explorer */ isMSIE: isMSIE, /** @property {Boolean} [isFF=false] true if this agent is a Firefox */ isFF: /firefox/i.test(userAgent), isWebkit: /webkit/i.test(userAgent), /** @property {Boolean} [isSafari=false] true if this agent is a Safari */ isSafari: /safari/i.test(userAgent), /** @property {Float} browserVersion current browser version */ browserVersion: browserVersion, /** @property {String} jqueryVersion current jQuery version string */ jqueryVersion: parseFloat($.fn.jquery), isSupportAmd: isSupportAmd, hasCodeMirror: isSupportAmd ? require.specified('CodeMirror') : !!window.CodeMirror, isFontInstalled: isFontInstalled, isW3CRangeSupport: !!document.createRange }; /** * @class core.func * * func utils (for high-order func's arg) * * @singleton * @alternateClassName func */ var func = (function () { var eq = function (itemA) { return function (itemB) { return itemA === itemB; }; }; var eq2 = function (itemA, itemB) { return itemA === itemB; }; var peq2 = function (propName) { return function (itemA, itemB) { return itemA[propName] === itemB[propName]; }; }; var ok = function () { return true; }; var fail = function () { return false; }; var not = function (f) { return function () { return !f.apply(f, arguments); }; }; var and = function (fA, fB) { return function (item) { return fA(item) && fB(item); }; }; var self = function (a) { return a; }; var idCounter = 0; /** * generate a globally-unique id * * @param {String} [prefix] */ var uniqueId = function (prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; /** * returns bnd (bounds) from rect * * - IE Compatability Issue: http://goo.gl/sRLOAo * - Scroll Issue: http://goo.gl/sNjUc * * @param {Rect} rect * @return {Object} bounds * @return {Number} bounds.top * @return {Number} bounds.left * @return {Number} bounds.width * @return {Number} bounds.height */ var rect2bnd = function (rect) { var $document = $(document); return { top: rect.top + $document.scrollTop(), left: rect.left + $document.scrollLeft(), width: rect.right - rect.left, height: rect.bottom - rect.top }; }; /** * returns a copy of the object where the keys have become the values and the values the keys. * @param {Object} obj * @return {Object} */ var invertObject = function (obj) { var inverted = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { inverted[obj[key]] = key; } } return inverted; }; /** * @param {String} namespace * @param {String} [prefix] * @return {String} */ var namespaceToCamel = function (namespace, prefix) { prefix = prefix || ''; return prefix + namespace.split('.').map(function (name) { return name.substring(0, 1).toUpperCase() + name.substring(1); }).join(''); }; return { eq: eq, eq2: eq2, peq2: peq2, ok: ok, fail: fail, self: self, not: not, and: and, uniqueId: uniqueId, rect2bnd: rect2bnd, invertObject: invertObject, namespaceToCamel: namespaceToCamel }; })(); /** * @class core.list * * list utils * * @singleton * @alternateClassName list */ var list = (function () { /** * returns the first item of an array. * * @param {Array} array */ var head = function (array) { return array[0]; }; /** * returns the last item of an array. * * @param {Array} array */ var last = function (array) { return array[array.length - 1]; }; /** * returns everything but the last entry of the array. * * @param {Array} array */ var initial = function (array) { return array.slice(0, array.length - 1); }; /** * returns the rest of the items in an array. * * @param {Array} array */ var tail = function (array) { return array.slice(1); }; /** * returns item of array */ var find = function (array, pred) { for (var idx = 0, len = array.length; idx < len; idx ++) { var item = array[idx]; if (pred(item)) { return item; } } }; /** * returns true if all of the values in the array pass the predicate truth test. */ var all = function (array, pred) { for (var idx = 0, len = array.length; idx < len; idx ++) { if (!pred(array[idx])) { return false; } } return true; }; /** * returns index of item */ var indexOf = function (array, item) { return $.inArray(item, array); }; /** * returns true if the value is present in the list. */ var contains = function (array, item) { return indexOf(array, item) !== -1; }; /** * get sum from a list * * @param {Array} array - array * @param {Function} fn - iterator */ var sum = function (array, fn) { fn = fn || func.self; return array.reduce(function (memo, v) { return memo + fn(v); }, 0); }; /** * returns a copy of the collection with array type. * @param {Collection} collection - collection eg) node.childNodes, ... */ var from = function (collection) { var result = [], idx = -1, length = collection.length; while (++idx < length) { result[idx] = collection[idx]; } return result; }; /** * cluster elements by predicate function. * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule * @param {Array[]} */ var clusterBy = function (array, fn) { if (!array.length) { return []; } var aTail = tail(array); return aTail.reduce(function (memo, v) { var aLast = last(memo); if (fn(last(aLast), v)) { aLast[aLast.length] = v; } else { memo[memo.length] = [v]; } return memo; }, [[head(array)]]); }; /** * returns a copy of the array with all falsy values removed * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule */ var compact = function (array) { var aResult = []; for (var idx = 0, len = array.length; idx < len; idx ++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }; /** * produces a duplicate-free version of the array * * @param {Array} array */ var unique = function (array) { var results = []; for (var idx = 0, len = array.length; idx < len; idx ++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }; /** * returns next item. * @param {Array} array */ var next = function (array, item) { var idx = indexOf(array, item); if (idx === -1) { return null; } return array[idx + 1]; }; /** * returns prev item. * @param {Array} array */ var prev = function (array, item) { var idx = indexOf(array, item); if (idx === -1) { return null; } return array[idx - 1]; }; return { head: head, last: last, initial: initial, tail: tail, prev: prev, next: next, find: find, contains: contains, all: all, sum: sum, from: from, clusterBy: clusterBy, compact: compact, unique: unique }; })(); var NBSP_CHAR = String.fromCharCode(160); var ZERO_WIDTH_NBSP_CHAR = '\ufeff'; /** * @class core.dom * * Dom functions * * @singleton * @alternateClassName dom */ var dom = (function () { /** * @method isEditable * * returns whether node is `note-editable` or not. * * @param {Node} node * @return {Boolean} */ var isEditable = function (node) { return node && $(node).hasClass('note-editable'); }; /** * @method isControlSizing * * returns whether node is `note-control-sizing` or not. * * @param {Node} node * @return {Boolean} */ var isControlSizing = function (node) { return node && $(node).hasClass('note-control-sizing'); }; /** * @method buildLayoutInfo * * build layoutInfo from $editor(.note-editor) * * @param {jQuery} $editor * @return {Object} * @return {Function} return.editor * @return {Node} return.dropzone * @return {Node} return.toolbar * @return {Node} return.editable * @return {Node} return.codable * @return {Node} return.popover * @return {Node} return.handle * @return {Node} return.dialog */ var buildLayoutInfo = function ($editor) { var makeFinder; // air mode if ($editor.hasClass('note-air-editor')) { var id = list.last($editor.attr('id').split('-')); makeFinder = function (sIdPrefix) { return function () { return $(sIdPrefix + id); }; }; return { editor: function () { return $editor; }, holder : function () { return $editor.data('holder'); }, editable: function () { return $editor; }, popover: makeFinder('#note-popover-'), handle: makeFinder('#note-handle-'), dialog: makeFinder('#note-dialog-') }; // frame mode } else { makeFinder = function (className, $base) { $base = $base || $editor; return function () { return $base.find(className); }; }; var options = $editor.data('options'); var $dialogHolder = (options && options.dialogsInBody) ? $(document.body) : null; return { editor: function () { return $editor; }, holder : function () { return $editor.data('holder'); }, dropzone: makeFinder('.note-dropzone'), toolbar: makeFinder('.note-toolbar'), editable: makeFinder('.note-editable'), codable: makeFinder('.note-codable'), statusbar: makeFinder('.note-statusbar'), popover: makeFinder('.note-popover'), handle: makeFinder('.note-handle'), dialog: makeFinder('.note-dialog', $dialogHolder) }; } }; /** * returns makeLayoutInfo from editor's descendant node. * * @private * @param {Node} descendant * @return {Object} */ var makeLayoutInfo = function (descendant) { var $target = $(descendant).closest('.note-editor, .note-air-editor, .note-air-layout'); if (!$target.length) { return null; } var $editor; if ($target.is('.note-editor, .note-air-editor')) { $editor = $target; } else { $editor = $('#note-editor-' + list.last($target.attr('id').split('-'))); } return buildLayoutInfo($editor); }; /** * @method makePredByNodeName * * returns predicate which judge whether nodeName is same * * @param {String} nodeName * @return {Function} */ var makePredByNodeName = function (nodeName) { nodeName = nodeName.toUpperCase(); return function (node) { return node && node.nodeName.toUpperCase() === nodeName; }; }; /** * @method isText * * * * @param {Node} node * @return {Boolean} true if node's type is text(3) */ var isText = function (node) { return node && node.nodeType === 3; }; /** * ex) br, col, embed, hr, img, input, ... * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements */ var isVoid = function (node) { return node && /^BR|^IMG|^HR/.test(node.nodeName.toUpperCase()); }; var isPara = function (node) { if (isEditable(node)) { return false; } // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase()); }; var isLi = makePredByNodeName('LI'); var isPurePara = function (node) { return isPara(node) && !isLi(node); }; var isTable = makePredByNodeName('TABLE'); var isInline = function (node) { return !isBodyContainer(node) && !isList(node) && !isPara(node) && !isTable(node) && !isBlockquote(node); }; var isList = function (node) { return node && /^UL|^OL/.test(node.nodeName.toUpperCase()); }; var isCell = function (node) { return node && /^TD|^TH/.test(node.nodeName.toUpperCase()); }; var isBlockquote = makePredByNodeName('BLOCKQUOTE'); var isBodyContainer = function (node) { return isCell(node) || isBlockquote(node) || isEditable(node); }; var isAnchor = makePredByNodeName('A'); var isParaInline = function (node) { return isInline(node) && !!ancestor(node, isPara); }; var isBodyInline = function (node) { return isInline(node) && !ancestor(node, isPara); }; var isBody = makePredByNodeName('BODY'); /** * returns whether nodeB is closest sibling of nodeA * * @param {Node} nodeA * @param {Node} nodeB * @return {Boolean} */ var isClosestSibling = function (nodeA, nodeB) { return nodeA.nextSibling === nodeB || nodeA.previousSibling === nodeB; }; /** * returns array of closest siblings with node * * @param {Node} node * @param {function} [pred] - predicate function * @return {Node[]} */ var withClosestSiblings = function (node, pred) { pred = pred || func.ok; var siblings = []; if (node.previousSibling && pred(node.previousSibling)) { siblings.push(node.previousSibling); } siblings.push(node); if (node.nextSibling && pred(node.nextSibling)) { siblings.push(node.nextSibling); } return siblings; }; /** * blank HTML for cursor position * - [workaround] old IE only works with &nbsp; * - [workaround] IE11 and other browser works with bogus br */ var blankHTML = agent.isMSIE && agent.browserVersion < 11 ? '&nbsp;' : '<br>'; /** * @method nodeLength * * returns #text's text size or element's childNodes size * * @param {Node} node */ var nodeLength = function (node) { if (isText(node)) { return node.nodeValue.length; } return node.childNodes.length; }; /** * returns whether node is empty or not. * * @param {Node} node * @return {Boolean} */ var isEmpty = function (node) { var len = nodeLength(node); if (len === 0) { return true; } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) { // ex) <p><br></p>, <span><br></span> return true; } else if (list.all(node.childNodes, isText) && node.innerHTML === '') { // ex) <p></p>, <span></span> return true; } return false; }; /** * padding blankHTML if node is empty (for cursor position) */ var paddingBlankHTML = function (node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } }; /** * find nearest ancestor predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ var ancestor = function (node, pred) { while (node) { if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; }; /** * find nearest ancestor only single child blood line and predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ var singleChildAncestor = function (node, pred) { node = node.parentNode; while (node) { if (nodeLength(node) !== 1) { break; } if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; }; /** * returns new array of ancestor nodes (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ var listAncestor = function (node, pred) { pred = pred || func.fail; var ancestors = []; ancestor(node, function (el) { if (!isEditable(el)) { ancestors.push(el); } return pred(el); }); return ancestors; }; /** * find farthest ancestor predicate hit */ var lastAncestor = function (node, pred) { var ancestors = listAncestor(node); return list.last(ancestors.filter(pred)); }; /** * returns common ancestor node between two nodes. * * @param {Node} nodeA * @param {Node} nodeB */ var commonAncestor = function (nodeA, nodeB) { var ancestors = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if ($.inArray(n, ancestors) > -1) { return n; } } return null; // difference document area }; /** * listing all previous siblings (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ var listPrev = function (node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.previousSibling; } return nodes; }; /** * listing next siblings (until predicate hit). * * @param {Node} node * @param {Function} [pred] - predicate function */ var listNext = function (node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.nextSibling; } return nodes; }; /** * listing descendant nodes * * @param {Node} node * @param {Function} [pred] - predicate function */ var listDescendant = function (node, pred) { var descendents = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendents.push(current); } for (var idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendents; }; /** * wrap node with new tag. * * @param {Node} node * @param {Node} tagName of wrapper * @return {Node} - wrapper */ var wrap = function (node, wrapperName) { var parent = node.parentNode; var wrapper = $('<' + wrapperName + '>')[0]; parent.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; }; /** * insert node after preceding * * @param {Node} node * @param {Node} preceding - predicate function */ var insertAfter = function (node, preceding) { var next = preceding.nextSibling, parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; }; /** * append elements. * * @param {Node} node * @param {Collection} aChild */ var appendChildNodes = function (node, aChild) { $.each(aChild, function (idx, child) { node.appendChild(child); }); return node; }; /** * returns whether boundaryPoint is left edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ var isLeftEdgePoint = function (point) { return point.offset === 0; }; /** * returns whether boundaryPoint is right edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ var isRightEdgePoint = function (point) { return point.offset === nodeLength(point.node); }; /** * returns whether boundaryPoint is edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ var isEdgePoint = function (point) { return isLeftEdgePoint(point) || isRightEdgePoint(point); }; /** * returns wheter node is left edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ var isLeftEdgeOf = function (node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }; /** * returns whether node is right edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ var isRightEdgeOf = function (node, ancestor) { while (node && node !== ancestor) { if (position(node) !== nodeLength(node.parentNode) - 1) { return false; } node = node.parentNode; } return true; }; /** * returns whether point is left edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ var isLeftEdgePointOf = function (point, ancestor) { return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor); }; /** * returns whether point is right edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ var isRightEdgePointOf = function (point, ancestor) { return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor); }; /** * returns offset from parent. * * @param {Node} node */ var position = function (node) { var offset = 0; while ((node = node.previousSibling)) { offset += 1; } return offset; }; var hasChildren = function (node) { return !!(node && node.childNodes && node.childNodes.length); }; /** * returns previous boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ var prevPoint = function (point, isSkipInnerOffset) { var node, offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset }; }; /** * returns next boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ var nextPoint = function (point, isSkipInnerOffset) { var node, offset; if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node) + 1; } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; } return { node: node, offset: offset }; }; /** * returns whether pointA and pointB is same or not. * * @param {BoundaryPoint} pointA * @param {BoundaryPoint} pointB * @return {Boolean} */ var isSamePoint = function (pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; }; /** * returns whether point is visible (can set cursor) or not. * * @param {BoundaryPoint} point * @return {Boolean} */ var isVisiblePoint = function (point) { if (isText(point.node) || !hasChildren(point.node) || isEmpty(point.node)) { return true; } var leftNode = point.node.childNodes[point.offset - 1]; var rightNode = point.node.childNodes[point.offset]; if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode))) { return true; } return false; }; /** * @method prevPointUtil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ var prevPointUntil = function (point, pred) { while (point) { if (pred(point)) { return point; } point = prevPoint(point); } return null; }; /** * @method nextPointUntil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ var nextPointUntil = function (point, pred) { while (point) { if (pred(point)) { return point; } point = nextPoint(point); } return null; }; /** * returns whether point has character or not. * * @param {Point} point * @return {Boolean} */ var isCharPoint = function (point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch && (ch !== ' ' && ch !== NBSP_CHAR); }; /** * @method walkPoint * * @param {BoundaryPoint} startPoint * @param {BoundaryPoint} endPoint * @param {Function} handler * @param {Boolean} isSkipInnerOffset */ var walkPoint = function (startPoint, endPoint, handler, isSkipInnerOffset) { var point = startPoint; while (point) { handler(point); if (isSamePoint(point, endPoint)) { break; } var isSkipOffset = isSkipInnerOffset && startPoint.node !== point.node && endPoint.node !== point.node; point = nextPoint(point, isSkipOffset); } }; /** * @method makeOffsetPath * * return offsetPath(array of offset) from ancestor * * @param {Node} ancestor - ancestor node * @param {Node} node */ var makeOffsetPath = function (ancestor, node) { var ancestors = listAncestor(node, func.eq(ancestor)); return ancestors.map(position).reverse(); }; /** * @method fromOffsetPath * * return element from offsetPath(array of offset) * * @param {Node} ancestor - ancestor node * @param {array} offsets - offsetPath */ var fromOffsetPath = function (ancestor, offsets) { var current = ancestor; for (var i = 0, len = offsets.length; i < len; i++) { if (current.childNodes.length <= offsets[i]) { current = current.childNodes[current.childNodes.length - 1]; } else { current = current.childNodes[offsets[i]]; } } return current; }; /** * @method splitNode * * split element or #text * * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ var splitNode = function (point, options) { var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML; var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint; // edge case if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) { if (isLeftEdgePoint(point)) { return point.node; } else if (isRightEdgePoint(point)) { return point.node.nextSibling; } } // split #text if (isText(point.node)) { return point.node.splitText(point.offset); } else { var childNode = point.node.childNodes[point.offset]; var clone = insertAfter(point.node.cloneNode(false), point.node); appendChildNodes(clone, listNext(childNode)); if (!isSkipPaddingBlankHTML) { paddingBlankHTML(point.node); paddingBlankHTML(clone); } return clone; } }; /** * @method splitTree * * split tree by point * * @param {Node} root - split root * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ var splitTree = function (root, point, options) { // ex) [#text, <span>, <p>] var ancestors = listAncestor(point.node, func.eq(root)); if (!ancestors.length) { return null; } else if (ancestors.length === 1) { return splitNode(point, options); } return ancestors.reduce(function (node, parent) { if (node === point.node) { node = splitNode(point, options); } return splitNode({ node: parent, offset: node ? dom.position(node) : nodeLength(parent) }, options); }); }; /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ var splitPoint = function (point, isInline) { // find splitRoot, container // - inline: splitRoot is a child of paragraph // - block: splitRoot is a child of bodyContainer var pred = isInline ? isPara : isBodyContainer; var ancestors = listAncestor(point.node, pred); var topAncestor = list.last(ancestors) || point.node; var splitRoot, container; if (pred(topAncestor)) { splitRoot = ancestors[ancestors.length - 2]; container = topAncestor; } else { splitRoot = topAncestor; container = splitRoot.parentNode; } // if splitRoot is exists, split with splitTree var pivot = splitRoot && splitTree(splitRoot, point, { isSkipPaddingBlankHTML: isInline, isNotSplitEdgePoint: isInline }); // if container is point.node, find pivot with point.offset if (!pivot && container === point.node) { pivot = point.node.childNodes[point.offset]; } return { rightNode: pivot, container: container }; }; var create = function (nodeName) { return document.createElement(nodeName); }; var createText = function (text) { return document.createTextNode(text); }; /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ var remove = function (node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; var i, len; for (i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (i = 0, len = nodes.length; i < len; i++) { parent.insertBefore(nodes[i], node); } } parent.removeChild(node); }; /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ var removeWhile = function (node, pred) { while (node) { if (isEditable(node) || !pred(node)) { break; } var parent = node.parentNode; remove(node); node = parent; } }; /** * @method replace * * replace node with provided nodeName * * @param {Node} node * @param {String} nodeName * @return {Node} - new node */ var replace = function (node, nodeName) { if (node.nodeName.toUpperCase() === nodeName.toUpperCase()) { return node; } var newNode = create(nodeName); if (node.style.cssText) { newNode.style.cssText = node.style.cssText; } appendChildNodes(newNode, list.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; }; var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ var value = function ($node, stripLinebreaks) { var val = isTextarea($node[0]) ? $node.val() : $node.html(); if (stripLinebreaks) { return val.replace(/[\n\r]/g, ''); } return val; }; /** * @method html * * get the HTML contents of node * * @param {jQuery} $node * @param {Boolean} [isNewlineOnBlock] */ var html = function ($node, isNewlineOnBlock) { var markup = value($node); if (isNewlineOnBlock) { var regexTag = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g; markup = markup.replace(regexTag, function (match, endSlash, name) { name = name.toUpperCase(); var isEndOfInlineContainer = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(name) && !!endSlash; var isBlockNode = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(name); return match + ((isEndOfInlineContainer || isBlockNode) ? '\n' : ''); }); markup = $.trim(markup); } return markup; }; return { /** @property {String} NBSP_CHAR */ NBSP_CHAR: NBSP_CHAR, /** @property {String} ZERO_WIDTH_NBSP_CHAR */ ZERO_WIDTH_NBSP_CHAR: ZERO_WIDTH_NBSP_CHAR, /** @property {String} blank */ blank: blankHTML, /** @property {String} emptyPara */ emptyPara: '<p>' + blankHTML + '</p>', makePredByNodeName: makePredByNodeName, isEditable: isEditable, isControlSizing: isControlSizing, buildLayoutInfo: buildLayoutInfo, makeLayoutInfo: makeLayoutInfo, isText: isText, isVoid: isVoid, isPara: isPara, isPurePara: isPurePara, isInline: isInline, isBlock: func.not(isInline), isBodyInline: isBodyInline, isBody: isBody, isParaInline: isParaInline, isList: isList, isTable: isTable, isCell: isCell, isBlockquote: isBlockquote, isBodyContainer: isBodyContainer, isAnchor: isAnchor, isDiv: makePredByNodeName('DIV'), isLi: isLi, isBR: makePredByNodeName('BR'), isSpan: makePredByNodeName('SPAN'), isB: makePredByNodeName('B'), isU: makePredByNodeName('U'), isS: makePredByNodeName('S'), isI: makePredByNodeName('I'), isImg: makePredByNodeName('IMG'), isTextarea: isTextarea, isEmpty: isEmpty, isEmptyAnchor: func.and(isAnchor, isEmpty), isClosestSibling: isClosestSibling, withClosestSiblings: withClosestSiblings, nodeLength: nodeLength, isLeftEdgePoint: isLeftEdgePoint, isRightEdgePoint: isRightEdgePoint, isEdgePoint: isEdgePoint, isLeftEdgeOf: isLeftEdgeOf, isRightEdgeOf: isRightEdgeOf, isLeftEdgePointOf: isLeftEdgePointOf, isRightEdgePointOf: isRightEdgePointOf, prevPoint: prevPoint, nextPoint: nextPoint, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, walkPoint: walkPoint, ancestor: ancestor, singleChildAncestor: singleChildAncestor, listAncestor: listAncestor, lastAncestor: lastAncestor, listNext: listNext, listPrev: listPrev, listDescendant: listDescendant, commonAncestor: commonAncestor, wrap: wrap, insertAfter: insertAfter, appendChildNodes: appendChildNodes, position: position, hasChildren: hasChildren, makeOffsetPath: makeOffsetPath, fromOffsetPath: fromOffsetPath, splitTree: splitTree, splitPoint: splitPoint, create: create, createText: createText, remove: remove, removeWhile: removeWhile, replace: replace, html: html, value: value }; })(); var range = (function () { /** * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js * * @param {TextRange} textRange * @param {Boolean} isStart * @return {BoundaryPoint} * * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx */ var textRangeToPoint = function (textRange, isStart) { var container = textRange.parentElement(), offset; var tester = document.body.createTextRange(), prevContainer; var childNodes = list.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { var textRangeStart = document.body.createTextRange(), curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } /* jshint ignore:start */ var dummy = curTextNode.nodeValue; // enforce IE to re-reference curTextNode, hack /* jshint ignore:end */ if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset }; }; /** * return TextRange from boundary point (inspired by google closure-library) * @param {BoundaryPoint} point * @return {TextRange} */ var pointToTextRange = function (point) { var textRangeInfo = function (container, offset) { var node, isCollapseToStart; if (dom.isText(container)) { var prevTextNodes = dom.listPrev(container, func.not(dom.isText)); var prevContainer = list.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += list.sum(list.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset }; }; var textRange = document.body.createTextRange(); var info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; }; /** * Wrapped Range * * @constructor * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset */ var WrappedRange = function (sc, so, ec, eo) { this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // nativeRange: get nativeRange from sc, so, ec, eo var nativeRange = function () { if (agent.isW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(sc, so); w3cRange.setEnd(ec, eo); return w3cRange; } else { var textRange = pointToTextRange({ node: sc, offset: so }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: ec, offset: eo })); return textRange; } }; this.getPoints = function () { return { sc: sc, so: so, ec: ec, eo: eo }; }; this.getStartPoint = function () { return { node: sc, offset: so }; }; this.getEndPoint = function () { return { node: ec, offset: eo }; }; /** * select update visible range */ this.select = function () { var nativeRng = nativeRange(); if (agent.isW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } return this; }; /** * @return {WrappedRange} */ this.normalize = function () { /** * @param {BoundaryPoint} point * @param {Boolean} isLeftToRight * @return {BoundaryPoint} */ var getVisiblePoint = function (point, isLeftToRight) { if ((dom.isVisiblePoint(point) && !dom.isEdgePoint(point)) || (dom.isVisiblePoint(point) && dom.isRightEdgePoint(point) && !isLeftToRight) || (dom.isVisiblePoint(point) && dom.isLeftEdgePoint(point) && isLeftToRight) || (dom.isVisiblePoint(point) && dom.isBlock(point.node) && dom.isEmpty(point.node))) { return point; } // point on block's edge var block = dom.ancestor(point.node, dom.isBlock); if ((dom.isLeftEdgePointOf(point, block) && !isLeftToRight) || (dom.isRightEdgePointOf(point, block) && isLeftToRight)) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }; var endPoint = getVisiblePoint(this.getEndPoint(), false); var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true); return new WrappedRange( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); }; /** * returns matched nodes on range * * @param {Function} [pred] - predicate function * @param {Object} [options] * @param {Boolean} [options.includeAncestor] * @param {Boolean} [options.fullyContains] * @return {Node[]} */ this.nodes = function (pred, options) { pred = pred || func.ok; var includeAncestor = options && options.includeAncestor; var fullyContains = options && options.fullyContains; // TODO compare points and sort var startPoint = this.getStartPoint(); var endPoint = this.getEndPoint(); var nodes = []; var leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function (point) { if (dom.isEditable(point.node)) { return; } var node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && list.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return list.unique(nodes); }; /** * returns commonAncestor of range * @return {Element} - commonAncestor */ this.commonAncestor = function () { return dom.commonAncestor(sc, ec); }; /** * returns expanded range by pred * * @param {Function} pred - predicate function * @return {WrappedRange} */ this.expand = function (pred) { var startAncestor = dom.ancestor(sc, pred); var endAncestor = dom.ancestor(ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(sc, so, ec, eo); } var boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange( boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo ); }; /** * @param {Boolean} isCollapseToStart * @return {WrappedRange} */ this.collapse = function (isCollapseToStart) { if (isCollapseToStart) { return new WrappedRange(sc, so, sc, so); } else { return new WrappedRange(ec, eo, ec, eo); } }; /** * splitText on range */ this.splitText = function () { var isSameContainer = sc === ec; var boundaryPoints = this.getPoints(); if (dom.isText(ec) && !dom.isEdgePoint(this.getEndPoint())) { ec.splitText(eo); } if (dom.isText(sc) && !dom.isEdgePoint(this.getStartPoint())) { boundaryPoints.sc = sc.splitText(so); boundaryPoints.so = 0; if (isSameContainer) { boundaryPoints.ec = boundaryPoints.sc; boundaryPoints.eo = eo - so; } } return new WrappedRange( boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo ); }; /** * delete contents on range * @return {WrappedRange} */ this.deleteContents = function () { if (this.isCollapsed()) { return this; } var rng = this.splitText(); var nodes = rng.nodes(null, { fullyContains: true }); // find new cursor point var point = dom.prevPointUntil(rng.getStartPoint(), function (point) { return !list.contains(nodes, point.node); }); var emptyParents = []; $.each(nodes, function (idx, node) { // find empty parents var parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents $.each(emptyParents, function (idx, node) { dom.remove(node, false); }); return new WrappedRange( point.node, point.offset, point.node, point.offset ).normalize(); }; /** * makeIsOn: return isOn(pred) function */ var makeIsOn = function (pred) { return function () { var ancestor = dom.ancestor(sc, pred); return !!ancestor && (ancestor === dom.ancestor(ec, pred)); }; }; // isOnEditable: judge whether range is on editable or not this.isOnEditable = makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = makeIsOn(dom.isAnchor); // isOnAnchor: judge whether range is on cell node or not this.isOnCell = makeIsOn(dom.isCell); /** * @param {Function} pred * @return {Boolean} */ this.isLeftEdgeOf = function (pred) { if (!dom.isLeftEdgePoint(this.getStartPoint())) { return false; } var node = dom.ancestor(this.sc, pred); return node && dom.isLeftEdgeOf(this.sc, node); }; /** * returns whether range was collapsed or not */ this.isCollapsed = function () { return sc === ec && so === eo; }; /** * wrap inline nodes which children of body with paragraph * * @return {WrappedRange} */ this.wrapBodyInlineWithPara = function () { if (dom.isBodyContainer(sc) && dom.isEmpty(sc)) { sc.innerHTML = dom.emptyPara; return new WrappedRange(sc.firstChild, 0, sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ var rng = this.normalize(); if (dom.isParaInline(sc) || dom.isPara(sc)) { return rng; } // find inline top ancestor var topAncestor; if (dom.isInline(rng.sc)) { var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = list.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } // siblings not in paragraph var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { var para = dom.wrap(list.head(inlineSiblings), 'p'); dom.appendChildNodes(para, list.tail(inlineSiblings)); } return this.normalize(); }; /** * insert node at current cursor * * @param {Node} node * @return {Node} */ this.insertNode = function (node) { var rng = this.wrapBodyInlineWithPara().deleteContents(); var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); } else { info.container.appendChild(node); } return node; }; /** * insert html at current cursor */ this.pasteHTML = function (markup) { var contentsContainer = $('<div></div>').html(markup)[0]; var childNodes = list.from(contentsContainer.childNodes); var rng = this.wrapBodyInlineWithPara().deleteContents(); return childNodes.reverse().map(function (childNode) { return rng.insertNode(childNode); }).reverse(); }; /** * returns text in range * * @return {String} */ this.toString = function () { var nativeRng = nativeRange(); return agent.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; }; /** * returns range for word before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ this.getWordRange = function (findAfter) { var endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); } return new WrappedRange( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); }; /** * create offsetPath bookmark * * @param {Node} editable */ this.bookmark = function (editable) { return { s: { path: dom.makeOffsetPath(editable, sc), offset: so }, e: { path: dom.makeOffsetPath(editable, ec), offset: eo } }; }; /** * create offsetPath bookmark base on paragraph * * @param {Node[]} paras */ this.paraBookmark = function (paras) { return { s: { path: list.tail(dom.makeOffsetPath(list.head(paras), sc)), offset: so }, e: { path: list.tail(dom.makeOffsetPath(list.last(paras), ec)), offset: eo } }; }; /** * getClientRects * @return {Rect[]} */ this.getClientRects = function () { var nativeRng = nativeRange(); return nativeRng.getClientRects(); }; }; /** * @class core.range * * Data structure * * BoundaryPoint: a point of dom tree * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range * * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position * * @singleton * @alternateClassName range */ return { /** * @method * * create Range Object From arguments or Browser Selection * * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset * @return {WrappedRange} */ create : function (sc, so, ec, eo) { if (!arguments.length) { // from Browser Selection if (agent.isW3CRangeSupport) { var selection = document.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } else if (dom.isBody(selection.anchorNode)) { // Firefox: returns entire body as range on initialization. We won't never need it. return null; } var nativeRng = selection.getRangeAt(0); sc = nativeRng.startContainer; so = nativeRng.startOffset; ec = nativeRng.endContainer; eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var startPoint = textRangeToPoint(textRangeStart, true), endPoint = textRangeToPoint(textRangeEnd, false); // same visible point case: range was collapsed. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) && dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) && endPoint.node.nextSibling === startPoint.node) { startPoint = endPoint; } sc = startPoint.cont; so = startPoint.offset; ec = endPoint.cont; eo = endPoint.offset; } } else if (arguments.length === 2) { //collapsed ec = sc; eo = so; } return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from node * * @param {Node} node * @return {WrappedRange} */ createFromNode: function (node) { var sc = node; var so = 0; var ec = node; var eo = dom.nodeLength(ec); // browsers can't target a picture or void node if (dom.isVoid(sc)) { so = dom.listPrev(sc).length - 1; sc = sc.parentNode; } if (dom.isBR(ec)) { eo = dom.listPrev(ec).length - 1; ec = ec.parentNode; } else if (dom.isVoid(ec)) { eo = dom.listPrev(ec).length; ec = ec.parentNode; } return this.create(sc, so, ec, eo); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeBefore: function (node) { return this.createFromNode(node).collapse(true); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeAfter: function (node) { return this.createFromNode(node).collapse(); }, /** * @method * * create WrappedRange from bookmark * * @param {Node} editable * @param {Object} bookmark * @return {WrappedRange} */ createFromBookmark : function (editable, bookmark) { var sc = dom.fromOffsetPath(editable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(editable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from paraBookmark * * @param {Object} bookmark * @param {Node[]} paras * @return {WrappedRange} */ createFromParaBookmark: function (bookmark, paras) { var so = bookmark.s.offset; var eo = bookmark.e.offset; var sc = dom.fromOffsetPath(list.head(paras), bookmark.s.path); var ec = dom.fromOffsetPath(list.last(paras), bookmark.e.path); return new WrappedRange(sc, so, ec, eo); } }; })(); /** * @class defaults * * @singleton */ var defaults = { /** @property */ version: '0.6.13', /** * * for event options, reference to EventHandler.attach * * @property {Object} options * @property {String/Number} [options.width=null] set editor width * @property {String/Number} [options.height=null] set editor height, ex) 300 * @property {String/Number} options.minHeight set minimum height of editor * @property {String/Number} options.maxHeight * @property {String/Number} options.focus * @property {Number} options.tabsize * @property {Boolean} options.styleWithSpan * @property {Object} options.codemirror * @property {Object} [options.codemirror.mode='text/html'] * @property {Object} [options.codemirror.htmlMode=true] * @property {Object} [options.codemirror.lineNumbers=true] * @property {String} [options.lang=en-US] language 'en-US', 'ko-KR', ... * @property {String} [options.direction=null] text direction, ex) 'rtl' * @property {Array} [options.toolbar] * @property {Boolean} [options.airMode=false] * @property {Array} [options.airPopover] * @property {Fucntion} [options.onInit] initialize * @property {Fucntion} [options.onsubmit] */ options: { width: null, // set editor width height: null, // set editor height, ex) 300 minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor focus: false, // set focus to editable area after initializing summernote tabsize: 4, // size of tab ex) 2 or 4 styleWithSpan: true, // style with span (Chrome and FF only) disableLinkTarget: false, // hide link Target Checkbox disableDragAndDrop: false, // disable drag and drop event disableResizeEditor: false, // disable resizing editor shortcuts: true, // enable keyboard shortcuts placeholder: false, // enable placeholder text prettifyHtml: true, // enable prettifying html while toggling codeview iconPrefix: 'fa fa-', // prefix for css icon classes icons: { font: { bold: 'bold', italic: 'italic', underline: 'underline', clear: 'eraser', height: 'text-height', strikethrough: 'strikethrough', superscript: 'superscript', subscript: 'subscript' }, image: { image: 'picture-o', floatLeft: 'align-left', floatRight: 'align-right', floatNone: 'align-justify', shapeRounded: 'square', shapeCircle: 'circle-o', shapeThumbnail: 'picture-o', shapeNone: 'times', remove: 'trash-o' }, link: { link: 'link', unlink: 'unlink', edit: 'edit' }, table: { table: 'table' }, hr: { insert: 'minus' }, style: { style: 'magic' }, lists: { unordered: 'list-ul', ordered: 'list-ol' }, options: { help: 'question', fullscreen: 'arrows-alt', codeview: 'code' }, paragraph: { paragraph: 'align-left', outdent: 'outdent', indent: 'indent', left: 'align-left', center: 'align-center', right: 'align-right', justify: 'align-justify' }, color: { recent: 'font' }, history: { undo: 'undo', redo: 'repeat' }, misc: { check: 'check' } }, dialogsInBody: false, // false will add dialogs into editor codemirror: { // codemirror options mode: 'text/html', htmlMode: true, lineNumbers: true }, // language lang: 'en-US', // language 'en-US', 'ko-KR', ... direction: null, // text direction, ex) 'rtl' // toolbar toolbar: [ ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'clear']], // ['font', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']], ['fontname', ['fontname']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']] ], plugin : { }, // air mode: inline editor airMode: false, // airPopover: [ // ['style', ['style']], // ['font', ['bold', 'italic', 'underline', 'clear']], // ['fontname', ['fontname']], // ['color', ['color']], // ['para', ['ul', 'ol', 'paragraph']], // ['height', ['height']], // ['table', ['table']], // ['insert', ['link', 'picture']], // ['help', ['help']] // ], airPopover: [ ['color', ['color']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture']] ], // style tag styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], // default fontName defaultFontName: 'Helvetica Neue', // fontName fontNames: [ 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana' ], fontNamesIgnoreCheck: [], fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'], // pallete colors(n x n) colors: [ ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031'] ], // lineHeight lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'], // insertTable max size insertTableMaxSize: { col: 10, row: 10 }, // image maximumImageFileSize: null, // size in bytes, null = no limit // callbacks oninit: null, // initialize onfocus: null, // editable has focus onblur: null, // editable out of focus onenter: null, // enter key pressed onkeyup: null, // keyup onkeydown: null, // keydown onImageUpload: null, // imageUpload onImageUploadError: null, // imageUploadError onMediaDelete: null, // media delete onToolbarClick: null, onsubmit: null, /** * manipulate link address when user create link * @param {String} sLinkUrl * @return {String} */ onCreateLink: function (sLinkUrl) { if (sLinkUrl.indexOf('@') !== -1 && sLinkUrl.indexOf(':') === -1) { sLinkUrl = 'mailto:' + sLinkUrl; } return sLinkUrl; }, keyMap: { pc: { 'ENTER': 'insertParagraph', 'CTRL+Z': 'undo', 'CTRL+Y': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CTRL+B': 'bold', 'CTRL+I': 'italic', 'CTRL+U': 'underline', 'CTRL+SHIFT+S': 'strikethrough', 'CTRL+BACKSLASH': 'removeFormat', 'CTRL+SHIFT+L': 'justifyLeft', 'CTRL+SHIFT+E': 'justifyCenter', 'CTRL+SHIFT+R': 'justifyRight', 'CTRL+SHIFT+J': 'justifyFull', 'CTRL+SHIFT+NUM7': 'insertUnorderedList', 'CTRL+SHIFT+NUM8': 'insertOrderedList', 'CTRL+LEFTBRACKET': 'outdent', 'CTRL+RIGHTBRACKET': 'indent', 'CTRL+NUM0': 'formatPara', 'CTRL+NUM1': 'formatH1', 'CTRL+NUM2': 'formatH2', 'CTRL+NUM3': 'formatH3', 'CTRL+NUM4': 'formatH4', 'CTRL+NUM5': 'formatH5', 'CTRL+NUM6': 'formatH6', 'CTRL+ENTER': 'insertHorizontalRule', 'CTRL+K': 'showLinkDialog' }, mac: { 'ENTER': 'insertParagraph', 'CMD+Z': 'undo', 'CMD+SHIFT+Z': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CMD+B': 'bold', 'CMD+I': 'italic', 'CMD+U': 'underline', 'CMD+SHIFT+S': 'strikethrough', 'CMD+BACKSLASH': 'removeFormat', 'CMD+SHIFT+L': 'justifyLeft', 'CMD+SHIFT+E': 'justifyCenter', 'CMD+SHIFT+R': 'justifyRight', 'CMD+SHIFT+J': 'justifyFull', 'CMD+SHIFT+NUM7': 'insertUnorderedList', 'CMD+SHIFT+NUM8': 'insertOrderedList', 'CMD+LEFTBRACKET': 'outdent', 'CMD+RIGHTBRACKET': 'indent', 'CMD+NUM0': 'formatPara', 'CMD+NUM1': 'formatH1', 'CMD+NUM2': 'formatH2', 'CMD+NUM3': 'formatH3', 'CMD+NUM4': 'formatH4', 'CMD+NUM5': 'formatH5', 'CMD+NUM6': 'formatH6', 'CMD+ENTER': 'insertHorizontalRule', 'CMD+K': 'showLinkDialog' } } }, // default language: en-US lang: { 'en-US': { font: { bold: 'Bold', italic: 'Italic', underline: 'Underline', clear: 'Remove Font Style', height: 'Line Height', name: 'Font Family', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript', size: 'Font Size' }, image: { image: 'Picture', insert: 'Insert Image', resizeFull: 'Resize Full', resizeHalf: 'Resize Half', resizeQuarter: 'Resize Quarter', floatLeft: 'Float Left', floatRight: 'Float Right', floatNone: 'Float None', shapeRounded: 'Shape: Rounded', shapeCircle: 'Shape: Circle', shapeThumbnail: 'Shape: Thumbnail', shapeNone: 'Shape: None', dragImageHere: 'Drag image or text here', dropImage: 'Drop image or Text', selectFromFiles: 'Select from files', maximumFileSize: 'Maximum file size', maximumFileSizeError: 'Maximum file size exceeded.', url: 'Image URL', remove: 'Remove Image' }, link: { link: 'Link', insert: 'Insert Link', unlink: 'Unlink', edit: 'Edit', textToDisplay: 'Text to display', url: 'To what URL should this link go?', openInNewWindow: 'Open in new window' }, table: { table: 'Table' }, hr: { insert: 'Insert Horizontal Rule' }, style: { style: 'Style', normal: 'Normal', blockquote: 'Quote', pre: 'Code', h1: 'Header 1', h2: 'Header 2', h3: 'Header 3', h4: 'Header 4', h5: 'Header 5', h6: 'Header 6' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list' }, options: { help: 'Help', fullscreen: 'Full Screen', codeview: 'Code View' }, paragraph: { paragraph: 'Paragraph', outdent: 'Outdent', indent: 'Indent', left: 'Align left', center: 'Align center', right: 'Align right', justify: 'Justify full' }, color: { recent: 'Recent Color', more: 'More Color', background: 'Background Color', foreground: 'Foreground Color', transparent: 'Transparent', setTransparent: 'Set transparent', reset: 'Reset', resetToDefault: 'Reset to default' }, shortcut: { shortcuts: 'Keyboard shortcuts', close: 'Close', textFormatting: 'Text formatting', action: 'Action', paragraphFormatting: 'Paragraph formatting', documentStyle: 'Document Style', extraKeys: 'Extra keys' }, history: { undo: 'Undo', redo: 'Redo' } } } }; /** * @class core.async * * Async functions which returns `Promise` * * @singleton * @alternateClassName async */ var async = (function () { /** * @method readFileAsDataURL * * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: sDataUrl */ var readFileAsDataURL = function (file) { return $.Deferred(function (deferred) { $.extend(new FileReader(), { onload: function (e) { var sDataURL = e.target.result; deferred.resolve(sDataURL); }, onerror: function () { deferred.reject(this); } }).readAsDataURL(file); }).promise(); }; /** * @method createImage * * create `<image>` from url string * * @param {String} sUrl * @param {String} filename * @return {Promise} - then: $image */ var createImage = function (sUrl, filename) { return $.Deferred(function (deferred) { var $img = $('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr({ 'src': sUrl, 'data-filename': filename }); }).promise(); }; return { readFileAsDataURL: readFileAsDataURL, createImage: createImage }; })(); /** * @class core.key * * Object for keycodes. * * @singleton * @alternateClassName key */ var key = (function () { var keyMap = { 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'SPACE': 32, // Number: 0-9 'NUM0': 48, 'NUM1': 49, 'NUM2': 50, 'NUM3': 51, 'NUM4': 52, 'NUM5': 53, 'NUM6': 54, 'NUM7': 55, 'NUM8': 56, // Alphabet: a-z 'B': 66, 'E': 69, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'R': 82, 'S': 83, 'U': 85, 'V': 86, 'Y': 89, 'Z': 90, 'SLASH': 191, 'LEFTBRACKET': 219, 'BACKSLASH': 220, 'RIGHTBRACKET': 221 }; return { /** * @method isEdit * * @param {Number} keyCode * @return {Boolean} */ isEdit: function (keyCode) { return list.contains([8, 9, 13, 32], keyCode); }, /** * @method isMove * * @param {Number} keyCode * @return {Boolean} */ isMove: function (keyCode) { return list.contains([37, 38, 39, 40], keyCode); }, /** * @property {Object} nameFromCode * @property {String} nameFromCode.8 "BACKSPACE" */ nameFromCode: func.invertObject(keyMap), code: keyMap }; })(); /** * @class editing.History * * Editor History * */ var History = function ($editable) { var stack = [], stackOffset = -1; var editable = $editable[0]; var makeSnapshot = function () { var rng = range.create(); var emptyBookmark = {s: {path: [], offset: 0}, e: {path: [], offset: 0}}; return { contents: $editable.html(), bookmark: (rng ? rng.bookmark(editable) : emptyBookmark) }; }; var applySnapshot = function (snapshot) { if (snapshot.contents !== null) { $editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(editable, snapshot.bookmark).select(); } }; /** * undo */ this.undo = function () { if (0 < stackOffset) { stackOffset--; applySnapshot(stack[stackOffset]); } }; /** * redo */ this.redo = function () { if (stack.length - 1 > stackOffset) { stackOffset++; applySnapshot(stack[stackOffset]); } }; /** * recorded undo */ this.recordUndo = function () { stackOffset++; // Wash out stack after stackOffset if (stack.length > stackOffset) { stack = stack.slice(0, stackOffset); } // Create new snapshot and push it to the end stack.push(makeSnapshot()); }; // Create first undo stack this.recordUndo(); }; /** * @class editing.Style * * Style * */ var Style = function () { /** * @method jQueryCSS * * [workaround] for old jQuery * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @private * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @return {Object} */ var jQueryCSS = function ($obj, propertyNames) { if (agent.jqueryVersion < 1.9) { var result = {}; $.each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } return $obj.css.call($obj, propertyNames); }; /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ this.stylePara = function (rng, styleInfo) { $.each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { $(para).css(styleInfo); }); }; /** * insert and returns styleNodes on range. * * @param {WrappedRange} rng * @param {Object} [options] - options for styleNodes * @param {String} [options.nodeName] - default: `SPAN` * @param {Boolean} [options.expandClosestSibling] - default: `false` * @param {Boolean} [options.onlyPartialContains] - default: `false` * @return {Node[]} */ this.styleNodes = function (rng, options) { rng = rng.splitText(); var nodeName = options && options.nodeName || 'SPAN'; var expandClosestSibling = !!(options && options.expandClosestSibling); var onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } var pred = dom.makePredByNodeName(nodeName); var nodes = rng.nodes(dom.isText, { fullyContains: true }).map(function (text) { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { var nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, function (node) { return list.contains(nodesInRange, node); }); } return nodes.map(function (node) { var siblings = dom.withClosestSiblings(node, pred); var head = list.head(siblings); var tails = list.tail(siblings); $.each(tails, function (idx, elem) { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return list.head(siblings); }); } else { return nodes; } }; /** * get current style on cursor * * @param {WrappedRange} rng * @param {Node} target - target element on event * @return {Object} - object contains style properties. */ this.current = function (rng, target) { var $cont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc); var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = jQueryCSS($cont, properties) || {}; styleInfo['font-size'] = parseInt(styleInfo['font-size'], 10); // document.queryCommandState for toggle state styleInfo['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal'; styleInfo['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal'; styleInfo['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal'; styleInfo['font-strikethrough'] = document.queryCommandState('strikeThrough') ? 'strikethrough' : 'normal'; styleInfo['font-superscript'] = document.queryCommandState('superscript') ? 'superscript' : 'normal'; styleInfo['font-subscript'] = document.queryCommandState('subscript') ? 'subscript' : 'normal'; // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = $.inArray(styleInfo['list-style-type'], aOrderedType) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.image = dom.isImg(target) && target; styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; }; }; /** * @class editing.Bullet * * @alternateClassName Bullet */ var Bullet = function () { /** * @method insertOrderedList * * toggle ordered list * * @type command */ this.insertOrderedList = function () { this.toggleList('OL'); }; /** * @method insertUnorderedList * * toggle unordered list * * @type command */ this.insertUnorderedList = function () { this.toggleList('UL'); }; /** * @method indent * * indent * * @type command */ this.indent = function () { var self = this; var rng = range.create().wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = list.clusterBy(paras, func.peq2('parentNode')); $.each(clustereds, function (idx, paras) { var head = list.head(paras); if (dom.isLi(head)) { self.wrapList(paras, head.parentNode.nodeName); } else { $.each(paras, function (idx, para) { $(para).css('marginLeft', function (idx, val) { return (parseInt(val, 10) || 0) + 25; }); }); } }); rng.select(); }; /** * @method outdent * * outdent * * @type command */ this.outdent = function () { var self = this; var rng = range.create().wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = list.clusterBy(paras, func.peq2('parentNode')); $.each(clustereds, function (idx, paras) { var head = list.head(paras); if (dom.isLi(head)) { self.releaseList([paras]); } else { $.each(paras, function (idx, para) { $(para).css('marginLeft', function (idx, val) { val = (parseInt(val, 10) || 0); return val > 25 ? val - 25 : ''; }); }); } }); rng.select(); }; /** * @method toggleList * * toggle list * * @param {String} listName - OL or UL */ this.toggleList = function (listName) { var self = this; var rng = range.create().wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var bookmark = rng.paraBookmark(paras); var clustereds = list.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (list.find(paras, dom.isPurePara)) { var wrappedParas = []; $.each(clustereds, function (idx, paras) { wrappedParas = wrappedParas.concat(self.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { var diffLists = rng.nodes(dom.isList, { includeAncestor: true }).filter(function (listNode) { return !$.nodeName(listNode, listName); }); if (diffLists.length) { $.each(diffLists, function (idx, listNode) { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); }; /** * @method wrapList * * @param {Node[]} paras * @param {String} listName * @return {Node[]} */ this.wrapList = function (paras, listName) { var head = list.head(paras); var last = list.last(paras); var prevList = dom.isList(head.previousSibling) && head.previousSibling; var nextList = dom.isList(last.nextSibling) && last.nextSibling; var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map(function (para) { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras); if (nextList) { dom.appendChildNodes(listNode, list.from(nextList.childNodes)); dom.remove(nextList); } return paras; }; /** * @method releaseList * * @param {Array[]} clustereds * @param {Boolean} isEscapseToBody * @return {Node[]} */ this.releaseList = function (clustereds, isEscapseToBody) { var releasedParas = []; $.each(clustereds, function (idx, paras) { var head = list.head(paras); var last = list.last(paras); var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, { node: last.parentNode, offset: dom.position(last) + 1 }, { isSkipPaddingBlankHTML: true }) : null; var middleList = dom.splitTree(headList, { node: head.parentNode, offset: dom.position(head) }, { isSkipPaddingBlankHTML: true }); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : list.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map(function (para) { return dom.replace(para, 'P'); }); } $.each(list.from(paras).reverse(), function (idx, para) { dom.insertAfter(para, headList); }); // remove empty lists var rootLists = list.compact([headList, middleList, lastList]); $.each(rootLists, function (idx, rootList) { var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); $.each(listNodes.reverse(), function (idx, listNode) { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); releasedParas = releasedParas.concat(paras); }); return releasedParas; }; }; /** * @class editing.Typing * * Typing * */ var Typing = function () { // a Bullet instance to toggle lists off var bullet = new Bullet(); /** * insert tab * * @param {jQuery} $editable * @param {WrappedRange} rng * @param {Number} tabsize */ this.insertTab = function ($editable, rng, tabsize) { var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); }; /** * insert paragraph */ this.insertParagraph = function () { var rng = range.create(); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph var splitRoot = dom.ancestor(rng.sc, dom.isPara); var nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isEmpty(splitRoot) && dom.isLi(splitRoot)) { // disable UL/OL and escape! bullet.toggleList(splitRoot.parentNode.nodeName); return; // if new line has content (not a line break) } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); $.each(emptyAnchors, function (idx, anchor) { dom.remove(anchor); }); } // no paragraph: insert empty paragraph } else { var next = rng.sc.childNodes[rng.so]; nextPara = $(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select(); }; }; /** * @class editing.Table * * Table * */ var Table = function () { /** * handle tab key * * @param {WrappedRange} rng * @param {Boolean} isShift */ this.tab = function (rng, isShift) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var table = dom.ancestor(cell, dom.isTable); var cells = dom.listDescendant(table, dom.isCell); var nextCell = list[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } }; /** * create empty table element * * @param {Number} rowCount * @param {Number} colCount * @return {Node} */ this.createTable = function (colCount, rowCount) { var tds = [], tdHTML; for (var idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); var trs = [], trHTML; for (var idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); return $('<table class="table table-bordered">' + trHTML + '</table>')[0]; }; }; var KEY_BOGUS = 'bogus'; /** * @class editing.Editor * * Editor * */ var Editor = function (handler) { var self = this; var style = new Style(); var table = new Table(); var typing = new Typing(); var bullet = new Bullet(); /** * @method createRange * * create range * * @param {jQuery} $editable * @return {WrappedRange} */ this.createRange = function ($editable) { this.focus($editable); return range.create(); }; /** * @method saveRange * * save current range * * @param {jQuery} $editable * @param {Boolean} [thenCollapse=false] */ this.saveRange = function ($editable, thenCollapse) { this.focus($editable); $editable.data('range', range.create()); if (thenCollapse) { range.create().collapse().select(); } }; /** * @method saveRange * * save current node list to $editable.data('childNodes') * * @param {jQuery} $editable */ this.saveNode = function ($editable) { // copy child node reference var copy = []; for (var key = 0, len = $editable[0].childNodes.length; key < len; key++) { copy.push($editable[0].childNodes[key]); } $editable.data('childNodes', copy); }; /** * @method restoreRange * * restore lately range * * @param {jQuery} $editable */ this.restoreRange = function ($editable) { var rng = $editable.data('range'); if (rng) { rng.select(); this.focus($editable); } }; /** * @method restoreNode * * restore lately node list * * @param {jQuery} $editable */ this.restoreNode = function ($editable) { $editable.html(''); var child = $editable.data('childNodes'); for (var index = 0, len = child.length; index < len; index++) { $editable[0].appendChild(child[index]); } }; /** * @method currentStyle * * current style * * @param {Node} target * @return {Boolean} false if range is no */ this.currentStyle = function (target) { var rng = range.create(); return rng && rng.isOnEditable() ? style.current(rng.normalize(), target) : false; }; var triggerOnBeforeChange = function ($editable) { var $holder = dom.makeLayoutInfo($editable).holder(); handler.bindCustomEvent( $holder, $editable.data('callbacks'), 'before.command' )($editable.html(), $editable); }; var triggerOnChange = function ($editable) { var $holder = dom.makeLayoutInfo($editable).holder(); handler.bindCustomEvent( $holder, $editable.data('callbacks'), 'change' )($editable.html(), $editable); }; /** * @method undo * undo * @param {jQuery} $editable */ this.undo = function ($editable) { triggerOnBeforeChange($editable); $editable.data('NoteHistory').undo(); triggerOnChange($editable); }; /** * @method redo * redo * @param {jQuery} $editable */ this.redo = function ($editable) { triggerOnBeforeChange($editable); $editable.data('NoteHistory').redo(); triggerOnChange($editable); }; /** * @method beforeCommand * before command * @param {jQuery} $editable */ var beforeCommand = this.beforeCommand = function ($editable) { triggerOnBeforeChange($editable); // keep focus on editable before command execution self.focus($editable); }; /** * @method afterCommand * after command * @param {jQuery} $editable * @param {Boolean} isPreventTrigger */ var afterCommand = this.afterCommand = function ($editable, isPreventTrigger) { $editable.data('NoteHistory').recordUndo(); if (!isPreventTrigger) { triggerOnChange($editable); } }; /** * @method bold * @param {jQuery} $editable * @param {Mixed} value */ /** * @method italic * @param {jQuery} $editable * @param {Mixed} value */ /** * @method underline * @param {jQuery} $editable * @param {Mixed} value */ /** * @method strikethrough * @param {jQuery} $editable * @param {Mixed} value */ /** * @method formatBlock * @param {jQuery} $editable * @param {Mixed} value */ /** * @method superscript * @param {jQuery} $editable * @param {Mixed} value */ /** * @method subscript * @param {jQuery} $editable * @param {Mixed} value */ /** * @method justifyLeft * @param {jQuery} $editable * @param {Mixed} value */ /** * @method justifyCenter * @param {jQuery} $editable * @param {Mixed} value */ /** * @method justifyRight * @param {jQuery} $editable * @param {Mixed} value */ /** * @method justifyFull * @param {jQuery} $editable * @param {Mixed} value */ /** * @method formatBlock * @param {jQuery} $editable * @param {Mixed} value */ /** * @method removeFormat * @param {jQuery} $editable * @param {Mixed} value */ /** * @method backColor * @param {jQuery} $editable * @param {Mixed} value */ /** * @method foreColor * @param {jQuery} $editable * @param {Mixed} value */ /** * @method insertHorizontalRule * @param {jQuery} $editable * @param {Mixed} value */ /** * @method fontName * * change font name * * @param {jQuery} $editable * @param {Mixed} value */ /* jshint ignore:start */ // native commands(with execCommand), generate function for execCommand var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'formatBlock', 'removeFormat', 'backColor', 'foreColor', 'insertHorizontalRule', 'fontName']; for (var idx = 0, len = commands.length; idx < len; idx ++) { this[commands[idx]] = (function (sCmd) { return function ($editable, value) { beforeCommand($editable); document.execCommand(sCmd, false, value); afterCommand($editable, true); }; })(commands[idx]); } /* jshint ignore:end */ /** * @method tab * * handle tab key * * @param {jQuery} $editable * @param {Object} options */ this.tab = function ($editable, options) { var rng = this.createRange($editable); if (rng.isCollapsed() && rng.isOnCell()) { table.tab(rng); } else { beforeCommand($editable); typing.insertTab($editable, rng, options.tabsize); afterCommand($editable); } }; /** * @method untab * * handle shift+tab key * */ this.untab = function ($editable) { var rng = this.createRange($editable); if (rng.isCollapsed() && rng.isOnCell()) { table.tab(rng, true); } }; /** * @method insertParagraph * * insert paragraph * * @param {Node} $editable */ this.insertParagraph = function ($editable) { beforeCommand($editable); typing.insertParagraph($editable); afterCommand($editable); }; /** * @method insertOrderedList * * @param {jQuery} $editable */ this.insertOrderedList = function ($editable) { beforeCommand($editable); bullet.insertOrderedList($editable); afterCommand($editable); }; /** * @param {jQuery} $editable */ this.insertUnorderedList = function ($editable) { beforeCommand($editable); bullet.insertUnorderedList($editable); afterCommand($editable); }; /** * @param {jQuery} $editable */ this.indent = function ($editable) { beforeCommand($editable); bullet.indent($editable); afterCommand($editable); }; /** * @param {jQuery} $editable */ this.outdent = function ($editable) { beforeCommand($editable); bullet.outdent($editable); afterCommand($editable); }; /** * insert image * * @param {jQuery} $editable * @param {String} sUrl */ this.insertImage = function ($editable, sUrl, filename) { async.createImage(sUrl, filename).then(function ($image) { beforeCommand($editable); $image.css({ display: '', width: Math.min($editable.width(), $image.width()) }); range.create().insertNode($image[0]); range.createFromNodeAfter($image[0]).select(); afterCommand($editable); }).fail(function () { var $holder = dom.makeLayoutInfo($editable).holder(); handler.bindCustomEvent( $holder, $editable.data('callbacks'), 'image.upload.error' )(); }); }; /** * @method insertNode * insert node * @param {Node} $editable * @param {Node} node */ this.insertNode = function ($editable, node) { beforeCommand($editable); range.create().insertNode(node); range.createFromNodeAfter(node).select(); afterCommand($editable); }; /** * insert text * @param {Node} $editable * @param {String} text */ this.insertText = function ($editable, text) { beforeCommand($editable); var textNode = range.create().insertNode(dom.createText(text)); range.create(textNode, dom.nodeLength(textNode)).select(); afterCommand($editable); }; /** * paste HTML * @param {Node} $editable * @param {String} markup */ this.pasteHTML = function ($editable, markup) { beforeCommand($editable); var contents = range.create().pasteHTML(markup); range.createFromNodeAfter(list.last(contents)).select(); afterCommand($editable); }; /** * formatBlock * * @param {jQuery} $editable * @param {String} tagName */ this.formatBlock = function ($editable, tagName) { beforeCommand($editable); // [workaround] for MSIE, IE need `<` tagName = agent.isMSIE ? '<' + tagName + '>' : tagName; document.execCommand('FormatBlock', false, tagName); afterCommand($editable); }; this.formatPara = function ($editable) { beforeCommand($editable); this.formatBlock($editable, 'P'); afterCommand($editable); }; /* jshint ignore:start */ for (var idx = 1; idx <= 6; idx ++) { this['formatH' + idx] = function (idx) { return function ($editable) { this.formatBlock($editable, 'H' + idx); }; }(idx); }; /* jshint ignore:end */ /** * fontSize * * @param {jQuery} $editable * @param {String} value - px */ this.fontSize = function ($editable, value) { var rng = range.create(); if (rng.isCollapsed()) { var spans = style.styleNodes(rng); var firstSpan = list.head(spans); $(spans).css({ 'font-size': value + 'px' }); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNodeAfter(firstSpan.firstChild).select(); $editable.data(KEY_BOGUS, firstSpan); } } else { beforeCommand($editable); $(style.styleNodes(rng)).css({ 'font-size': value + 'px' }); afterCommand($editable); } }; /** * remove bogus node and character */ this.removeBogus = function ($editable) { var bogusNode = $editable.data(KEY_BOGUS); if (!bogusNode) { return; } var textNode = list.find(list.from(bogusNode.childNodes), dom.isText); var bogusCharIdx = textNode.nodeValue.indexOf(dom.ZERO_WIDTH_NBSP_CHAR); if (bogusCharIdx !== -1) { textNode.deleteData(bogusCharIdx, 1); } if (dom.isEmpty(bogusNode)) { dom.remove(bogusNode); } $editable.removeData(KEY_BOGUS); }; /** * lineHeight * @param {jQuery} $editable * @param {String} value */ this.lineHeight = function ($editable, value) { beforeCommand($editable); style.stylePara(range.create(), { lineHeight: value }); afterCommand($editable); }; /** * unlink * * @type command * * @param {jQuery} $editable */ this.unlink = function ($editable) { var rng = this.createRange($editable); if (rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.createFromNode(anchor); rng.select(); beforeCommand($editable); document.execCommand('unlink'); afterCommand($editable); } }; /** * create link (command) * * @param {jQuery} $editable * @param {Object} linkInfo * @param {Object} options */ this.createLink = function ($editable, linkInfo, options) { var linkUrl = linkInfo.url; var linkText = linkInfo.text; var isNewWindow = linkInfo.newWindow; var rng = linkInfo.range || this.createRange($editable); var isTextChanged = rng.toString() !== linkText; options = options || dom.makeLayoutInfo($editable).editor().data('options'); beforeCommand($editable); if (options.onCreateLink) { linkUrl = options.onCreateLink(linkUrl); } var anchors = []; if (isTextChanged) { // Create a new link when text changed. var anchor = rng.insertNode($('<A>' + linkText + '</A>')[0]); anchors.push(anchor); } else { anchors = style.styleNodes(rng, { nodeName: 'A', expandClosestSibling: true, onlyPartialContains: true }); } $.each(anchors, function (idx, anchor) { $(anchor).attr('href', linkUrl); if (isNewWindow) { $(anchor).attr('target', '_blank'); } else { $(anchor).removeAttr('target'); } }); var startRange = range.createFromNodeBefore(list.head(anchors)); var startPoint = startRange.getStartPoint(); var endRange = range.createFromNodeAfter(list.last(anchors)); var endPoint = endRange.getEndPoint(); range.create( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ).select(); afterCommand($editable); }; /** * returns link info * * @return {Object} * @return {WrappedRange} return.range * @return {String} return.text * @return {Boolean} [return.isNewWindow=true] * @return {String} [return.url=""] */ this.getLinkInfo = function ($editable) { this.focus($editable); var rng = range.create().expand(dom.isAnchor); // Get the first anchor on range(for edit). var $anchor = $(list.head(rng.nodes(dom.isAnchor))); return { range: rng, text: rng.toString(), isNewWindow: $anchor.length ? $anchor.attr('target') === '_blank' : false, url: $anchor.length ? $anchor.attr('href') : '' }; }; /** * setting color * * @param {Node} $editable * @param {Object} sObjColor color code * @param {String} sObjColor.foreColor foreground color * @param {String} sObjColor.backColor background color */ this.color = function ($editable, sObjColor) { var oColor = JSON.parse(sObjColor); var foreColor = oColor.foreColor, backColor = oColor.backColor; beforeCommand($editable); if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } afterCommand($editable); }; /** * insert Table * * @param {Node} $editable * @param {String} sDim dimension of table (ex : "5x5") */ this.insertTable = function ($editable, sDim) { var dimension = sDim.split('x'); beforeCommand($editable); var rng = range.create().deleteContents(); rng.insertNode(table.createTable(dimension[0], dimension[1])); afterCommand($editable); }; /** * float me * * @param {jQuery} $editable * @param {String} value * @param {jQuery} $target */ this.floatMe = function ($editable, value, $target) { beforeCommand($editable); $target.css('float', value); afterCommand($editable); }; /** * change image shape * * @param {jQuery} $editable * @param {String} value css class * @param {Node} $target */ this.imageShape = function ($editable, value, $target) { beforeCommand($editable); $target.removeClass('img-rounded img-circle img-thumbnail'); if (value) { $target.addClass(value); } afterCommand($editable); }; /** * resize overlay element * @param {jQuery} $editable * @param {String} value * @param {jQuery} $target - target element */ this.resize = function ($editable, value, $target) { beforeCommand($editable); $target.css({ width: value * 100 + '%', height: '' }); afterCommand($editable); }; /** * @param {Position} pos * @param {jQuery} $target - target element * @param {Boolean} [bKeepRatio] - keep ratio */ this.resizeTo = function (pos, $target, bKeepRatio) { var imageSize; if (bKeepRatio) { var newRatio = pos.y / pos.x; var ratio = $target.data('ratio'); imageSize = { width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }; } else { imageSize = { width: pos.x, height: pos.y }; } $target.css(imageSize); }; /** * remove media object * * @param {jQuery} $editable * @param {String} value - dummy argument (for keep interface) * @param {jQuery} $target - target element */ this.removeMedia = function ($editable, value, $target) { beforeCommand($editable); $target.detach(); handler.bindCustomEvent( $(), $editable.data('callbacks'), 'media.delete' )($target, $editable); afterCommand($editable); }; /** * set focus * * @param $editable */ this.focus = function ($editable) { $editable.focus(); // [workaround] for firefox bug http://goo.gl/lVfAaI if (agent.isFF && !range.create().isOnEditable()) { range.createFromNode($editable[0]) .normalize() .collapse() .select(); } }; /** * returns whether contents is empty or not. * * @param {jQuery} $editable * @return {Boolean} */ this.isEmpty = function ($editable) { return dom.isEmpty($editable[0]) || dom.emptyPara === $editable.html(); }; }; /** * @class module.Button * * Button */ var Button = function () { /** * update button status * * @param {jQuery} $container * @param {Object} styleInfo */ this.update = function ($container, styleInfo) { /** * handle dropdown's check mark (for fontname, fontsize, lineHeight). * @param {jQuery} $btn * @param {Number} value */ var checkDropdownMenu = function ($btn, value) { $btn.find('.dropdown-menu li a').each(function () { // always compare string to avoid creating another func. var isChecked = ($(this).data('value') + '') === (value + ''); this.className = isChecked ? 'checked' : ''; }); }; /** * update button state(active or not). * * @private * @param {String} selector * @param {Function} pred */ var btnState = function (selector, pred) { var $btn = $container.find(selector); $btn.toggleClass('active', pred()); }; if (styleInfo.image) { var $img = $(styleInfo.image); btnState('button[data-event="imageShape"][data-value="img-rounded"]', function () { return $img.hasClass('img-rounded'); }); btnState('button[data-event="imageShape"][data-value="img-circle"]', function () { return $img.hasClass('img-circle'); }); btnState('button[data-event="imageShape"][data-value="img-thumbnail"]', function () { return $img.hasClass('img-thumbnail'); }); btnState('button[data-event="imageShape"]:not([data-value])', function () { return !$img.is('.img-rounded, .img-circle, .img-thumbnail'); }); var imgFloat = $img.css('float'); btnState('button[data-event="floatMe"][data-value="left"]', function () { return imgFloat === 'left'; }); btnState('button[data-event="floatMe"][data-value="right"]', function () { return imgFloat === 'right'; }); btnState('button[data-event="floatMe"][data-value="none"]', function () { return imgFloat !== 'left' && imgFloat !== 'right'; }); var style = $img.attr('style'); btnState('button[data-event="resize"][data-value="1"]', function () { return !!/(^|\s)(max-)?width\s*:\s*100%/.test(style); }); btnState('button[data-event="resize"][data-value="0.5"]', function () { return !!/(^|\s)(max-)?width\s*:\s*50%/.test(style); }); btnState('button[data-event="resize"][data-value="0.25"]', function () { return !!/(^|\s)(max-)?width\s*:\s*25%/.test(style); }); return; } // fontname var $fontname = $container.find('.note-fontname'); if ($fontname.length) { var selectedFont = styleInfo['font-family']; if (!!selectedFont) { var list = selectedFont.split(','); for (var i = 0, len = list.length; i < len; i++) { selectedFont = list[i].replace(/[\'\"]/g, '').replace(/\s+$/, '').replace(/^\s+/, ''); if (agent.isFontInstalled(selectedFont)) { break; } } $fontname.find('.note-current-fontname').text(selectedFont); checkDropdownMenu($fontname, selectedFont); } } // fontsize var $fontsize = $container.find('.note-fontsize'); $fontsize.find('.note-current-fontsize').text(styleInfo['font-size']); checkDropdownMenu($fontsize, parseFloat(styleInfo['font-size'])); // lineheight var $lineHeight = $container.find('.note-height'); checkDropdownMenu($lineHeight, parseFloat(styleInfo['line-height'])); btnState('button[data-event="bold"]', function () { return styleInfo['font-bold'] === 'bold'; }); btnState('button[data-event="italic"]', function () { return styleInfo['font-italic'] === 'italic'; }); btnState('button[data-event="underline"]', function () { return styleInfo['font-underline'] === 'underline'; }); btnState('button[data-event="strikethrough"]', function () { return styleInfo['font-strikethrough'] === 'strikethrough'; }); btnState('button[data-event="superscript"]', function () { return styleInfo['font-superscript'] === 'superscript'; }); btnState('button[data-event="subscript"]', function () { return styleInfo['font-subscript'] === 'subscript'; }); btnState('button[data-event="justifyLeft"]', function () { return styleInfo['text-align'] === 'left' || styleInfo['text-align'] === 'start'; }); btnState('button[data-event="justifyCenter"]', function () { return styleInfo['text-align'] === 'center'; }); btnState('button[data-event="justifyRight"]', function () { return styleInfo['text-align'] === 'right'; }); btnState('button[data-event="justifyFull"]', function () { return styleInfo['text-align'] === 'justify'; }); btnState('button[data-event="insertUnorderedList"]', function () { return styleInfo['list-style'] === 'unordered'; }); btnState('button[data-event="insertOrderedList"]', function () { return styleInfo['list-style'] === 'ordered'; }); }; /** * update recent color * * @param {Node} button * @param {String} eventName * @param {Mixed} value */ this.updateRecentColor = function (button, eventName, value) { var $color = $(button).closest('.note-color'); var $recentColor = $color.find('.note-recent-color'); var colorInfo = JSON.parse($recentColor.attr('data-value')); colorInfo[eventName] = value; $recentColor.attr('data-value', JSON.stringify(colorInfo)); var sKey = eventName === 'backColor' ? 'background-color' : 'color'; $recentColor.find('i').css(sKey, value); }; }; /** * @class module.Toolbar * * Toolbar */ var Toolbar = function () { var button = new Button(); this.update = function ($toolbar, styleInfo) { button.update($toolbar, styleInfo); }; /** * @param {Node} button * @param {String} eventName * @param {String} value */ this.updateRecentColor = function (buttonNode, eventName, value) { button.updateRecentColor(buttonNode, eventName, value); }; /** * activate buttons exclude codeview * @param {jQuery} $toolbar */ this.activate = function ($toolbar) { $toolbar.find('button') .not('button[data-event="codeview"]') .removeClass('disabled'); }; /** * deactivate buttons exclude codeview * @param {jQuery} $toolbar */ this.deactivate = function ($toolbar) { $toolbar.find('button') .not('button[data-event="codeview"]') .addClass('disabled'); }; /** * @param {jQuery} $container * @param {Boolean} [bFullscreen=false] */ this.updateFullscreen = function ($container, bFullscreen) { var $btn = $container.find('button[data-event="fullscreen"]'); $btn.toggleClass('active', bFullscreen); }; /** * @param {jQuery} $container * @param {Boolean} [isCodeview=false] */ this.updateCodeview = function ($container, isCodeview) { var $btn = $container.find('button[data-event="codeview"]'); $btn.toggleClass('active', isCodeview); if (isCodeview) { this.deactivate($container); } else { this.activate($container); } }; /** * get button in toolbar * * @param {jQuery} $editable * @param {String} name * @return {jQuery} */ this.get = function ($editable, name) { var $toolbar = dom.makeLayoutInfo($editable).toolbar(); return $toolbar.find('[data-name=' + name + ']'); }; /** * set button state * @param {jQuery} $editable * @param {String} name * @param {Boolean} [isActive=true] */ this.setButtonState = function ($editable, name, isActive) { isActive = (isActive === false) ? false : true; var $button = this.get($editable, name); $button.toggleClass('active', isActive); }; }; var EDITABLE_PADDING = 24; var Statusbar = function () { var $document = $(document); this.attach = function (layoutInfo, options) { if (!options.disableResizeEditor) { layoutInfo.statusbar().on('mousedown', hStatusbarMousedown); } }; /** * `mousedown` event handler on statusbar * * @param {MouseEvent} event */ var hStatusbarMousedown = function (event) { event.preventDefault(); event.stopPropagation(); var $editable = dom.makeLayoutInfo(event.target).editable(); var editableTop = $editable.offset().top - $document.scrollTop(); var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); var options = layoutInfo.editor().data('options'); $document.on('mousemove', function (event) { var nHeight = event.clientY - (editableTop + EDITABLE_PADDING); nHeight = (options.minHeight > 0) ? Math.max(nHeight, options.minHeight) : nHeight; nHeight = (options.maxHeight > 0) ? Math.min(nHeight, options.maxHeight) : nHeight; $editable.height(nHeight); }).one('mouseup', function () { $document.off('mousemove'); }); }; }; /** * @class module.Popover * * Popover (http://getbootstrap.com/javascript/#popovers) * */ var Popover = function () { var button = new Button(); /** * returns position from placeholder * * @private * @param {Node} placeholder * @param {Object} options * @param {Boolean} options.isAirMode * @return {Position} */ var posFromPlaceholder = function (placeholder, options) { var isAirMode = options && options.isAirMode; var isLeftTop = options && options.isLeftTop; var $placeholder = $(placeholder); var pos = isAirMode ? $placeholder.offset() : $placeholder.position(); var height = isLeftTop ? 0 : $placeholder.outerHeight(true); // include margin // popover below placeholder. return { left: pos.left, top: pos.top + height }; }; /** * show popover * * @private * @param {jQuery} popover * @param {Position} pos */ var showPopover = function ($popover, pos) { $popover.css({ display: 'block', left: pos.left, top: pos.top }); }; var PX_POPOVER_ARROW_OFFSET_X = 20; /** * update current state * @param {jQuery} $popover - popover container * @param {Object} styleInfo - style object * @param {Boolean} isAirMode */ this.update = function ($popover, styleInfo, isAirMode) { button.update($popover, styleInfo); var $linkPopover = $popover.find('.note-link-popover'); if (styleInfo.anchor) { var $anchor = $linkPopover.find('a'); var href = $(styleInfo.anchor).attr('href'); var target = $(styleInfo.anchor).attr('target'); $anchor.attr('href', href).html(href); if (!target) { $anchor.removeAttr('target'); } else { $anchor.attr('target', '_blank'); } showPopover($linkPopover, posFromPlaceholder(styleInfo.anchor, { isAirMode: isAirMode })); } else { $linkPopover.hide(); } var $imagePopover = $popover.find('.note-image-popover'); if (styleInfo.image) { showPopover($imagePopover, posFromPlaceholder(styleInfo.image, { isAirMode: isAirMode, isLeftTop: true })); } else { $imagePopover.hide(); } var $airPopover = $popover.find('.note-air-popover'); if (isAirMode && !styleInfo.range.isCollapsed()) { var rect = list.last(styleInfo.range.getClientRects()); if (rect) { var bnd = func.rect2bnd(rect); showPopover($airPopover, { left: Math.max(bnd.left + bnd.width / 2 - PX_POPOVER_ARROW_OFFSET_X, 0), top: bnd.top + bnd.height }); } } else { $airPopover.hide(); } }; /** * @param {Node} button * @param {String} eventName * @param {String} value */ this.updateRecentColor = function (button, eventName, value) { button.updateRecentColor(button, eventName, value); }; /** * hide all popovers * @param {jQuery} $popover - popover container */ this.hide = function ($popover) { $popover.children().hide(); }; }; /** * @class module.Handle * * Handle */ var Handle = function (handler) { var $document = $(document); /** * `mousedown` event handler on $handle * - controlSizing: resize image * * @param {MouseEvent} event */ var hHandleMousedown = function (event) { if (dom.isControlSizing(event.target)) { event.preventDefault(); event.stopPropagation(); var layoutInfo = dom.makeLayoutInfo(event.target), $handle = layoutInfo.handle(), $popover = layoutInfo.popover(), $editable = layoutInfo.editable(), $editor = layoutInfo.editor(); var target = $handle.find('.note-control-selection').data('target'), $target = $(target), posStart = $target.offset(), scrollTop = $document.scrollTop(); var isAirMode = $editor.data('options').airMode; $document.on('mousemove', function (event) { handler.invoke('editor.resizeTo', { x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop) }, $target, !event.shiftKey); handler.invoke('handle.update', $handle, {image: target}, isAirMode); handler.invoke('popover.update', $popover, {image: target}, isAirMode); }).one('mouseup', function () { $document.off('mousemove'); handler.invoke('editor.afterCommand', $editable); }); if (!$target.data('ratio')) { // original ratio. $target.data('ratio', $target.height() / $target.width()); } } }; this.attach = function (layoutInfo) { layoutInfo.handle().on('mousedown', hHandleMousedown); }; /** * update handle * @param {jQuery} $handle * @param {Object} styleInfo * @param {Boolean} isAirMode */ this.update = function ($handle, styleInfo, isAirMode) { var $selection = $handle.find('.note-control-selection'); if (styleInfo.image) { var $image = $(styleInfo.image); var pos = isAirMode ? $image.offset() : $image.position(); // include margin var imageSize = { w: $image.outerWidth(true), h: $image.outerHeight(true) }; $selection.css({ display: 'block', left: pos.left, top: pos.top, width: imageSize.w, height: imageSize.h }).data('target', styleInfo.image); // save current image element. var sizingText = imageSize.w + 'x' + imageSize.h; $selection.find('.note-control-selection-info').text(sizingText); } else { $selection.hide(); } }; /** * hide * * @param {jQuery} $handle */ this.hide = function ($handle) { $handle.children().hide(); }; }; var Fullscreen = function (handler) { var $window = $(window); var $scrollbar = $('html, body'); /** * toggle fullscreen * * @param {Object} layoutInfo */ this.toggle = function (layoutInfo) { var $editor = layoutInfo.editor(), $toolbar = layoutInfo.toolbar(), $editable = layoutInfo.editable(), $codable = layoutInfo.codable(); var resize = function (size) { $editable.css('height', size.h); $codable.css('height', size.h); if ($codable.data('cmeditor')) { $codable.data('cmeditor').setsize(null, size.h); } }; $editor.toggleClass('fullscreen'); var isFullscreen = $editor.hasClass('fullscreen'); if (isFullscreen) { $editable.data('orgheight', $editable.css('height')); $window.on('resize', function () { resize({ h: $window.height() - $toolbar.outerHeight() }); }).trigger('resize'); $scrollbar.css('overflow', 'hidden'); } else { $window.off('resize'); resize({ h: $editable.data('orgheight') }); $scrollbar.css('overflow', 'visible'); } handler.invoke('toolbar.updateFullscreen', $toolbar, isFullscreen); }; }; var CodeMirror; if (agent.hasCodeMirror) { if (agent.isSupportAmd) { require(['CodeMirror'], function (cm) { CodeMirror = cm; }); } else { CodeMirror = window.CodeMirror; } } /** * @class Codeview */ var Codeview = function (handler) { this.sync = function (layoutInfo) { var isCodeview = handler.invoke('codeview.isActivated', layoutInfo); if (isCodeview && agent.hasCodeMirror) { layoutInfo.codable().data('cmEditor').save(); } }; /** * @param {Object} layoutInfo * @return {Boolean} */ this.isActivated = function (layoutInfo) { var $editor = layoutInfo.editor(); return $editor.hasClass('codeview'); }; /** * toggle codeview * * @param {Object} layoutInfo */ this.toggle = function (layoutInfo) { if (this.isActivated(layoutInfo)) { this.deactivate(layoutInfo); } else { this.activate(layoutInfo); } }; /** * activate code view * * @param {Object} layoutInfo */ this.activate = function (layoutInfo) { var $editor = layoutInfo.editor(), $toolbar = layoutInfo.toolbar(), $editable = layoutInfo.editable(), $codable = layoutInfo.codable(), $popover = layoutInfo.popover(), $handle = layoutInfo.handle(); var options = $editor.data('options'); $codable.val(dom.html($editable, options.prettifyHtml)); $codable.height($editable.height()); handler.invoke('toolbar.updateCodeview', $toolbar, true); handler.invoke('popover.hide', $popover); handler.invoke('handle.hide', $handle); $editor.addClass('codeview'); $codable.focus(); // activate CodeMirror as codable if (agent.hasCodeMirror) { var cmEditor = CodeMirror.fromTextArea($codable[0], options.codemirror); // CodeMirror TernServer if (options.codemirror.tern) { var server = new CodeMirror.TernServer(options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function (cm) { server.updateArgHints(cm); }); } // CodeMirror hasn't Padding. cmEditor.setSize(null, $editable.outerHeight()); $codable.data('cmEditor', cmEditor); } }; /** * deactivate code view * * @param {Object} layoutInfo */ this.deactivate = function (layoutInfo) { var $holder = layoutInfo.holder(), $editor = layoutInfo.editor(), $toolbar = layoutInfo.toolbar(), $editable = layoutInfo.editable(), $codable = layoutInfo.codable(); var options = $editor.data('options'); // deactivate CodeMirror as codable if (agent.hasCodeMirror) { var cmEditor = $codable.data('cmEditor'); $codable.val(cmEditor.getValue()); cmEditor.toTextArea(); } var value = dom.value($codable, options.prettifyHtml) || dom.emptyPara; var isChange = $editable.html() !== value; $editable.html(value); $editable.height(options.height ? $codable.height() : 'auto'); $editor.removeClass('codeview'); if (isChange) { handler.bindCustomEvent( $holder, $editable.data('callbacks'), 'change' )($editable.html(), $editable); } $editable.focus(); handler.invoke('toolbar.updateCodeview', $toolbar, false); }; }; var DragAndDrop = function (handler) { var $document = $(document); /** * attach Drag and Drop Events * * @param {Object} layoutInfo - layout Informations * @param {Object} options */ this.attach = function (layoutInfo, options) { if (options.airMode || options.disableDragAndDrop) { // prevent default drop event $document.on('drop', function (e) { e.preventDefault(); }); } else { this.attachDragAndDropEvent(layoutInfo, options); } }; /** * attach Drag and Drop Events * * @param {Object} layoutInfo - layout Informations * @param {Object} options */ this.attachDragAndDropEvent = function (layoutInfo, options) { var collection = $(), $editor = layoutInfo.editor(), $dropzone = layoutInfo.dropzone(), $dropzoneMessage = $dropzone.find('.note-dropzone-message'); // show dropzone on dragenter when dragging a object to document // -but only if the editor is visible, i.e. has a positive width and height $document.on('dragenter', function (e) { var isCodeview = handler.invoke('codeview.isActivated', layoutInfo); var hasEditorSize = $editor.width() > 0 && $editor.height() > 0; if (!isCodeview && !collection.length && hasEditorSize) { $editor.addClass('dragover'); $dropzone.width($editor.width()); $dropzone.height($editor.height()); $dropzoneMessage.text(options.langInfo.image.dragImageHere); } collection = collection.add(e.target); }).on('dragleave', function (e) { collection = collection.not(e.target); if (!collection.length) { $editor.removeClass('dragover'); } }).on('drop', function () { collection = $(); $editor.removeClass('dragover'); }); // change dropzone's message on hover. $dropzone.on('dragenter', function () { $dropzone.addClass('hover'); $dropzoneMessage.text(options.langInfo.image.dropImage); }).on('dragleave', function () { $dropzone.removeClass('hover'); $dropzoneMessage.text(options.langInfo.image.dragImageHere); }); // attach dropImage $dropzone.on('drop', function (event) { var dataTransfer = event.originalEvent.dataTransfer; var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { event.preventDefault(); layoutInfo.editable().focus(); handler.insertImages(layoutInfo, dataTransfer.files); } else { var insertNodefunc = function () { layoutInfo.holder().summernote('insertNode', this); }; for (var i = 0, len = dataTransfer.types.length; i < len; i++) { var type = dataTransfer.types[i]; var content = dataTransfer.getData(type); if (type.toLowerCase().indexOf('text') > -1) { layoutInfo.holder().summernote('pasteHTML', content); } else { $(content).each(insertNodefunc); } } } }).on('dragover', false); // prevent default dragover event }; }; var Clipboard = function (handler) { var $paste; this.attach = function (layoutInfo) { if (window.clipboardData || agent.isFF) { $paste = $('<div />').attr('contenteditable', true).css({ position : 'absolute', left : -100000, opacity : 0 }); layoutInfo.editable().after($paste); $paste.on('paste', hPaste); layoutInfo.editable().on('keydown', function (e) { if (e.ctrlKey && e.keyCode === key.code.V) { handler.invoke('saveRange', layoutInfo.editable()); $paste.focus(); } }); } layoutInfo.editable().on('paste', hPaste); }; /** * paste clipboard image * * @param {Event} event */ var hPaste = function (event) { var clipboardData = event.originalEvent.clipboardData; var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); var $editable = layoutInfo.editable(); if (clipboardData && clipboardData.items && clipboardData.items.length) { // using clipboardData case var item = list.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { handler.insertImages(layoutInfo, [item.getAsFile()]); } handler.invoke('editor.afterCommand', $editable); } else if ($paste && $editable.data('callbacks').onImageUpload) { // using dummy contenteditable: only can run if it has onImageUpload method setTimeout(function () { var node = $paste[0].firstChild; if (dom.isImg(node)) { handler.invoke('restoreRange', $editable); var dataURI = node.src; var decodedData = atob(dataURI.split(',')[1]); var array = new Uint8Array(decodedData.length); for (var i = 0; i < decodedData.length; i++) { array[i] = decodedData.charCodeAt(i); } var blob = new Blob([array], { type : 'image/png' }); blob.name = 'clipboard.png'; handler.invoke('focus', $editable); handler.insertImages(layoutInfo, [blob]); $paste.empty(); } else { var pasteContent = $('<div />').html($paste.html()); handler.invoke('restoreRange', $editable); handler.invoke('focus', $editable); handler.invoke('pasteHTML', $editable, pasteContent.html()); $paste.empty(); } }, 0); } }; }; var LinkDialog = function (handler) { /** * toggle button status * * @private * @param {jQuery} $btn * @param {Boolean} isEnable */ var toggleBtn = function ($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }; /** * bind enter key * * @private * @param {jQuery} $input * @param {jQuery} $btn */ var bindEnterKey = function ($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { $btn.trigger('click'); } }); }; /** * Show link dialog and set event handlers on dialog controls. * * @param {jQuery} $editable * @param {jQuery} $dialog * @param {Object} linkInfo * @return {Promise} */ this.showLinkDialog = function ($editable, $dialog, linkInfo) { return $.Deferred(function (deferred) { var $linkDialog = $dialog.find('.note-link-dialog'); var $linkText = $linkDialog.find('.note-link-text'), $linkUrl = $linkDialog.find('.note-link-url'), $linkBtn = $linkDialog.find('.note-link-btn'), $openInNewWindow = $linkDialog.find('input[type=checkbox]'); $linkDialog.one('shown.bs.modal', function () { $linkText.val(linkInfo.text); $linkText.on('input', function () { toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); // if linktext was modified by keyup, // stop cloning text from linkUrl linkInfo.text = $linkText.val(); }); // if no url was given, copy text to url if (!linkInfo.url) { linkInfo.url = linkInfo.text || 'http://'; toggleBtn($linkBtn, linkInfo.text); } $linkUrl.on('input', function () { toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); // display same link on `Text to display` input // when create a new link if (!linkInfo.text) { $linkText.val($linkUrl.val()); } }).val(linkInfo.url).trigger('focus').trigger('select'); bindEnterKey($linkUrl, $linkBtn); bindEnterKey($linkText, $linkBtn); $openInNewWindow.prop('checked', linkInfo.newWindow); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve({ range: linkInfo.range, url: $linkUrl.val(), text: $linkText.val(), newWindow: $openInNewWindow.is(':checked') }); $linkDialog.modal('hide'); }); }).one('hidden.bs.modal', function () { // detach events $linkText.off('input keypress'); $linkUrl.off('input keypress'); $linkBtn.off('click'); if (deferred.state() === 'pending') { deferred.reject(); } }).modal('show'); }).promise(); }; /** * @param {Object} layoutInfo */ this.show = function (layoutInfo) { var $editor = layoutInfo.editor(), $dialog = layoutInfo.dialog(), $editable = layoutInfo.editable(), $popover = layoutInfo.popover(), linkInfo = handler.invoke('editor.getLinkInfo', $editable); var options = $editor.data('options'); handler.invoke('editor.saveRange', $editable); this.showLinkDialog($editable, $dialog, linkInfo).then(function (linkInfo) { handler.invoke('editor.restoreRange', $editable); handler.invoke('editor.createLink', $editable, linkInfo, options); // hide popover after creating link handler.invoke('popover.hide', $popover); }).fail(function () { handler.invoke('editor.restoreRange', $editable); }); }; }; var ImageDialog = function (handler) { /** * toggle button status * * @private * @param {jQuery} $btn * @param {Boolean} isEnable */ var toggleBtn = function ($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }; /** * bind enter key * * @private * @param {jQuery} $input * @param {jQuery} $btn */ var bindEnterKey = function ($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { $btn.trigger('click'); } }); }; this.show = function (layoutInfo) { var $dialog = layoutInfo.dialog(), $editable = layoutInfo.editable(); handler.invoke('editor.saveRange', $editable); this.showImageDialog($editable, $dialog).then(function (data) { handler.invoke('editor.restoreRange', $editable); if (typeof data === 'string') { // image url handler.invoke('editor.insertImage', $editable, data); } else { // array of files handler.insertImages(layoutInfo, data); } }).fail(function () { handler.invoke('editor.restoreRange', $editable); }); }; /** * show image dialog * * @param {jQuery} $editable * @param {jQuery} $dialog * @return {Promise} */ this.showImageDialog = function ($editable, $dialog) { return $.Deferred(function (deferred) { var $imageDialog = $dialog.find('.note-image-dialog'); var $imageInput = $dialog.find('.note-image-input'), $imageUrl = $dialog.find('.note-image-url'), $imageBtn = $dialog.find('.note-image-btn'); $imageDialog.one('shown.bs.modal', function () { // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone() .on('change', function () { deferred.resolve(this.files || this.value); $imageDialog.modal('hide'); }) .val('') ); $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); $imageDialog.modal('hide'); }); $imageUrl.on('keyup paste', function (event) { var url; if (event.type === 'paste') { url = event.originalEvent.clipboardData.getData('text'); } else { url = $imageUrl.val(); } toggleBtn($imageBtn, url); }).val('').trigger('focus'); bindEnterKey($imageUrl, $imageBtn); }).one('hidden.bs.modal', function () { $imageInput.off('change'); $imageUrl.off('keyup paste keypress'); $imageBtn.off('click'); if (deferred.state() === 'pending') { deferred.reject(); } }).modal('show'); }); }; }; var HelpDialog = function (handler) { /** * show help dialog * * @param {jQuery} $editable * @param {jQuery} $dialog * @return {Promise} */ this.showHelpDialog = function ($editable, $dialog) { return $.Deferred(function (deferred) { var $helpDialog = $dialog.find('.note-help-dialog'); $helpDialog.one('hidden.bs.modal', function () { deferred.resolve(); }).modal('show'); }).promise(); }; /** * @param {Object} layoutInfo */ this.show = function (layoutInfo) { var $dialog = layoutInfo.dialog(), $editable = layoutInfo.editable(); handler.invoke('editor.saveRange', $editable, true); this.showHelpDialog($editable, $dialog).then(function () { handler.invoke('editor.restoreRange', $editable); }); }; }; /** * @class EventHandler * * EventHandler * - TODO: new instance per a editor */ var EventHandler = function () { /** * Modules */ var modules = this.modules = { editor: new Editor(this), toolbar: new Toolbar(this), statusbar: new Statusbar(this), popover: new Popover(this), handle: new Handle(this), fullscreen: new Fullscreen(this), codeview: new Codeview(this), dragAndDrop: new DragAndDrop(this), clipboard: new Clipboard(this), linkDialog: new LinkDialog(this), imageDialog: new ImageDialog(this), helpDialog: new HelpDialog(this) }; /** * invoke module's method * * @param {String} moduleAndMethod - ex) 'editor.redo' * @param {...*} arguments - arguments of method * @return {*} */ this.invoke = function () { var moduleAndMethod = list.head(list.from(arguments)); var args = list.tail(list.from(arguments)); var splits = moduleAndMethod.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && list.head(splits); var methodName = hasSeparator ? list.last(splits) : list.head(splits); var module = this.getModule(moduleName); var method = module[methodName]; return method && method.apply(module, args); }; /** * returns module * * @param {String} moduleName - name of module * @return {Module} - defaults is editor */ this.getModule = function (moduleName) { return this.modules[moduleName] || this.modules.editor; }; /** * @param {jQuery} $holder * @param {Object} callbacks * @param {String} eventNamespace * @returns {Function} */ var bindCustomEvent = this.bindCustomEvent = function ($holder, callbacks, eventNamespace) { return function () { var callback = callbacks[func.namespaceToCamel(eventNamespace, 'on')]; if (callback) { callback.apply($holder[0], arguments); } return $holder.trigger('summernote.' + eventNamespace, arguments); }; }; /** * insert Images from file array. * * @private * @param {Object} layoutInfo * @param {File[]} files */ this.insertImages = function (layoutInfo, files) { var $editor = layoutInfo.editor(), $editable = layoutInfo.editable(), $holder = layoutInfo.holder(); var callbacks = $editable.data('callbacks'); var options = $editor.data('options'); // If onImageUpload options setted if (callbacks.onImageUpload) { bindCustomEvent($holder, callbacks, 'image.upload')(files); // else insert Image as dataURL } else { $.each(files, function (idx, file) { var filename = file.name; if (options.maximumImageFileSize && options.maximumImageFileSize < file.size) { bindCustomEvent($holder, callbacks, 'image.upload.error')(options.langInfo.image.maximumFileSizeError); } else { async.readFileAsDataURL(file).then(function (sDataURL) { modules.editor.insertImage($editable, sDataURL, filename); }).fail(function () { bindCustomEvent($holder, callbacks, 'image.upload.error')(options.langInfo.image.maximumFileSizeError); }); } }); } }; var commands = { /** * @param {Object} layoutInfo */ showLinkDialog: function (layoutInfo) { modules.linkDialog.show(layoutInfo); }, /** * @param {Object} layoutInfo */ showImageDialog: function (layoutInfo) { modules.imageDialog.show(layoutInfo); }, /** * @param {Object} layoutInfo */ showHelpDialog: function (layoutInfo) { modules.helpDialog.show(layoutInfo); }, /** * @param {Object} layoutInfo */ fullscreen: function (layoutInfo) { modules.fullscreen.toggle(layoutInfo); }, /** * @param {Object} layoutInfo */ codeview: function (layoutInfo) { modules.codeview.toggle(layoutInfo); } }; var hMousedown = function (event) { //preventDefault Selection for FF, IE8+ if (dom.isImg(event.target)) { event.preventDefault(); } }; var hKeyupAndMouseup = function (event) { var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); modules.editor.removeBogus(layoutInfo.editable()); hToolbarAndPopoverUpdate(event); }; var hToolbarAndPopoverUpdate = function (event) { // delay for range after mouseup setTimeout(function () { var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); var styleInfo = modules.editor.currentStyle(event.target); if (!styleInfo) { return; } var isAirMode = layoutInfo.editor().data('options').airMode; if (!isAirMode) { modules.toolbar.update(layoutInfo.toolbar(), styleInfo); } modules.popover.update(layoutInfo.popover(), styleInfo, isAirMode); modules.handle.update(layoutInfo.handle(), styleInfo, isAirMode); }, 0); }; var hScroll = function (event) { var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target); //hide popover and handle when scrolled modules.popover.hide(layoutInfo.popover()); modules.handle.hide(layoutInfo.handle()); }; var hToolbarAndPopoverMousedown = function (event) { // prevent default event when insertTable (FF, Webkit) var $btn = $(event.target).closest('[data-event]'); if ($btn.length) { event.preventDefault(); } }; var hToolbarAndPopoverClick = function (event) { var $btn = $(event.target).closest('[data-event]'); if ($btn.length) { var eventName = $btn.attr('data-event'), value = $btn.attr('data-value'), hide = $btn.attr('data-hide'); var layoutInfo = dom.makeLayoutInfo(event.target); // before command: detect control selection element($target) var $target; if ($.inArray(eventName, ['resize', 'floatMe', 'removeMedia', 'imageShape']) !== -1) { var $selection = layoutInfo.handle().find('.note-control-selection'); $target = $($selection.data('target')); } // If requested, hide the popover when the button is clicked. // Useful for things like showHelpDialog. if (hide) { $btn.parents('.popover').hide(); } if ($.isFunction($.summernote.pluginEvents[eventName])) { $.summernote.pluginEvents[eventName](event, modules.editor, layoutInfo, value); } else if (modules.editor[eventName]) { // on command var $editable = layoutInfo.editable(); $editable.focus(); modules.editor[eventName]($editable, value, $target); event.preventDefault(); } else if (commands[eventName]) { commands[eventName].call(this, layoutInfo); event.preventDefault(); } // after command if ($.inArray(eventName, ['backColor', 'foreColor']) !== -1) { var options = layoutInfo.editor().data('options', options); var module = options.airMode ? modules.popover : modules.toolbar; module.updateRecentColor(list.head($btn), eventName, value); } hToolbarAndPopoverUpdate(event); } }; var PX_PER_EM = 18; var hDimensionPickerMove = function (event, options) { var $picker = $(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = $(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.attr('data-value', dim.c + 'x' + dim.r); if (3 < dim.c && dim.c < options.insertTableMaxSize.col) { $unhighlighted.css({ width: dim.c + 1 + 'em'}); } if (3 < dim.r && dim.r < options.insertTableMaxSize.row) { $unhighlighted.css({ height: dim.r + 1 + 'em'}); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); }; /** * bind KeyMap on keydown * * @param {Object} layoutInfo * @param {Object} keyMap */ this.bindKeyMap = function (layoutInfo, keyMap) { var $editor = layoutInfo.editor(); var $editable = layoutInfo.editable(); $editable.on('keydown', function (event) { var keys = []; // modifier if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } // keycode var keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } var pluginEvent; var keyString = keys.join('+'); var eventName = keyMap[keyString]; if (eventName) { // FIXME Summernote doesn't support event pipeline yet. // - Plugin -> Base Code pluginEvent = $.summernote.pluginEvents[keyString]; if ($.isFunction(pluginEvent)) { if (pluginEvent(event, modules.editor, layoutInfo)) { return false; } } pluginEvent = $.summernote.pluginEvents[eventName]; if ($.isFunction(pluginEvent)) { pluginEvent(event, modules.editor, layoutInfo); } else if (modules.editor[eventName]) { modules.editor[eventName]($editable, $editor.data('options')); event.preventDefault(); } else if (commands[eventName]) { commands[eventName].call(this, layoutInfo); event.preventDefault(); } } else if (key.isEdit(event.keyCode)) { modules.editor.afterCommand($editable); } }); }; /** * attach eventhandler * * @param {Object} layoutInfo - layout Informations * @param {Object} options - user options include custom event handlers */ this.attach = function (layoutInfo, options) { // handlers for editable if (options.shortcuts) { this.bindKeyMap(layoutInfo, options.keyMap[agent.isMac ? 'mac' : 'pc']); } layoutInfo.editable().on('mousedown', hMousedown); layoutInfo.editable().on('keyup mouseup', hKeyupAndMouseup); layoutInfo.editable().on('scroll', hScroll); // handler for clipboard modules.clipboard.attach(layoutInfo, options); // handler for handle and popover modules.handle.attach(layoutInfo, options); layoutInfo.popover().on('click', hToolbarAndPopoverClick); layoutInfo.popover().on('mousedown', hToolbarAndPopoverMousedown); // handler for drag and drop modules.dragAndDrop.attach(layoutInfo, options); // handlers for frame mode (toolbar, statusbar) if (!options.airMode) { // handler for toolbar layoutInfo.toolbar().on('click', hToolbarAndPopoverClick); layoutInfo.toolbar().on('mousedown', hToolbarAndPopoverMousedown); // handler for statusbar modules.statusbar.attach(layoutInfo, options); } // handler for table dimension var $catcherContainer = options.airMode ? layoutInfo.popover() : layoutInfo.toolbar(); var $catcher = $catcherContainer.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: options.insertTableMaxSize.col + 'em', height: options.insertTableMaxSize.row + 'em' }).on('mousemove', function (event) { hDimensionPickerMove(event, options); }); // save options on editor layoutInfo.editor().data('options', options); // ret styleWithCSS for backColor / foreColor clearing with 'inherit'. if (!agent.isMSIE) { // [workaround] for Firefox // - protect FF Error: NS_ERROR_FAILURE: Failure setTimeout(function () { document.execCommand('styleWithCSS', 0, options.styleWithSpan); }, 0); } // History var history = new History(layoutInfo.editable()); layoutInfo.editable().data('NoteHistory', history); // All editor status will be saved on editable with jquery's data // for support multiple editor with singleton object. layoutInfo.editable().data('callbacks', { onInit: options.onInit, onFocus: options.onFocus, onBlur: options.onBlur, onKeydown: options.onKeydown, onKeyup: options.onKeyup, onMousedown: options.onMousedown, onEnter: options.onEnter, onPaste: options.onPaste, onBeforeCommand: options.onBeforeCommand, onChange: options.onChange, onImageUpload: options.onImageUpload, onImageUploadError: options.onImageUploadError, onMediaDelete: options.onMediaDelete, onToolbarClick: options.onToolbarClick }); // Textarea: auto filling the code before form submit. if (dom.isTextarea(list.head(layoutInfo.holder()))) { layoutInfo.holder().closest('form').submit(function () { layoutInfo.holder().val(layoutInfo.holder().code()); }); } }; /** * attach jquery custom event * * @param {Object} layoutInfo - layout Informations */ this.attachCustomEvent = function (layoutInfo, options) { var $holder = layoutInfo.holder(); var $editable = layoutInfo.editable(); var callbacks = $editable.data('callbacks'); $editable.focus(bindCustomEvent($holder, callbacks, 'focus')); $editable.blur(bindCustomEvent($holder, callbacks, 'blur')); $editable.keydown(function (event) { if (event.keyCode === key.code.ENTER) { bindCustomEvent($holder, callbacks, 'enter').call(this, event); } bindCustomEvent($holder, callbacks, 'keydown').call(this, event); }); $editable.keyup(bindCustomEvent($holder, callbacks, 'keyup')); $editable.on('mousedown', bindCustomEvent($holder, callbacks, 'mousedown')); $editable.on('mouseup', bindCustomEvent($holder, callbacks, 'mouseup')); $editable.on('scroll', bindCustomEvent($holder, callbacks, 'scroll')); $editable.on('paste', bindCustomEvent($holder, callbacks, 'paste')); // [workaround] IE doesn't have input events for contentEditable // - see: https://goo.gl/4bfIvA var changeEventName = agent.isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input'; $editable.on(changeEventName, function () { bindCustomEvent($holder, callbacks, 'change')($editable.html(), $editable); }); if (!options.airMode) { layoutInfo.toolbar().click(bindCustomEvent($holder, callbacks, 'toolbar.click')); layoutInfo.popover().click(bindCustomEvent($holder, callbacks, 'popover.click')); } // Textarea: auto filling the code before form submit. if (dom.isTextarea(list.head($holder))) { $holder.closest('form').submit(function (e) { bindCustomEvent($holder, callbacks, 'submit').call(this, e, $holder.code()); }); } // fire init event bindCustomEvent($holder, callbacks, 'init')(layoutInfo); // fire plugin init event for (var i = 0, len = $.summernote.plugins.length; i < len; i++) { if ($.isFunction($.summernote.plugins[i].init)) { $.summernote.plugins[i].init(layoutInfo); } } }; this.detach = function (layoutInfo, options) { layoutInfo.holder().off(); layoutInfo.editable().off(); layoutInfo.popover().off(); layoutInfo.handle().off(); layoutInfo.dialog().off(); if (!options.airMode) { layoutInfo.dropzone().off(); layoutInfo.toolbar().off(); layoutInfo.statusbar().off(); } }; }; /** * @class Renderer * * renderer * * rendering toolbar and editable */ var Renderer = function () { /** * bootstrap button template * @private * @param {String} label button name * @param {Object} [options] button options * @param {String} [options.event] data-event * @param {String} [options.className] button's class name * @param {String} [options.value] data-value * @param {String} [options.title] button's title for popup * @param {String} [options.dropdown] dropdown html * @param {String} [options.hide] data-hide */ var tplButton = function (label, options) { var event = options.event; var value = options.value; var title = options.title; var className = options.className; var dropdown = options.dropdown; var hide = options.hide; return (dropdown ? '<div class="btn-group' + (className ? ' ' + className : '') + '">' : '') + '<button type="button"' + ' class="btn btn-default btn-sm' + ((!dropdown && className) ? ' ' + className : '') + (dropdown ? ' dropdown-toggle' : '') + '"' + (dropdown ? ' data-toggle="dropdown"' : '') + (title ? ' title="' + title + '"' : '') + (event ? ' data-event="' + event + '"' : '') + (value ? ' data-value=\'' + value + '\'' : '') + (hide ? ' data-hide=\'' + hide + '\'' : '') + ' tabindex="-1">' + label + (dropdown ? ' <span class="caret"></span>' : '') + '</button>' + (dropdown || '') + (dropdown ? '</div>' : ''); }; /** * bootstrap icon button template * @private * @param {String} iconClassName * @param {Object} [options] * @param {String} [options.event] * @param {String} [options.value] * @param {String} [options.title] * @param {String} [options.dropdown] */ var tplIconButton = function (iconClassName, options) { var label = '<i class="' + iconClassName + '"></i>'; return tplButton(label, options); }; /** * bootstrap popover template * @private * @param {String} className * @param {String} content */ var tplPopover = function (className, content) { var $popover = $('<div class="' + className + ' popover bottom in" style="display: none;">' + '<div class="arrow"></div>' + '<div class="popover-content">' + '</div>' + '</div>'); $popover.find('.popover-content').append(content); return $popover; }; /** * bootstrap dialog template * * @param {String} className * @param {String} [title=''] * @param {String} body * @param {String} [footer=''] */ var tplDialog = function (className, title, body, footer) { return '<div class="' + className + ' modal" aria-hidden="false">' + '<div class="modal-dialog">' + '<div class="modal-content">' + (title ? '<div class="modal-header">' + '<button type="button" class="close" aria-hidden="true" tabindex="-1">&times;</button>' + '<h4 class="modal-title">' + title + '</h4>' + '</div>' : '' ) + '<div class="modal-body">' + body + '</div>' + (footer ? '<div class="modal-footer">' + footer + '</div>' : '' ) + '</div>' + '</div>' + '</div>'; }; /** * bootstrap dropdown template * * @param {String|String[]} contents * @param {String} [className=''] * @param {String} [nodeName=''] */ var tplDropdown = function (contents, className, nodeName) { var classes = 'dropdown-menu' + (className ? ' ' + className : ''); nodeName = nodeName || 'ul'; if (contents instanceof Array) { contents = contents.join(''); } return '<' + nodeName + ' class="' + classes + '">' + contents + '</' + nodeName + '>'; }; var tplButtonInfo = { picture: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.image.image, { event: 'showImageDialog', title: lang.image.image, hide: true }); }, link: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.link.link, { event: 'showLinkDialog', title: lang.link.link, hide: true }); }, table: function (lang, options) { var dropdown = [ '<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display"> 1 x 1 </div>' ]; return tplIconButton(options.iconPrefix + options.icons.table.table, { title: lang.table.table, dropdown: tplDropdown(dropdown, 'note-table') }); }, style: function (lang, options) { var items = options.styleTags.reduce(function (memo, v) { var label = lang.style[v === 'p' ? 'normal' : v]; return memo + '<li><a data-event="formatBlock" href="#" data-value="' + v + '">' + ( (v === 'p' || v === 'pre') ? label : '<' + v + '>' + label + '</' + v + '>' ) + '</a></li>'; }, ''); return tplIconButton(options.iconPrefix + options.icons.style.style, { title: lang.style.style, dropdown: tplDropdown(items) }); }, fontname: function (lang, options) { var realFontList = []; var items = options.fontNames.reduce(function (memo, v) { if (!agent.isFontInstalled(v) && !list.contains(options.fontNamesIgnoreCheck, v)) { return memo; } realFontList.push(v); return memo + '<li><a data-event="fontName" href="#" data-value="' + v + '" style="font-family:\'' + v + '\'">' + '<i class="' + options.iconPrefix + options.icons.misc.check + '"></i> ' + v + '</a></li>'; }, ''); var hasDefaultFont = agent.isFontInstalled(options.defaultFontName); var defaultFontName = (hasDefaultFont) ? options.defaultFontName : realFontList[0]; var label = '<span class="note-current-fontname">' + defaultFontName + '</span>'; return tplButton(label, { title: lang.font.name, className: 'note-fontname', dropdown: tplDropdown(items, 'note-check') }); }, fontsize: function (lang, options) { var items = options.fontSizes.reduce(function (memo, v) { return memo + '<li><a data-event="fontSize" href="#" data-value="' + v + '">' + '<i class="' + options.iconPrefix + options.icons.misc.check + '"></i> ' + v + '</a></li>'; }, ''); var label = '<span class="note-current-fontsize">11</span>'; return tplButton(label, { title: lang.font.size, className: 'note-fontsize', dropdown: tplDropdown(items, 'note-check') }); }, color: function (lang, options) { var colorButtonLabel = '<i class="' + options.iconPrefix + options.icons.color.recent + '" style="color:black;background-color:yellow;"></i>'; var colorButton = tplButton(colorButtonLabel, { className: 'note-recent-color', title: lang.color.recent, event: 'color', value: '{"backColor":"yellow"}' }); var items = [ '<li><div class="btn-group">', '<div class="note-palette-title">' + lang.color.background + '</div>', '<div class="note-color-reset" data-event="backColor"', ' data-value="inherit" title="' + lang.color.transparent + '">' + lang.color.setTransparent + '</div>', '<div class="note-color-palette" data-target-event="backColor"></div>', '</div><div class="btn-group">', '<div class="note-palette-title">' + lang.color.foreground + '</div>', '<div class="note-color-reset" data-event="foreColor" data-value="inherit" title="' + lang.color.reset + '">', lang.color.resetToDefault, '</div>', '<div class="note-color-palette" data-target-event="foreColor"></div>', '</div></li>' ]; var moreButton = tplButton('', { title: lang.color.more, dropdown: tplDropdown(items) }); return colorButton + moreButton; }, bold: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.bold, { event: 'bold', title: lang.font.bold }); }, italic: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.italic, { event: 'italic', title: lang.font.italic }); }, underline: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.underline, { event: 'underline', title: lang.font.underline }); }, strikethrough: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.strikethrough, { event: 'strikethrough', title: lang.font.strikethrough }); }, superscript: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.superscript, { event: 'superscript', title: lang.font.superscript }); }, subscript: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.subscript, { event: 'subscript', title: lang.font.subscript }); }, clear: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.font.clear, { event: 'removeFormat', title: lang.font.clear }); }, ul: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.lists.unordered, { event: 'insertUnorderedList', title: lang.lists.unordered }); }, ol: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.lists.ordered, { event: 'insertOrderedList', title: lang.lists.ordered }); }, paragraph: function (lang, options) { var leftButton = tplIconButton(options.iconPrefix + options.icons.paragraph.left, { title: lang.paragraph.left, event: 'justifyLeft' }); var centerButton = tplIconButton(options.iconPrefix + options.icons.paragraph.center, { title: lang.paragraph.center, event: 'justifyCenter' }); var rightButton = tplIconButton(options.iconPrefix + options.icons.paragraph.right, { title: lang.paragraph.right, event: 'justifyRight' }); var justifyButton = tplIconButton(options.iconPrefix + options.icons.paragraph.justify, { title: lang.paragraph.justify, event: 'justifyFull' }); var outdentButton = tplIconButton(options.iconPrefix + options.icons.paragraph.outdent, { title: lang.paragraph.outdent, event: 'outdent' }); var indentButton = tplIconButton(options.iconPrefix + options.icons.paragraph.indent, { title: lang.paragraph.indent, event: 'indent' }); var dropdown = [ '<div class="note-align btn-group">', leftButton + centerButton + rightButton + justifyButton, '</div><div class="note-list btn-group">', indentButton + outdentButton, '</div>' ]; return tplIconButton(options.iconPrefix + options.icons.paragraph.paragraph, { title: lang.paragraph.paragraph, dropdown: tplDropdown(dropdown, '', 'div') }); }, height: function (lang, options) { var items = options.lineHeights.reduce(function (memo, v) { return memo + '<li><a data-event="lineHeight" href="#" data-value="' + parseFloat(v) + '">' + '<i class="' + options.iconPrefix + options.icons.misc.check + '"></i> ' + v + '</a></li>'; }, ''); return tplIconButton(options.iconPrefix + options.icons.font.height, { title: lang.font.height, dropdown: tplDropdown(items, 'note-check') }); }, help: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.options.help, { event: 'showHelpDialog', title: lang.options.help, hide: true }); }, fullscreen: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.options.fullscreen, { event: 'fullscreen', title: lang.options.fullscreen }); }, codeview: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.options.codeview, { event: 'codeview', title: lang.options.codeview }); }, undo: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.history.undo, { event: 'undo', title: lang.history.undo }); }, redo: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.history.redo, { event: 'redo', title: lang.history.redo }); }, hr: function (lang, options) { return tplIconButton(options.iconPrefix + options.icons.hr.insert, { event: 'insertHorizontalRule', title: lang.hr.insert }); } }; var tplPopovers = function (lang, options) { var tplLinkPopover = function () { var linkButton = tplIconButton(options.iconPrefix + options.icons.link.edit, { title: lang.link.edit, event: 'showLinkDialog', hide: true }); var unlinkButton = tplIconButton(options.iconPrefix + options.icons.link.unlink, { title: lang.link.unlink, event: 'unlink' }); var content = '<a href="http://www.google.com" target="_blank">www.google.com</a>&nbsp;&nbsp;' + '<div class="note-insert btn-group">' + linkButton + unlinkButton + '</div>'; return tplPopover('note-link-popover', content); }; var tplImagePopover = function () { var fullButton = tplButton('<span class="note-fontsize-10">100%</span>', { title: lang.image.resizeFull, event: 'resize', value: '1' }); var halfButton = tplButton('<span class="note-fontsize-10">50%</span>', { title: lang.image.resizeHalf, event: 'resize', value: '0.5' }); var quarterButton = tplButton('<span class="note-fontsize-10">25%</span>', { title: lang.image.resizeQuarter, event: 'resize', value: '0.25' }); var leftButton = tplIconButton(options.iconPrefix + options.icons.image.floatLeft, { title: lang.image.floatLeft, event: 'floatMe', value: 'left' }); var rightButton = tplIconButton(options.iconPrefix + options.icons.image.floatRight, { title: lang.image.floatRight, event: 'floatMe', value: 'right' }); var justifyButton = tplIconButton(options.iconPrefix + options.icons.image.floatNone, { title: lang.image.floatNone, event: 'floatMe', value: 'none' }); var roundedButton = tplIconButton(options.iconPrefix + options.icons.image.shapeRounded, { title: lang.image.shapeRounded, event: 'imageShape', value: 'img-rounded' }); var circleButton = tplIconButton(options.iconPrefix + options.icons.image.shapeCircle, { title: lang.image.shapeCircle, event: 'imageShape', value: 'img-circle' }); var thumbnailButton = tplIconButton(options.iconPrefix + options.icons.image.shapeThumbnail, { title: lang.image.shapeThumbnail, event: 'imageShape', value: 'img-thumbnail' }); var noneButton = tplIconButton(options.iconPrefix + options.icons.image.shapeNone, { title: lang.image.shapeNone, event: 'imageShape', value: '' }); var removeButton = tplIconButton(options.iconPrefix + options.icons.image.remove, { title: lang.image.remove, event: 'removeMedia', value: 'none' }); var content = '<div class="btn-group">' + fullButton + halfButton + quarterButton + '</div>' + '<div class="btn-group">' + leftButton + rightButton + justifyButton + '</div><br>' + '<div class="btn-group">' + roundedButton + circleButton + thumbnailButton + noneButton + '</div>' + '<div class="btn-group">' + removeButton + '</div>'; return tplPopover('note-image-popover', content); }; var tplAirPopover = function () { var $content = $('<div />'); for (var idx = 0, len = options.airPopover.length; idx < len; idx ++) { var group = options.airPopover[idx]; var $group = $('<div class="note-' + group[0] + ' btn-group">'); for (var i = 0, lenGroup = group[1].length; i < lenGroup; i++) { var $button = $(tplButtonInfo[group[1][i]](lang, options)); $button.attr('data-name', group[1][i]); $group.append($button); } $content.append($group); } return tplPopover('note-air-popover', $content.children()); }; var $notePopover = $('<div class="note-popover" />'); $notePopover.append(tplLinkPopover()); $notePopover.append(tplImagePopover()); if (options.airMode) { $notePopover.append(tplAirPopover()); } return $notePopover; }; var tplHandles = function () { return '<div class="note-handle">' + '<div class="note-control-selection">' + '<div class="note-control-selection-bg"></div>' + '<div class="note-control-holder note-control-nw"></div>' + '<div class="note-control-holder note-control-ne"></div>' + '<div class="note-control-holder note-control-sw"></div>' + '<div class="note-control-sizing note-control-se"></div>' + '<div class="note-control-selection-info"></div>' + '</div>' + '</div>'; }; /** * shortcut table template * @param {String} title * @param {String} body */ var tplShortcut = function (title, keys) { var keyClass = 'note-shortcut-col col-xs-6 note-shortcut-'; var body = []; for (var i in keys) { if (keys.hasOwnProperty(i)) { body.push( '<div class="' + keyClass + 'key">' + keys[i].kbd + '</div>' + '<div class="' + keyClass + 'name">' + keys[i].text + '</div>' ); } } return '<div class="note-shortcut-row row"><div class="' + keyClass + 'title col-xs-offset-6">' + title + '</div></div>' + '<div class="note-shortcut-row row">' + body.join('</div><div class="note-shortcut-row row">') + '</div>'; }; var tplShortcutText = function (lang) { var keys = [ { kbd: '⌘ + B', text: lang.font.bold }, { kbd: '⌘ + I', text: lang.font.italic }, { kbd: '⌘ + U', text: lang.font.underline }, { kbd: '⌘ + \\', text: lang.font.clear } ]; return tplShortcut(lang.shortcut.textFormatting, keys); }; var tplShortcutAction = function (lang) { var keys = [ { kbd: '⌘ + Z', text: lang.history.undo }, { kbd: '⌘ + ⇧ + Z', text: lang.history.redo }, { kbd: '⌘ + ]', text: lang.paragraph.indent }, { kbd: '⌘ + [', text: lang.paragraph.outdent }, { kbd: '⌘ + ENTER', text: lang.hr.insert } ]; return tplShortcut(lang.shortcut.action, keys); }; var tplShortcutPara = function (lang) { var keys = [ { kbd: '⌘ + ⇧ + L', text: lang.paragraph.left }, { kbd: '⌘ + ⇧ + E', text: lang.paragraph.center }, { kbd: '⌘ + ⇧ + R', text: lang.paragraph.right }, { kbd: '⌘ + ⇧ + J', text: lang.paragraph.justify }, { kbd: '⌘ + ⇧ + NUM7', text: lang.lists.ordered }, { kbd: '⌘ + ⇧ + NUM8', text: lang.lists.unordered } ]; return tplShortcut(lang.shortcut.paragraphFormatting, keys); }; var tplShortcutStyle = function (lang) { var keys = [ { kbd: '⌘ + NUM0', text: lang.style.normal }, { kbd: '⌘ + NUM1', text: lang.style.h1 }, { kbd: '⌘ + NUM2', text: lang.style.h2 }, { kbd: '⌘ + NUM3', text: lang.style.h3 }, { kbd: '⌘ + NUM4', text: lang.style.h4 }, { kbd: '⌘ + NUM5', text: lang.style.h5 }, { kbd: '⌘ + NUM6', text: lang.style.h6 } ]; return tplShortcut(lang.shortcut.documentStyle, keys); }; var tplExtraShortcuts = function (lang, options) { var extraKeys = options.extraKeys; var keys = []; for (var key in extraKeys) { if (extraKeys.hasOwnProperty(key)) { keys.push({ kbd: key, text: extraKeys[key] }); } } return tplShortcut(lang.shortcut.extraKeys, keys); }; var tplShortcutTable = function (lang, options) { var colClass = 'class="note-shortcut note-shortcut-col col-sm-6 col-xs-12"'; var template = [ '<div ' + colClass + '>' + tplShortcutAction(lang, options) + '</div>' + '<div ' + colClass + '>' + tplShortcutText(lang, options) + '</div>', '<div ' + colClass + '>' + tplShortcutStyle(lang, options) + '</div>' + '<div ' + colClass + '>' + tplShortcutPara(lang, options) + '</div>' ]; if (options.extraKeys) { template.push('<div ' + colClass + '>' + tplExtraShortcuts(lang, options) + '</div>'); } return '<div class="note-shortcut-row row">' + template.join('</div><div class="note-shortcut-row row">') + '</div>'; }; var replaceMacKeys = function (sHtml) { return sHtml.replace(/⌘/g, 'Ctrl').replace(/⇧/g, 'Shift'); }; var tplDialogInfo = { image: function (lang, options) { var imageLimitation = ''; if (options.maximumImageFileSize) { var unit = Math.floor(Math.log(options.maximumImageFileSize) / Math.log(1024)); var readableSize = (options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B'; imageLimitation = '<small>' + lang.image.maximumFileSize + ' : ' + readableSize + '</small>'; } var body = '<div class="form-group row note-group-select-from-files">' + '<label>' + lang.image.selectFromFiles + '</label>' + '<input class="note-image-input" type="file" name="files" accept="image/*" multiple="multiple" />' + imageLimitation + '</div>' + '<div class="form-group row">' + '<label>' + lang.image.url + '</label>' + '<input class="note-image-url form-control col-md-12" type="text" />' + '</div>'; var footer = '<button href="#" class="btn btn-primary note-image-btn disabled" disabled>' + lang.image.insert + '</button>'; return tplDialog('note-image-dialog', lang.image.insert, body, footer); }, link: function (lang, options) { var body = '<div class="form-group row">' + '<label>' + lang.link.textToDisplay + '</label>' + '<input class="note-link-text form-control col-md-12" type="text" />' + '</div>' + '<div class="form-group row">' + '<label>' + lang.link.url + '</label>' + '<input class="note-link-url form-control col-md-12" type="text" value="http://" />' + '</div>' + (!options.disableLinkTarget ? '<div class="checkbox">' + '<label>' + '<input type="checkbox" checked> ' + lang.link.openInNewWindow + '</label>' + '</div>' : '' ); var footer = '<button href="#" class="btn btn-primary note-link-btn disabled" disabled>' + lang.link.insert + '</button>'; return tplDialog('note-link-dialog', lang.link.insert, body, footer); }, help: function (lang, options) { var body = '<a class="modal-close pull-right" aria-hidden="true" tabindex="-1">' + lang.shortcut.close + '</a>' + '<div class="title">' + lang.shortcut.shortcuts + '</div>' + (agent.isMac ? tplShortcutTable(lang, options) : replaceMacKeys(tplShortcutTable(lang, options))) + '<p class="text-center">' + '<a href="//summernote.org/" target="_blank">Summernote 0.6.13</a> · ' + '<a href="//github.com/summernote/summernote" target="_blank">Project</a> · ' + '<a href="//github.com/summernote/summernote/issues" target="_blank">Issues</a>' + '</p>'; return tplDialog('note-help-dialog', '', body, ''); } }; var tplDialogs = function (lang, options) { var dialogs = ''; $.each(tplDialogInfo, function (idx, tplDialog) { dialogs += tplDialog(lang, options); }); return '<div class="note-dialog">' + dialogs + '</div>'; }; var tplStatusbar = function () { return '<div class="note-resizebar">' + '<div class="note-icon-bar"></div>' + '<div class="note-icon-bar"></div>' + '<div class="note-icon-bar"></div>' + '</div>'; }; var representShortcut = function (str) { if (agent.isMac) { str = str.replace('CMD', '⌘').replace('SHIFT', '⇧'); } return str.replace('BACKSLASH', '\\') .replace('SLASH', '/') .replace('LEFTBRACKET', '[') .replace('RIGHTBRACKET', ']'); }; /** * createTooltip * * @param {jQuery} $container * @param {Object} keyMap * @param {String} [sPlacement] */ var createTooltip = function ($container, keyMap, sPlacement) { var invertedKeyMap = func.invertObject(keyMap); var $buttons = $container.find('button'); $buttons.each(function (i, elBtn) { var $btn = $(elBtn); var sShortcut = invertedKeyMap[$btn.data('event')]; if (sShortcut) { $btn.attr('title', function (i, v) { return v + ' (' + representShortcut(sShortcut) + ')'; }); } // bootstrap tooltip on btn-group bug // https://github.com/twbs/bootstrap/issues/5687 }).tooltip({ container: 'body', trigger: 'hover', placement: sPlacement || 'top' }).on('click', function () { $(this).tooltip('hide'); }); }; // createPalette var createPalette = function ($container, options) { var colorInfo = options.colors; $container.find('.note-color-palette').each(function () { var $palette = $(this), eventName = $palette.attr('data-target-event'); var paletteContents = []; for (var row = 0, lenRow = colorInfo.length; row < lenRow; row++) { var colors = colorInfo[row]; var buttons = []; for (var col = 0, lenCol = colors.length; col < lenCol; col++) { var color = colors[col]; buttons.push(['<button type="button" class="note-color-btn" style="background-color:', color, ';" data-event="', eventName, '" data-value="', color, '" title="', color, '" data-toggle="button" tabindex="-1"></button>'].join('')); } paletteContents.push('<div class="note-color-row">' + buttons.join('') + '</div>'); } $palette.html(paletteContents.join('')); }); }; /** * create summernote layout (air mode) * * @param {jQuery} $holder * @param {Object} options */ this.createLayoutByAirMode = function ($holder, options) { var langInfo = options.langInfo; var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc']; var id = func.uniqueId(); $holder.addClass('note-air-editor note-editable panel-body'); $holder.attr({ 'id': 'note-editor-' + id, 'contentEditable': true }); var body = document.body; // create Popover var $popover = $(tplPopovers(langInfo, options)); $popover.addClass('note-air-layout'); $popover.attr('id', 'note-popover-' + id); $popover.appendTo(body); createTooltip($popover, keyMap); createPalette($popover, options); // create Handle var $handle = $(tplHandles()); $handle.addClass('note-air-layout'); $handle.attr('id', 'note-handle-' + id); $handle.appendTo(body); // create Dialog var $dialog = $(tplDialogs(langInfo, options)); $dialog.addClass('note-air-layout'); $dialog.attr('id', 'note-dialog-' + id); $dialog.find('button.close, a.modal-close').click(function () { $(this).closest('.modal').modal('hide'); }); $dialog.appendTo(body); }; /** * create summernote layout (normal mode) * * @param {jQuery} $holder * @param {Object} options */ this.createLayoutByFrame = function ($holder, options) { var langInfo = options.langInfo; //01. create Editor var $editor = $('<div class="note-editor panel panel-default" />'); if (options.width) { $editor.width(options.width); } //02. statusbar (resizebar) if (options.height > 0) { $('<div class="note-statusbar">' + (options.disableResizeEditor ? '' : tplStatusbar()) + '</div>').prependTo($editor); } //03 editing area var $editingArea = $('<div class="note-editing-area" />'); //03. create editable var isContentEditable = !$holder.is(':disabled'); var $editable = $('<div class="note-editable panel-body" contentEditable="' + isContentEditable + '"></div>').prependTo($editingArea); if (options.height) { $editable.height(options.height); } if (options.direction) { $editable.attr('dir', options.direction); } var placeholder = $holder.attr('placeholder') || options.placeholder; if (placeholder) { $editable.attr('data-placeholder', placeholder); } $editable.html(dom.html($holder) || dom.emptyPara); //031. create codable $('<textarea class="note-codable"></textarea>').prependTo($editingArea); //04. create Popover var $popover = $(tplPopovers(langInfo, options)).prependTo($editingArea); createPalette($popover, options); createTooltip($popover, keyMap); //05. handle(control selection, ...) $(tplHandles()).prependTo($editingArea); $editingArea.prependTo($editor); //06. create Toolbar var $toolbar = $('<div class="note-toolbar panel-heading" />'); for (var idx = 0, len = options.toolbar.length; idx < len; idx ++) { var groupName = options.toolbar[idx][0]; var groupButtons = options.toolbar[idx][1]; var $group = $('<div class="note-' + groupName + ' btn-group" />'); for (var i = 0, btnLength = groupButtons.length; i < btnLength; i++) { var buttonInfo = tplButtonInfo[groupButtons[i]]; // continue creating toolbar even if a button doesn't exist if (!$.isFunction(buttonInfo)) { continue; } var $button = $(buttonInfo(langInfo, options)); $button.attr('data-name', groupButtons[i]); // set button's alias, becuase to get button element from $toolbar $group.append($button); } $toolbar.append($group); } var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc']; createPalette($toolbar, options); createTooltip($toolbar, keyMap, 'bottom'); $toolbar.prependTo($editor); //07. create Dropzone $('<div class="note-dropzone"><div class="note-dropzone-message"></div></div>').prependTo($editor); //08. create Dialog var $dialogContainer = options.dialogsInBody ? $(document.body) : $editor; var $dialog = $(tplDialogs(langInfo, options)).prependTo($dialogContainer); $dialog.find('button.close, a.modal-close').click(function () { $(this).closest('.modal').modal('hide'); }); //09. Editor/Holder switch $editor.insertAfter($holder); $holder.hide(); }; this.hasNoteEditor = function ($holder) { return this.noteEditorFromHolder($holder).length > 0; }; this.noteEditorFromHolder = function ($holder) { if ($holder.hasClass('note-air-editor')) { return $holder; } else if ($holder.next().hasClass('note-editor')) { return $holder.next(); } else { return $(); } }; /** * create summernote layout * * @param {jQuery} $holder * @param {Object} options */ this.createLayout = function ($holder, options) { if (options.airMode) { this.createLayoutByAirMode($holder, options); } else { this.createLayoutByFrame($holder, options); } }; /** * returns layoutInfo from holder * * @param {jQuery} $holder - placeholder * @return {Object} */ this.layoutInfoFromHolder = function ($holder) { var $editor = this.noteEditorFromHolder($holder); if (!$editor.length) { return; } // connect $holder to $editor $editor.data('holder', $holder); return dom.buildLayoutInfo($editor); }; /** * removeLayout * * @param {jQuery} $holder - placeholder * @param {Object} layoutInfo * @param {Object} options * */ this.removeLayout = function ($holder, layoutInfo, options) { if (options.airMode) { $holder.removeClass('note-air-editor note-editable') .removeAttr('id contentEditable'); layoutInfo.popover().remove(); layoutInfo.handle().remove(); layoutInfo.dialog().remove(); } else { $holder.html(layoutInfo.editable().html()); if (options.dialogsInBody) { layoutInfo.dialog().remove(); } layoutInfo.editor().remove(); $holder.show(); } }; /** * * @return {Object} * @return {function(label, options=):string} return.button {@link #tplButton function to make text button} * @return {function(iconClass, options=):string} return.iconButton {@link #tplIconButton function to make icon button} * @return {function(className, title=, body=, footer=):string} return.dialog {@link #tplDialog function to make dialog} */ this.getTemplate = function () { return { button: tplButton, iconButton: tplIconButton, dialog: tplDialog }; }; /** * add button information * * @param {String} name button name * @param {Function} buttonInfo function to make button, reference to {@link #tplButton},{@link #tplIconButton} */ this.addButtonInfo = function (name, buttonInfo) { tplButtonInfo[name] = buttonInfo; }; /** * * @param {String} name * @param {Function} dialogInfo function to make dialog, reference to {@link #tplDialog} */ this.addDialogInfo = function (name, dialogInfo) { tplDialogInfo[name] = dialogInfo; }; }; // jQuery namespace for summernote /** * @class $.summernote * * summernote attribute * * @mixin defaults * @singleton * */ $.summernote = $.summernote || {}; // extends default settings // - $.summernote.version // - $.summernote.options // - $.summernote.lang $.extend($.summernote, defaults); var renderer = new Renderer(); var eventHandler = new EventHandler(); $.extend($.summernote, { /** @property {Renderer} */ renderer: renderer, /** @property {EventHandler} */ eventHandler: eventHandler, /** * @property {Object} core * @property {core.agent} core.agent * @property {core.dom} core.dom * @property {core.range} core.range */ core: { agent: agent, list : list, dom: dom, range: range }, /** * @property {Object} * pluginEvents event list for plugins * event has name and callback function. * * ``` * $.summernote.addPlugin({ * events : { * 'hello' : function(layoutInfo, value, $target) { * console.log('event name is hello, value is ' + value ); * } * } * }) * ``` * * * event name is data-event property. * * layoutInfo is a summernote layout information. * * value is data-value property. */ pluginEvents: {}, plugins : [] }); /** * @method addPlugin * * add Plugin in Summernote * * Summernote can make a own plugin. * * ### Define plugin * ``` * // get template function * var tmpl = $.summernote.renderer.getTemplate(); * * // add a button * $.summernote.addPlugin({ * buttons : { * // "hello" is button's namespace. * "hello" : function(lang, options) { * // make icon button by template function * return tmpl.iconButton(options.iconPrefix + 'header', { * // callback function name when button clicked * event : 'hello', * // set data-value property * value : 'hello', * hide : true * }); * } * * }, * * events : { * "hello" : function(layoutInfo, value) { * // here is event code * } * } * }); * ``` * ### Use a plugin in toolbar * * ``` * $("#editor").summernote({ * ... * toolbar : [ * // display hello plugin in toolbar * ['group', [ 'hello' ]] * ] * ... * }); * ``` * * * @param {Object} plugin * @param {Object} [plugin.buttons] define plugin button. for detail, see to Renderer.addButtonInfo * @param {Object} [plugin.dialogs] define plugin dialog. for detail, see to Renderer.addDialogInfo * @param {Object} [plugin.events] add event in $.summernote.pluginEvents * @param {Object} [plugin.langs] update $.summernote.lang * @param {Object} [plugin.options] update $.summernote.options */ $.summernote.addPlugin = function (plugin) { // save plugin list $.summernote.plugins.push(plugin); if (plugin.buttons) { $.each(plugin.buttons, function (name, button) { renderer.addButtonInfo(name, button); }); } if (plugin.dialogs) { $.each(plugin.dialogs, function (name, dialog) { renderer.addDialogInfo(name, dialog); }); } if (plugin.events) { $.each(plugin.events, function (name, event) { $.summernote.pluginEvents[name] = event; }); } if (plugin.langs) { $.each(plugin.langs, function (locale, lang) { if ($.summernote.lang[locale]) { $.extend($.summernote.lang[locale], lang); } }); } if (plugin.options) { $.extend($.summernote.options, plugin.options); } }; /* * extend $.fn */ $.fn.extend({ /** * @method * Initialize summernote * - create editor layout and attach Mouse and keyboard events. * * ``` * $("#summernote").summernote( { options ..} ); * ``` * * @member $.fn * @param {Object|String} options reference to $.summernote.options * @return {this} */ summernote: function () { // check first argument's type // - {String}: External API call {{module}}.{{method}} // - {Object}: init options var type = $.type(list.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; // extend default options with custom user options var options = hasInitOptions ? list.head(arguments) : {}; options = $.extend({}, $.summernote.options, options); options.icons = $.extend({}, $.summernote.options.icons, options.icons); // Include langInfo in options for later use, e.g. for image drag-n-drop // Setup language info with en-US as default options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]); // override plugin options if (!isExternalAPICalled && hasInitOptions) { for (var i = 0, len = $.summernote.plugins.length; i < len; i++) { var plugin = $.summernote.plugins[i]; if (options.plugin[plugin.name]) { $.summernote.plugins[i] = $.extend(true, plugin, options.plugin[plugin.name]); } } } this.each(function (idx, holder) { var $holder = $(holder); // if layout isn't created yet, createLayout and attach events if (!renderer.hasNoteEditor($holder)) { renderer.createLayout($holder, options); var layoutInfo = renderer.layoutInfoFromHolder($holder); $holder.data('layoutInfo', layoutInfo); eventHandler.attach(layoutInfo, options); eventHandler.attachCustomEvent(layoutInfo, options); } }); var $first = this.first(); if ($first.length) { var layoutInfo = renderer.layoutInfoFromHolder($first); // external API if (isExternalAPICalled) { var moduleAndMethod = list.head(list.from(arguments)); var args = list.tail(list.from(arguments)); // TODO now external API only works for editor var params = [moduleAndMethod, layoutInfo.editable()].concat(args); return eventHandler.invoke.apply(eventHandler, params); } else if (options.focus) { // focus on first editable element for initialize editor layoutInfo.editable().focus(); } } return this; }, /** * @method * * get the HTML contents of note or set the HTML contents of note. * * * get contents * ``` * var content = $("#summernote").code(); * ``` * * set contents * * ``` * $("#summernote").code(html); * ``` * * @member $.fn * @param {String} [html] - HTML contents(optional, set) * @return {this|String} - context(set) or HTML contents of note(get). */ code: function (html) { // get the HTML contents of note if (html === undefined) { var $holder = this.first(); if (!$holder.length) { return; } var layoutInfo = renderer.layoutInfoFromHolder($holder); var $editable = layoutInfo && layoutInfo.editable(); if ($editable && $editable.length) { var isCodeview = eventHandler.invoke('codeview.isActivated', layoutInfo); eventHandler.invoke('codeview.sync', layoutInfo); return isCodeview ? layoutInfo.codable().val() : layoutInfo.editable().html(); } return dom.value($holder); } // set the HTML contents of note this.each(function (i, holder) { var layoutInfo = renderer.layoutInfoFromHolder($(holder)); var $editable = layoutInfo && layoutInfo.editable(); if ($editable) { $editable.html(html); } }); return this; }, /** * @method * * destroy Editor Layout and detach Key and Mouse Event * * @member $.fn * @return {this} */ destroy: function () { this.each(function (idx, holder) { var $holder = $(holder); if (!renderer.hasNoteEditor($holder)) { return; } var info = renderer.layoutInfoFromHolder($holder); var options = info.editor().data('options'); eventHandler.detach(info, options); renderer.removeLayout($holder, info, options); }); return this; } }); }));
/** * API Bound Models for AngularJS * @version v1.1.10 - 2015-10-24 * @link https://github.com/angular-platanus/restmod * @author Ignacio Baixas <ignacio@platan.us> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function(angular, undefined) { 'use strict'; /** * @mixin PagedModel * * @description Extracts header paging information into the `$page` and `$pageCount` properties. * * Usage: * * Just add mixin to a model's mixin chain * * ```javascript * var Bike = restmod.model('api/bikes', 'PagedModel'); * ``` * * Then using fetch on a collection bound to a paged api should provide page information * * ```javascript * Bike.$search().$then(function() { * console.log this.$page; // should print the current page number. * console.log this.$pageCount; // should print the request total page count. * }); * ``` * * Paging information is extracted from the 'X-Page' and the 'X-Page-Total' headers, to use different headers just * override the $pageHeader or the $pageCountHeader definition during model building. * * ```javascript * restmod.model('PagedModel', function() { * this.define('$pageHeader', 'X-My-Page-Header'); * }) * ``` * */ angular.module('restmod').factory('PagedModel', ['restmod', function(restmod) { return restmod.mixin(function() { this.setProperty('pageHeader', 'X-Page') .setProperty('pageCountHeader', 'X-Page-Total') .on('after-fetch-many', function(_response) { var page = _response.headers(this.$type.getProperty('pageHeader')), pageCount = _response.headers(this.$type.getProperty('pageCountHeader')); this.$page = (page !== undefined ? parseInt(page, 10) : 1); this.$pageCount = (pageCount !== undefined ? parseInt(pageCount, 10) : 1); }); }); }]);})(angular);
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("widget","fr",{move:"Cliquer et glisser pour déplacer",label:"Élément %1"});
class A {static ["prototype"](){}}
/*! * https://github.com/paulmillr/es6-shim * @license es6-shim Copyright 2013-2014 by Paul Miller (http://paulmillr.com) * and contributors, MIT License * es6-sham: v0.22.0 * see https://github.com/paulmillr/es6-shim/blob/0.22.0/LICENSE * Details and documentation: * https://github.com/paulmillr/es6-shim/ */ (function(t,e){if(typeof define==="function"&&define.amd){define(e)}else if(typeof exports==="object"){module.exports=e()}else{t.returnExports=e()}})(this,function(t){"use strict";var e=new Function("return this;");var r=e();var n=r.Object;(function(){if(n.setPrototypeOf){return}var t=function(t,e){i(e).forEach(function(r){o(t,r,c(e,r))});return t};var e=function(e,n){return t(r(n),e)};var r=n.create;var o=n.defineProperty;var f=n.getPrototypeOf;var i=n.getOwnPropertyNames;var c=n.getOwnPropertyDescriptor;var u=n.prototype;var a,_;try{a=c(u,"__proto__").set;a.call({},null);_=function(t,e){a.call(t,e);return t}}catch(p){a={__proto__:null};if(a instanceof n){_=e}else{a.__proto__=u;if(a instanceof n){_=function(t,e){t.__proto__=e;return t}}else{_=function(t,r){return f(t)?(t.__proto__=r,t):e(t,r)}}}}n.setPrototypeOf=_})()}); //# sourceMappingURL=es6-sham.map
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.uacss"]){ dojo._hasResource["dojo.uacss"]=true; dojo.provide("dojo.uacss"); (function(){ var d=dojo,_1=d.doc.documentElement,ie=d.isIE,_2=d.isOpera,_3=Math.floor,ff=d.isFF,_4=d.boxModel.replace(/-/,""),_5={dj_ie:ie,dj_ie6:_3(ie)==6,dj_ie7:_3(ie)==7,dj_ie8:_3(ie)==8,dj_ie9:_3(ie)==9,dj_quirks:d.isQuirks,dj_iequirks:ie&&d.isQuirks,dj_opera:_2,dj_khtml:d.isKhtml,dj_webkit:d.isWebKit,dj_safari:d.isSafari,dj_chrome:d.isChrome,dj_gecko:d.isMozilla,dj_ff3:_3(ff)==3}; _5["dj_"+_4]=true; var _6=""; for(var _7 in _5){ if(_5[_7]){ _6+=_7+" "; } } _1.className=d.trim(_1.className+" "+_6); dojo._loaders.unshift(function(){ if(!dojo._isBodyLtr()){ var _8="dj_rtl dijitRtl "+_6.replace(/ /g,"-rtl "); _1.className=d.trim(_1.className+" "+_8); } }); })(); }
var baseFlatten = require('../internal/baseFlatten'), baseSortByOrder = require('../internal/baseSortByOrder'), isIterateeCall = require('../internal/isIterateeCall'); /** * This method is like `_.sortBy` except that it sorts by property names * instead of an iteratee function. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(string|string[])} props The property names to sort by, * specified as individual property names or arrays of property names. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 26 }, * { 'user': 'fred', 'age': 30 } * ]; * * _.map(_.sortByAll(users, ['user', 'age']), _.values); * // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] */ function sortByAll() { var args = arguments, collection = args[0], guard = args[3], index = 0, length = args.length - 1; if (collection == null) { return []; } var props = Array(length); while (index < length) { props[index] = args[++index]; } if (guard && isIterateeCall(args[1], args[2], guard)) { props = args[1]; } return baseSortByOrder(collection, baseFlatten(props), []); } module.exports = sortByAll;
function max () { // http://kevin.vanzonneveld.net // + original by: Onno Marsman // + revised by: Onno Marsman // + tweaked by: Jack // % note: Long code cause we're aiming for maximum PHP compatibility // * example 1: max(1, 3, 5, 6, 7); // * returns 1: 7 // * example 2: max([2, 4, 5]); // * returns 2: 5 // * example 3: max(0, 'hello'); // * returns 3: 0 // * example 4: max('hello', 0); // * returns 4: 'hello' // * example 5: max(-1, 'hello'); // * returns 5: 'hello' // * example 6: max([2, 4, 8], [2, 5, 7]); // * returns 6: [2, 5, 7] var ar, retVal, i = 0, n = 0, argv = arguments, argc = argv.length, _obj2Array = function (obj) { if (Object.prototype.toString.call(obj) === '[object Array]') { return obj; } else { var ar = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { ar.push(obj[i]); } } return ar; } }, //function _obj2Array _compare = function (current, next) { var i = 0, n = 0, tmp = 0, nl = 0, cl = 0; if (current === next) { return 0; } else if (typeof current === 'object') { if (typeof next === 'object') { current = _obj2Array(current); next = _obj2Array(next); cl = current.length; nl = next.length; if (nl > cl) { return 1; } else if (nl < cl) { return -1; } for (i = 0, n = cl; i < n; ++i) { tmp = _compare(current[i], next[i]); if (tmp == 1) { return 1; } else if (tmp == -1) { return -1; } } return 0; } return -1; } else if (typeof next === 'object') { return 1; } else if (isNaN(next) && !isNaN(current)) { if (current == 0) { return 0; } return (current < 0 ? 1 : -1); } else if (isNaN(current) && !isNaN(next)) { if (next == 0) { return 0; } return (next > 0 ? 1 : -1); } if (next == current) { return 0; } return (next > current ? 1 : -1); }; //function _compare if (argc === 0) { throw new Error('At least one value should be passed to max()'); } else if (argc === 1) { if (typeof argv[0] === 'object') { ar = _obj2Array(argv[0]); } else { throw new Error('Wrong parameter count for max()'); } if (ar.length === 0) { throw new Error('Array must contain at least one element for max()'); } } else { ar = argv; } retVal = ar[0]; for (i = 1, n = ar.length; i < n; ++i) { if (_compare(retVal, ar[i]) == 1) { retVal = ar[i]; } } return retVal; }
/* Highcharts JS v5.0.1 (2016-10-26) Highcharts Drilldown module Author: Torstein Honsi License: www.highcharts.com/license */ (function(n){"object"===typeof module&&module.exports?module.exports=n:n(Highcharts)})(function(n){(function(f){function n(b,a,d){var c;a.rgba.length&&b.rgba.length?(b=b.rgba,a=a.rgba,c=1!==a[3]||1!==b[3],b=(c?"rgba(":"rgb(")+Math.round(a[0]+(b[0]-a[0])*(1-d))+","+Math.round(a[1]+(b[1]-a[1])*(1-d))+","+Math.round(a[2]+(b[2]-a[2])*(1-d))+(c?","+(a[3]+(b[3]-a[3])*(1-d)):"")+")"):b=a.input||"none";return b}var B=f.noop,v=f.color,w=f.defaultOptions,l=f.each,p=f.extend,H=f.format,C=f.pick,x=f.wrap,q=f.Chart, t=f.seriesTypes,D=t.pie,r=t.column,E=f.Tick,y=f.fireEvent,F=f.inArray,G=1;l(["fill","stroke"],function(b){f.Fx.prototype[b+"Setter"]=function(){this.elem.attr(b,n(v(this.start),v(this.end),this.pos))}});p(w.lang,{drillUpText:"\u25c1 Back to {series.name}"});w.drilldown={activeAxisLabelStyle:{cursor:"pointer",color:"#003399",fontWeight:"bold",textDecoration:"underline"},activeDataLabelStyle:{cursor:"pointer",color:"#003399",fontWeight:"bold",textDecoration:"underline"},animation:{duration:500},drillUpButton:{position:{align:"right", x:-10,y:10}}};f.SVGRenderer.prototype.Element.prototype.fadeIn=function(b){this.attr({opacity:.1,visibility:"inherit"}).animate({opacity:C(this.newOpacity,1)},b||{duration:250})};q.prototype.addSeriesAsDrilldown=function(b,a){this.addSingleSeriesAsDrilldown(b,a);this.applyDrilldown()};q.prototype.addSingleSeriesAsDrilldown=function(b,a){var d=b.series,c=d.xAxis,e=d.yAxis,h,g=[],k=[],u,m,z;z={color:b.color||d.color};this.drilldownLevels||(this.drilldownLevels=[]);u=d.options._levelNumber||0;(m=this.drilldownLevels[this.drilldownLevels.length- 1])&&m.levelNumber!==u&&(m=void 0);a=p(p({_ddSeriesId:G++},z),a);h=F(b,d.points);l(d.chart.series,function(a){a.xAxis!==c||a.isDrilling||(a.options._ddSeriesId=a.options._ddSeriesId||G++,a.options._colorIndex=a.userOptions._colorIndex,a.options._levelNumber=a.options._levelNumber||u,m?(g=m.levelSeries,k=m.levelSeriesOptions):(g.push(a),k.push(a.options)))});b=p({levelNumber:u,seriesOptions:d.options,levelSeriesOptions:k,levelSeries:g,shapeArgs:b.shapeArgs,bBox:b.graphic?b.graphic.getBBox():{},color:b.isNull? (new f.Color(v)).setOpacity(0).get():v,lowerSeriesOptions:a,pointOptions:d.options.data[h],pointIndex:h,oldExtremes:{xMin:c&&c.userMin,xMax:c&&c.userMax,yMin:e&&e.userMin,yMax:e&&e.userMax}},z);this.drilldownLevels.push(b);a=b.lowerSeries=this.addSeries(a,!1);a.options._levelNumber=u+1;c&&(c.oldPos=c.pos,c.userMin=c.userMax=null,e.userMin=e.userMax=null);d.type===a.type&&(a.animate=a.animateDrilldown||B,a.options.animation=!0)};q.prototype.applyDrilldown=function(){var b=this.drilldownLevels,a;b&& 0<b.length&&(a=b[b.length-1].levelNumber,l(this.drilldownLevels,function(b){b.levelNumber===a&&l(b.levelSeries,function(c){c.options&&c.options._levelNumber===a&&c.remove(!1)})}));this.redraw();this.showDrillUpButton()};q.prototype.getDrilldownBackText=function(){var b=this.drilldownLevels;if(b&&0<b.length)return b=b[b.length-1],b.series=b.seriesOptions,H(this.options.lang.drillUpText,b)};q.prototype.showDrillUpButton=function(){var b=this,a=this.getDrilldownBackText(),d=b.options.drilldown.drillUpButton, c,e;this.drillUpButton?this.drillUpButton.attr({text:a}).align():(e=(c=d.theme)&&c.states,this.drillUpButton=this.renderer.button(a,null,null,function(){b.drillUp()},c,e&&e.hover,e&&e.select).addClass("highcharts-drillup-button").attr({align:d.position.align,zIndex:7}).add().align(d.position,!1,d.relativeTo||"plotBox"))};q.prototype.drillUp=function(){for(var b=this,a=b.drilldownLevels,d=a[a.length-1].levelNumber,c=a.length,e=b.series,h,g,k,f,m=function(a){var c;l(e,function(b){b.options._ddSeriesId=== a._ddSeriesId&&(c=b)});c=c||b.addSeries(a,!1);c.type===k.type&&c.animateDrillupTo&&(c.animate=c.animateDrillupTo);a===g.seriesOptions&&(f=c)};c--;)if(g=a[c],g.levelNumber===d){a.pop();k=g.lowerSeries;if(!k.chart)for(h=e.length;h--;)if(e[h].options.id===g.lowerSeriesOptions.id&&e[h].options._levelNumber===d+1){k=e[h];break}k.xData=[];l(g.levelSeriesOptions,m);y(b,"drillup",{seriesOptions:g.seriesOptions});f.type===k.type&&(f.drilldownLevel=g,f.options.animation=b.options.drilldown.animation,k.animateDrillupFrom&& k.chart&&k.animateDrillupFrom(g));f.options._levelNumber=d;k.remove(!1);f.xAxis&&(h=g.oldExtremes,f.xAxis.setExtremes(h.xMin,h.xMax,!1),f.yAxis.setExtremes(h.yMin,h.yMax,!1))}y(b,"drillupall");this.redraw();0===this.drilldownLevels.length?this.drillUpButton=this.drillUpButton.destroy():this.drillUpButton.attr({text:this.getDrilldownBackText()}).align();this.ddDupes.length=[]};r.prototype.supportsDrilldown=!0;r.prototype.animateDrillupTo=function(b){if(!b){var a=this,d=a.drilldownLevel;l(this.points, function(a){a.graphic&&a.graphic.hide();a.dataLabel&&a.dataLabel.hide();a.connector&&a.connector.hide()});setTimeout(function(){a.points&&l(a.points,function(a,b){b=b===(d&&d.pointIndex)?"show":"fadeIn";var c="show"===b?!0:void 0;if(a.graphic)a.graphic[b](c);if(a.dataLabel)a.dataLabel[b](c);if(a.connector)a.connector[b](c)})},Math.max(this.chart.options.drilldown.animation.duration-50,0));this.animate=B}};r.prototype.animateDrilldown=function(b){var a=this,d=this.chart.drilldownLevels,c,e=this.chart.options.drilldown.animation, h=this.xAxis;b||(l(d,function(b){a.options._ddSeriesId===b.lowerSeriesOptions._ddSeriesId&&(c=b.shapeArgs,c.fill=b.color)}),c.x+=C(h.oldPos,h.pos)-h.pos,l(this.points,function(b){b.shapeArgs.fill=b.color;b.graphic&&b.graphic.attr(c).animate(p(b.shapeArgs,{fill:b.color||a.color}),e);b.dataLabel&&b.dataLabel.fadeIn(e)}),this.animate=null)};r.prototype.animateDrillupFrom=function(b){var a=this.chart.options.drilldown.animation,d=this.group,c=this;l(c.trackerGroups,function(a){if(c[a])c[a].on("mouseover")}); delete this.group;l(this.points,function(c){var e=c.graphic,g=b.shapeArgs,k=function(){e.destroy();d&&(d=d.destroy())};e&&(delete c.graphic,g.fill=b.color,a?e.animate(g,f.merge(a,{complete:k})):(e.attr(g),k()))})};D&&p(D.prototype,{supportsDrilldown:!0,animateDrillupTo:r.prototype.animateDrillupTo,animateDrillupFrom:r.prototype.animateDrillupFrom,animateDrilldown:function(b){var a=this.chart.drilldownLevels[this.chart.drilldownLevels.length-1],d=this.chart.options.drilldown.animation,c=a.shapeArgs, e=c.start,h=(c.end-e)/this.points.length;b||(l(this.points,function(b,k){var g=b.shapeArgs;c.fill=a.color;g.fill=b.color;if(b.graphic)b.graphic.attr(f.merge(c,{start:e+k*h,end:e+(k+1)*h}))[d?"animate":"attr"](g,d)}),this.animate=null)}});f.Point.prototype.doDrilldown=function(b,a,d){var c=this.series.chart,e=c.options.drilldown,f=(e.series||[]).length,g;c.ddDupes||(c.ddDupes=[]);for(;f--&&!g;)e.series[f].id===this.drilldown&&-1===F(this.drilldown,c.ddDupes)&&(g=e.series[f],c.ddDupes.push(this.drilldown)); y(c,"drilldown",{point:this,seriesOptions:g,category:a,originalEvent:d,points:void 0!==a&&this.series.xAxis.getDDPoints(a).slice(0)},function(a){var c=a.point.series&&a.point.series.chart,d=a.seriesOptions;c&&d&&(b?c.addSingleSeriesAsDrilldown(a.point,d):c.addSeriesAsDrilldown(a.point,d))})};f.Axis.prototype.drilldownCategory=function(b,a){var d,c,e=this.getDDPoints(b);for(d in e)(c=e[d])&&c.series&&c.series.visible&&c.doDrilldown&&c.doDrilldown(!0,b,a);this.chart.applyDrilldown()};f.Axis.prototype.getDDPoints= function(b){var a=[];l(this.series,function(d){var c,e=d.xData,f=d.points;for(c=0;c<e.length;c++)if(e[c]===b&&d.options.data[c]&&d.options.data[c].drilldown){a.push(f?f[c]:!0);break}});return a};E.prototype.drillable=function(){var b=this.pos,a=this.label,d=this.axis,c="xAxis"===d.coll&&d.getDDPoints,e=c&&d.getDDPoints(b);c&&(a&&e.length?(a.drillable=!0,a.basicStyles||(a.basicStyles=f.merge(a.styles)),a.addClass("highcharts-drilldown-axis-label").css(d.chart.options.drilldown.activeAxisLabelStyle).on("click", function(a){d.drilldownCategory(b,a)})):a&&a.drillable&&(a.styles={},a.css(a.basicStyles),a.on("click",null),a.removeClass("highcharts-drilldown-axis-label")))};x(E.prototype,"addLabel",function(b){b.call(this);this.drillable()});x(f.Point.prototype,"init",function(b,a,d,c){var e=b.call(this,a,d,c);c=(b=a.xAxis)&&b.ticks[c];e.drilldown&&f.addEvent(e,"click",function(b){a.xAxis&&!1===a.chart.options.drilldown.allowPointDrilldown?a.xAxis.drilldownCategory(e.x,b):e.doDrilldown(void 0,void 0,b)});c&& c.drillable();return e});x(f.Series.prototype,"drawDataLabels",function(b){var a=this.chart.options.drilldown.activeDataLabelStyle,d=this.chart.renderer;b.call(this);l(this.points,function(b){var c={};b.drilldown&&b.dataLabel&&("contrast"===a.color&&(c.color=d.getContrast(b.color||this.color)),b.dataLabel.addClass("highcharts-drilldown-data-label"),b.dataLabel.css(a).css(c))},this)});var A,w=function(b){b.call(this);l(this.points,function(a){a.drilldown&&a.graphic&&(a.graphic.addClass("highcharts-drilldown-point"), a.graphic.css({cursor:"pointer"}))})};for(A in t)t[A].prototype.supportsDrilldown&&x(t[A].prototype,"drawTracker",w)})(n)});
/*! * Waves v0.7.1 * http://fian.my.id/Waves * * Copyright 2014 Alfiana E. Sibuea and other contributors * Released under the MIT license * https://github.com/fians/Waves/blob/master/LICENSE */ ;(function(window, factory) { 'use strict'; // AMD. Register as an anonymous module. Wrap in function so we have access // to root via `this`. if (typeof define === 'function' && define.amd) { define([], function() { return factory.apply(window); }); } // Node. Does not work with strict CommonJS, but only CommonJS-like // environments that support module.exports, like Node. else if (typeof exports === 'object') { module.exports = factory.call(window); } // Browser globals. else { window.Waves = factory.call(window); } })(typeof global === 'object' ? global : this, function() { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); var toString = Object.prototype.toString; var isTouchAvailable = 'ontouchstart' in window; // Find exact position of element function isWindow(obj) { return obj !== null && obj === obj.window; } function getWindow(elem) { return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; } function isObject(value) { var type = typeof value; return type === 'function' || type === 'object' && !!value; } function isDOMNode(obj) { return isObject(obj) && obj.nodeType > 0; } function getWavesElements(nodes) { var stringRepr = toString.call(nodes); if (stringRepr === '[object String]') { return $$(nodes); } else if (isObject(nodes) && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(stringRepr) && nodes.hasOwnProperty('length')) { return nodes; } else if (isDOMNode(nodes)) { return [nodes]; } return []; } function offset(elem) { var docElem, win, box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; docElem = doc.documentElement; if (typeof elem.getBoundingClientRect !== typeof undefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function convertStyle(styleObj) { var style = ''; for (var prop in styleObj) { if (styleObj.hasOwnProperty(prop)) { style += (prop + ':' + styleObj[prop] + ';'); } } return style; } var Effect = { // Effect duration duration: 750, // Effect delay (check for scroll before showing effect) delay: 200, show: function(e, element, velocity) { // Disable right click if (e.button === 2) { return false; } element = element || this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple waves-rippling'; element.appendChild(ripple); // Get click coordinate and element witdh var pos = offset(element); var relativeY = (e.pageY - pos.top); var relativeX = (e.pageX - pos.left); var scale = 'scale(' + ((element.clientWidth / 100) * 3) + ')'; var translate = 'translate(0,0)'; if (velocity) { translate = 'translate(' + (velocity.x) + 'px, ' + (velocity.y) + 'px)'; } // Support for touch devices if ('touches' in e && e.touches.length) { relativeY = (e.touches[0].pageY - pos.top); relativeX = (e.touches[0].pageX - pos.left); } // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-translate', translate); // Set ripple position var rippleStyle = { top: relativeY + 'px', left: relativeX + 'px' }; ripple.classList.add('waves-notransition'); ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.classList.remove('waves-notransition'); // Scale the ripple rippleStyle['-webkit-transform'] = scale + ' ' + translate; rippleStyle['-moz-transform'] = scale + ' ' + translate; rippleStyle['-ms-transform'] = scale + ' ' + translate; rippleStyle['-o-transform'] = scale + ' ' + translate; rippleStyle.transform = scale + ' ' + translate; rippleStyle.opacity = '1'; var duration = e.type === 'mousemove' ? 2500 : Effect.duration; rippleStyle['-webkit-transition-duration'] = duration + 'ms'; rippleStyle['-moz-transition-duration'] = duration + 'ms'; rippleStyle['-o-transition-duration'] = duration + 'ms'; rippleStyle['transition-duration'] = duration + 'ms'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function(e, element) { element = element || this; var ripples = element.getElementsByClassName('waves-rippling'); for (var i = 0, len = ripples.length; i < len; i++) { removeRipple(e, element, ripples[i]); } }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var i = 0, len = elements.length; i < len; i++) { var element = elements[i]; if (element.tagName.toLowerCase() === 'input') { var parent = element.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) { continue; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = element.className + ' waves-input-wrapper'; element.className = 'waves-button-input'; // Put element as child parent.replaceChild(wrapper, element); wrapper.appendChild(element); // Apply element color and background color to wrapper var elementStyle = window.getComputedStyle(element, null); var color = elementStyle.color; var backgroundColor = elementStyle.backgroundColor; wrapper.setAttribute('style', 'color:' + color + ';background:' + backgroundColor); element.setAttribute('style', 'background-color:rgba(0,0,0,0);'); } } } }; /** * Hide the effect and remove the ripple. Must be * a separate function to pass the JSLint... */ function removeRipple(e, el, ripple) { // Check if the ripple still exist if (!ripple) { return; } ripple.classList.remove('waves-rippling'); var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); var translate = ripple.getAttribute('data-translate'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 350 - diff; if (delay < 0) { delay = 0; } if (e.type === 'mousemove') { delay = 150; } // Fade out ripple after delay var duration = e.type === 'mousemove' ? 2500 : Effect.duration; setTimeout(function() { var style = { top: relativeY + 'px', left: relativeX + 'px', opacity: '0', // Duration '-webkit-transition-duration': duration + 'ms', '-moz-transition-duration': duration + 'ms', '-o-transition-duration': duration + 'ms', 'transition-duration': duration + 'ms', '-webkit-transform': scale + ' ' + translate, '-moz-transform': scale + ' ' + translate, '-ms-transform': scale + ' ' + translate, '-o-transform': scale + ' ' + translate, 'transform': scale + ' ' + translate }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch (e) { return false; } }, duration); }, delay); } /** * Disable mousedown event for 500ms during and after touch */ var TouchHandler = { /* uses an integer rather than bool so there's no issues with * needing to clear timeouts if another touch event occurred * within the 500ms. Cannot mouseup between touchstart and * touchend, nor in the 500ms after touchend. */ touches: 0, allowEvent: function(e) { var allow = true; if (/^(mousedown|mousemove)$/.test(e.type) && TouchHandler.touches) { allow = false; } return allow; }, registerEvent: function(e) { var eType = e.type; if (eType === 'touchstart') { TouchHandler.touches += 1; // push } else if (/^(touchend|touchcancel)$/.test(eType)) { setTimeout(function() { if (TouchHandler.touches) { TouchHandler.touches -= 1; // pop after 500ms } }, 500); } } }; /** * Delegated click handler for .waves-effect element. * returns null when .waves-effect element not in "click tree" */ function getWavesEffectElement(e) { if (TouchHandler.allowEvent(e) === false) { return null; } var element = null; var target = e.target || e.srcElement; while (target.parentElement !== null) { if (target.classList.contains('waves-effect') && (!(target instanceof SVGElement))) { element = target; break; } target = target.parentElement; } return element; } /** * Bubble the click and show effect if .waves-effect elem was found */ function showEffect(e) { TouchHandler.registerEvent(e); var element = getWavesEffectElement(e); if (element !== null) { if (e.type === 'touchstart' && Effect.delay) { var hidden = false; var timer = setTimeout(function () { timer = null; Effect.show(e, element); }, Effect.delay); var hideEffect = function(hideEvent) { // if touch hasn't moved, and effect not yet started: start effect now if (timer) { clearTimeout(timer); timer = null; Effect.show(e, element); } if (!hidden) { hidden = true; Effect.hide(hideEvent, element); } }; var touchMove = function(moveEvent) { if (timer) { clearTimeout(timer); timer = null; } hideEffect(moveEvent); }; element.addEventListener('touchmove', touchMove, false); element.addEventListener('touchend', hideEffect, false); element.addEventListener('touchcancel', hideEffect, false); } else { Effect.show(e, element); if (isTouchAvailable) { element.addEventListener('touchend', Effect.hide, false); element.addEventListener('touchcancel', Effect.hide, false); } element.addEventListener('mouseup', Effect.hide, false); element.addEventListener('mouseleave', Effect.hide, false); } } } Waves.init = function(options) { var body = document.body; options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } if ('delay' in options) { Effect.delay = options.delay; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); if (isTouchAvailable) { body.addEventListener('touchstart', showEffect, false); body.addEventListener('touchcancel', TouchHandler.registerEvent, false); body.addEventListener('touchend', TouchHandler.registerEvent, false); } body.addEventListener('mousedown', showEffect, false); }; /** * Attach Waves to dynamically loaded inputs, or add .waves-effect and other * waves classes to a set of elements. Set drag to true if the ripple mouseover * or skimming effect should be applied to the elements. */ Waves.attach = function(elements, classes) { elements = getWavesElements(elements); if (toString.call(classes) === '[object Array]') { classes = classes.join(' '); } classes = classes ? ' ' + classes : ''; var element; for (var i = 0, len = elements.length; i < len; i++) { element = elements[i]; if (element.tagName.toLowerCase() === 'input') { Effect.wrapInput([element]); element = element.parentElement; } element.className += ' waves-effect' + classes; } }; /** * Cause a ripple to appear in an element via code. */ Waves.ripple = function(elements, options) { elements = getWavesElements(elements); var elementsLen = elements.length; options = options || {}; options.wait = options.wait || 0; options.position = options.position || null; // default = centre of element if (elementsLen) { var element, pos, off, centre = {}, i = 0; var mousedown = { type: 'mousedown', button: 1 }; var hideRipple = function(mouseup, element) { return function() { Effect.hide(mouseup, element); }; }; for (; i < elementsLen; i++) { element = elements[i]; pos = options.position || { x: element.clientWidth / 2, y: element.clientHeight / 2 }; off = offset(element); centre.x = off.left + pos.x; centre.y = off.top + pos.y; mousedown.pageX = centre.x; mousedown.pageY = centre.y; Effect.show(mousedown, element); if (options.wait >= 0 && options.wait !== null) { var mouseup = { type: 'mouseup', button: 1 }; setTimeout(hideRipple(mouseup, element), options.wait); } } } }; /** * Remove all ripples from an element. */ Waves.calm = function(elements) { elements = getWavesElements(elements); var mouseup = { type: 'mouseup', button: 1 }; for (var i = 0, len = elements.length; i < len; i++) { Effect.hide(mouseup, elements[i]); } }; /** * Deprecated API fallback */ Waves.displayEffect = function(options) { console.error('Waves.displayEffect() has been deprecated and will be removed in future version. Please use Waves.init() to initialize Waves effect'); Waves.init(options); }; return Waves; });
/*! * # Semantic UI 2.0.6 - Transition * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.transition = function() { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], moduleArguments = arguments, query = moduleArguments[0], queryArguments = [].slice.call(arguments, 1), methodInvoked = (typeof query === 'string'), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function(index) { var $module = $(this), element = this, // set at run time settings, instance, error, className, metadata, animationEnd, animationName, namespace, moduleNamespace, eventNamespace, module ; module = { initialize: function() { // get full settings settings = module.get.settings.apply(element, moduleArguments); // shorthand className = settings.className; error = settings.error; metadata = settings.metadata; // define namespace eventNamespace = '.' + settings.namespace; moduleNamespace = 'module-' + settings.namespace; instance = $module.data(moduleNamespace) || module; // get vendor specific events animationEnd = module.get.animationEndEvent(); if(methodInvoked) { methodInvoked = module.invoke(query); } // method not invoked, lets run an animation if(methodInvoked === false) { module.verbose('Converted arguments into settings object', settings); if(settings.interval) { module.delay(settings.animate); } else { module.animate(); } module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing display type on next animation'); delete module.displayType; }, forceRepaint: function() { module.verbose('Forcing element repaint'); var $parentElement = $module.parent(), $nextElement = $module.next() ; if($nextElement.length === 0) { $module.detach().appendTo($parentElement); } else { $module.detach().insertBefore($nextElement); } }, repaint: function() { module.verbose('Repainting element'); var fakeAssignment = element.offsetWidth ; }, delay: function(interval) { var direction = module.get.animationDirection(), shouldReverse, delay ; if(!direction) { direction = module.can.transition() ? module.get.direction() : 'static' ; } interval = (interval !== undefined) ? interval : settings.interval ; shouldReverse = (settings.reverse == 'auto' && direction == className.outward); delay = (shouldReverse || settings.reverse == true) ? ($allModules.length - index) * settings.interval : index * settings.interval ; module.debug('Delaying animation by', delay); setTimeout(module.animate, delay); }, animate: function(overrideSettings) { settings = overrideSettings || settings; if(!module.is.supported()) { module.error(error.support); return false; } module.debug('Preparing animation', settings.animation); if(module.is.animating()) { if(settings.queue) { if(!settings.allowRepeats && module.has.direction() && module.is.occurring() && module.queuing !== true) { module.debug('Animation is currently occurring, preventing queueing same animation', settings.animation); } else { module.queue(settings.animation); } return false; } else if(!settings.allowRepeats && module.is.occurring()) { module.debug('Animation is already occurring, will not execute repeated animation', settings.animation); return false; } else { module.debug('New animation started, completing previous early', settings.animation); instance.complete(); } } if( module.can.animate() ) { module.set.animating(settings.animation); } else { module.error(error.noAnimation, settings.animation, element); } }, reset: function() { module.debug('Resetting animation to beginning conditions'); module.remove.animationCallbacks(); module.restore.conditions(); module.remove.animating(); }, queue: function(animation) { module.debug('Queueing animation of', animation); module.queuing = true; $module .one(animationEnd + '.queue' + eventNamespace, function() { module.queuing = false; module.repaint(); module.animate.apply(this, settings); }) ; }, complete: function (event) { module.debug('Animation complete', settings.animation); module.remove.completeCallback(); module.remove.failSafe(); if(!module.is.looping()) { if( module.is.outward() ) { module.verbose('Animation is outward, hiding element'); module.restore.conditions(); module.hide(); } else if( module.is.inward() ) { module.verbose('Animation is outward, showing element'); module.restore.conditions(); module.show(); } else { module.restore.conditions(); } } }, force: { visible: function() { var style = $module.attr('style'), userStyle = module.get.userStyle(), displayType = module.get.displayType(), overrideStyle = userStyle + 'display: ' + displayType + ' !important;', currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== displayType) { module.verbose('Overriding default display to show element', displayType); $module .attr('style', overrideStyle) ; } else if(emptyStyle) { $module.removeAttr('style'); } }, hidden: function() { var style = $module.attr('style'), currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== 'none' && !module.is.hidden()) { module.verbose('Overriding default display to hide element'); $module .css('display', 'none') ; } else if(emptyStyle) { $module .removeAttr('style') ; } } }, has: { direction: function(animation) { var hasDirection = false ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); $.each(animation, function(index, word){ if(word === className.inward || word === className.outward) { hasDirection = true; } }); } return hasDirection; }, inlineDisplay: function() { var style = $module.attr('style') || '' ; return $.isArray(style.match(/display.*?;/, '')); } }, set: { animating: function(animation) { var animationClass, direction ; // remove previous callbacks module.remove.completeCallback(); // determine exact animation animation = animation || settings.animation; animationClass = module.get.animationClass(animation); // save animation class in cache to restore class names module.save.animation(animationClass); // override display if necessary so animation appears visibly module.force.visible(); module.remove.hidden(); module.remove.direction(); module.start.animation(animationClass); }, duration: function(animationName, duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; if(duration || duration === 0) { module.verbose('Setting animation duration', duration); $module .css({ 'animation-duration': duration }) ; } }, direction: function(direction) { direction = direction || module.get.direction(); if(direction == className.inward) { module.set.inward(); } else { module.set.outward(); } }, looping: function() { module.debug('Transition set to loop'); $module .addClass(className.looping) ; }, hidden: function() { $module .addClass(className.transition) .addClass(className.hidden) ; }, inward: function() { module.debug('Setting direction to inward'); $module .removeClass(className.outward) .addClass(className.inward) ; }, outward: function() { module.debug('Setting direction to outward'); $module .removeClass(className.inward) .addClass(className.outward) ; }, visible: function() { $module .addClass(className.transition) .addClass(className.visible) ; } }, start: { animation: function(animationClass) { animationClass = animationClass || module.get.animationClass(); module.debug('Starting tween', animationClass); $module .addClass(animationClass) .one(animationEnd + '.complete' + eventNamespace, module.complete) ; if(settings.useFailSafe) { module.add.failSafe(); } module.set.duration(settings.duration); settings.onStart.call(this); } }, save: { animation: function(animation) { if(!module.cache) { module.cache = {}; } module.cache.animation = animation; }, displayType: function(displayType) { if(displayType !== 'none') { $module.data(metadata.displayType, displayType); } }, transitionExists: function(animation, exists) { $.fn.transition.exists[animation] = exists; module.verbose('Saving existence of transition', animation, exists); } }, restore: { conditions: function() { var animation = module.get.currentAnimation() ; if(animation) { $module .removeClass(animation) ; module.verbose('Removing animation class', module.cache); } module.remove.duration(); } }, add: { failSafe: function() { var duration = module.get.duration() ; module.timer = setTimeout(function() { $module.triggerHandler(animationEnd); }, duration + settings.failSafeDelay); module.verbose('Adding fail safe timer', module.timer); } }, remove: { animating: function() { $module.removeClass(className.animating); }, animationCallbacks: function() { module.remove.queueCallback(); module.remove.completeCallback(); }, queueCallback: function() { $module.off('.queue' + eventNamespace); }, completeCallback: function() { $module.off('.complete' + eventNamespace); }, display: function() { $module.css('display', ''); }, direction: function() { $module .removeClass(className.inward) .removeClass(className.outward) ; }, duration: function() { $module .css('animation-duration', '') ; }, failSafe: function() { module.verbose('Removing fail safe timer', module.timer); if(module.timer) { clearTimeout(module.timer); } }, hidden: function() { $module.removeClass(className.hidden); }, visible: function() { $module.removeClass(className.visible); }, looping: function() { module.debug('Transitions are no longer looping'); if( module.is.looping() ) { module.reset(); $module .removeClass(className.looping) ; } }, transition: function() { $module .removeClass(className.visible) .removeClass(className.hidden) ; } }, get: { settings: function(animation, duration, onComplete) { // single settings object if(typeof animation == 'object') { return $.extend(true, {}, $.fn.transition.settings, animation); } // all arguments provided else if(typeof onComplete == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : onComplete, duration : duration }); } // only duration provided else if(typeof duration == 'string' || typeof duration == 'number') { return $.extend({}, $.fn.transition.settings, { animation : animation, duration : duration }); } // duration is actually settings object else if(typeof duration == 'object') { return $.extend({}, $.fn.transition.settings, duration, { animation : animation }); } // duration is actually callback else if(typeof duration == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : duration }); } // only animation provided else { return $.extend({}, $.fn.transition.settings, { animation : animation }); } return $.fn.transition.settings; }, animationClass: function(animation) { var animationClass = animation || settings.animation, directionClass = (module.can.transition() && !module.has.direction()) ? module.get.direction() + ' ' : '' ; return className.animating + ' ' + className.transition + ' ' + directionClass + animationClass ; }, currentAnimation: function() { return (module.cache && module.cache.animation !== undefined) ? module.cache.animation : false ; }, currentDirection: function() { return module.is.inward() ? className.inward : className.outward ; }, direction: function() { return module.is.hidden() || !module.is.visible() ? className.inward : className.outward ; }, animationDirection: function(animation) { var direction ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); // search animation name for out/in class $.each(animation, function(index, word){ if(word === className.inward) { direction = className.inward; } else if(word === className.outward) { direction = className.outward; } }); } // return found direction if(direction) { return direction; } return false; }, duration: function(duration) { duration = duration || settings.duration; if(duration === false) { duration = $module.css('animation-duration') || 0; } return (typeof duration === 'string') ? (duration.indexOf('ms') > -1) ? parseFloat(duration) : parseFloat(duration) * 1000 : duration ; }, displayType: function() { if(settings.displayType) { return settings.displayType; } if($module.data(metadata.displayType) === undefined) { // create fake element to determine display state module.can.transition(true); } return $module.data(metadata.displayType); }, userStyle: function(style) { style = style || $module.attr('style') || ''; return style.replace(/display.*?;/, ''); }, transitionExists: function(animation) { return $.fn.transition.exists[animation]; }, animationStartEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationstart', 'OAnimation' :'oAnimationStart', 'MozAnimation' :'mozAnimationStart', 'WebkitAnimation' :'webkitAnimationStart' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; }, animationEndEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationend', 'OAnimation' :'oAnimationEnd', 'MozAnimation' :'mozAnimationEnd', 'WebkitAnimation' :'webkitAnimationEnd' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; } }, can: { transition: function(forced) { var animation = settings.animation, transitionExists = module.get.transitionExists(animation), elementClass, tagName, $clone, currentAnimation, inAnimation, directionExists, displayType ; if( transitionExists === undefined || forced) { module.verbose('Determining whether animation exists'); elementClass = $module.attr('class'); tagName = $module.prop('tagName'); $clone = $('<' + tagName + ' />').addClass( elementClass ).insertAfter($module); currentAnimation = $clone .addClass(animation) .removeClass(className.inward) .removeClass(className.outward) .addClass(className.animating) .addClass(className.transition) .css('animationName') ; inAnimation = $clone .addClass(className.inward) .css('animationName') ; displayType = $clone .attr('class', elementClass) .removeAttr('style') .removeClass(className.hidden) .removeClass(className.visible) .show() .css('display') ; module.verbose('Determining final display state', displayType); module.save.displayType(displayType); $clone.remove(); if(currentAnimation != inAnimation) { module.debug('Direction exists for animation', animation); directionExists = true; } else if(currentAnimation == 'none' || !currentAnimation) { module.debug('No animation defined in css', animation); return; } else { module.debug('Static animation found', animation, displayType); directionExists = false; } module.save.transitionExists(animation, directionExists); } return (transitionExists !== undefined) ? transitionExists : directionExists ; }, animate: function() { // can transition does not return a value if animation does not exist return (module.can.transition() !== undefined); } }, is: { animating: function() { return $module.hasClass(className.animating); }, inward: function() { return $module.hasClass(className.inward); }, outward: function() { return $module.hasClass(className.outward); }, looping: function() { return $module.hasClass(className.looping); }, occurring: function(animation) { animation = animation || settings.animation; animation = '.' + animation.replace(' ', '.'); return ( $module.filter(animation).length > 0 ); }, visible: function() { return $module.is(':visible'); }, hidden: function() { return $module.css('visibility') === 'hidden'; }, supported: function() { return(animationEnd !== false); } }, hide: function() { module.verbose('Hiding element'); if( module.is.animating() ) { module.reset(); } element.blur(); // IE will trigger focus change if element is not blurred before hiding module.remove.display(); module.remove.visible(); module.set.hidden(); module.force.hidden(); settings.onHide.call(this); settings.onComplete.call(this); // module.repaint(); }, show: function(display) { module.verbose('Showing element', display); module.remove.hidden(); module.set.visible(); module.force.visible(); settings.onShow.call(this); settings.onComplete.call(this); // module.repaint(); }, toggle: function() { if( module.is.visible() ) { module.hide(); } else { module.show(); } }, stop: function() { module.debug('Stopping current animation'); $module.triggerHandler(animationEnd); }, stopAll: function() { module.debug('Stopping all animation'); module.remove.queueCallback(); $module.triggerHandler(animationEnd); }, clear: { queue: function() { module.debug('Clearing animation queue'); module.remove.queueCallback(); } }, enable: function() { module.verbose('Starting animation'); $module.removeClass(className.disabled); }, disable: function() { module.debug('Stopping animation'); $module.addClass(className.disabled); }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, // modified for transition to return invoke success invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return (found !== undefined) ? found : false ; } }; module.initialize(); }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // Records if CSS transition is available $.fn.transition.exists = {}; $.fn.transition.settings = { // module info name : 'Transition', // debug content outputted to console debug : false, // verbose debug output verbose : false, // performance data output performance : true, // event namespace namespace : 'transition', // delay between animations in group interval : 0, // whether group animations should be reversed reverse : 'auto', // animation callback event onStart : function() {}, onComplete : function() {}, onShow : function() {}, onHide : function() {}, // whether timeout should be used to ensure callback fires in cases animationend does not useFailSafe : true, // delay in ms for fail safe failSafeDelay : 100, // whether EXACT animation can occur twice in a row allowRepeats : false, // Override final display type on visible displayType : false, // animation duration animation : 'fade', duration : false, // new animations will occur after previous ones queue : true, metadata : { displayType: 'display' }, className : { animating : 'animating', disabled : 'disabled', hidden : 'hidden', inward : 'in', loading : 'loading', looping : 'looping', outward : 'out', transition : 'transition', visible : 'visible' }, // possible errors error: { noAnimation : 'There is no css animation matching the one you specified. Please make sure your css is vendor prefixed, and you have included transition css.', repeated : 'That animation is already occurring, cancelling repeated animation', method : 'The method you called is not defined', support : 'This browser does not support CSS animations' } }; })( jQuery, window , document );
(function ($) { Drupal.behaviors.PanelsAccordionStyle = { attach: function (context, settings) { for ( region_id in Drupal.settings.accordion ) { var accordion = Drupal.settings.accordion[region_id] ; jQuery('#'+region_id).accordion(accordion.options); } } } })(jQuery);
/** * @fileoverview enforce or disallow capitalization of the first letter of a comment * @author Kevin Partington */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const LETTER_PATTERN = require("../util/patterns/letters"); const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const ALWAYS_MESSAGE = "Comments should not begin with a lowercase character", NEVER_MESSAGE = "Comments should not begin with an uppercase character", DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, WHITESPACE = /\s/g, MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/, // TODO: Combine w/ max-len pattern? DEFAULTS = { ignorePattern: null, ignoreInlineComments: false, ignoreConsecutiveComments: false }; /* * Base schema body for defining the basic capitalization rule, ignorePattern, * and ignoreInlineComments values. * This can be used in a few different ways in the actual schema. */ const SCHEMA_BODY = { type: "object", properties: { ignorePattern: { type: "string" }, ignoreInlineComments: { type: "boolean" }, ignoreConsecutiveComments: { type: "boolean" } }, additionalProperties: false }; /** * Get normalized options for either block or line comments from the given * user-provided options. * - If the user-provided options is just a string, returns a normalized * set of options using default values for all other options. * - If the user-provided options is an object, then a normalized option * set is returned. Options specified in overrides will take priority * over options specified in the main options object, which will in * turn take priority over the rule's defaults. * * @param {Object|string} rawOptions The user-provided options. * @param {string} which Either "line" or "block". * @returns {Object} The normalized options. */ function getNormalizedOptions(rawOptions, which) { if (!rawOptions) { return Object.assign({}, DEFAULTS); } return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); } /** * Get normalized options for block and line comments. * * @param {Object|string} rawOptions The user-provided options. * @returns {Object} An object with "Line" and "Block" keys and corresponding * normalized options objects. */ function getAllNormalizedOptions(rawOptions) { return { Line: getNormalizedOptions(rawOptions, "line"), Block: getNormalizedOptions(rawOptions, "block") }; } /** * Creates a regular expression for each ignorePattern defined in the rule * options. * * This is done in order to avoid invoking the RegExp constructor repeatedly. * * @param {Object} normalizedOptions The normalized rule options. * @returns {void} */ function createRegExpForIgnorePatterns(normalizedOptions) { Object.keys(normalizedOptions).forEach(key => { const ignorePatternStr = normalizedOptions[key].ignorePattern; if (ignorePatternStr) { const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); normalizedOptions[key].ignorePatternRegExp = regExp; } }); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "enforce or disallow capitalization of the first letter of a comment", category: "Stylistic Issues", recommended: false }, fixable: "code", schema: [ { enum: ["always", "never"] }, { oneOf: [ SCHEMA_BODY, { type: "object", properties: { line: SCHEMA_BODY, block: SCHEMA_BODY }, additionalProperties: false } ] } ] }, create(context) { const capitalize = context.options[0] || "always", normalizedOptions = getAllNormalizedOptions(context.options[1]), sourceCode = context.getSourceCode(); createRegExpForIgnorePatterns(normalizedOptions); //---------------------------------------------------------------------- // Helpers //---------------------------------------------------------------------- /** * Checks whether a comment is an inline comment. * * For the purpose of this rule, a comment is inline if: * 1. The comment is preceded by a token on the same line; and * 2. The command is followed by a token on the same line. * * Note that the comment itself need not be single-line! * * Also, it follows from this definition that only block comments can * be considered as possibly inline. This is because line comments * would consume any following tokens on the same line as the comment. * * @param {ASTNode} comment The comment node to check. * @returns {boolean} True if the comment is an inline comment, false * otherwise. */ function isInlineComment(comment) { const previousToken = sourceCode.getTokenBefore(comment, { includeComments: true }), nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); return Boolean( previousToken && nextToken && comment.loc.start.line === previousToken.loc.end.line && comment.loc.end.line === nextToken.loc.start.line ); } /** * Determine if a comment follows another comment. * * @param {ASTNode} comment The comment to check. * @returns {boolean} True if the comment follows a valid comment. */ function isConsecutiveComment(comment) { const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true }); return Boolean( previousTokenOrComment && ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 ); } /** * Check a comment to determine if it is valid for this rule. * * @param {ASTNode} comment The comment node to process. * @param {Object} options The options for checking this comment. * @returns {boolean} True if the comment is valid, false otherwise. */ function isCommentValid(comment, options) { // 1. Check for default ignore pattern. if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { return true; } // 2. Check for custom ignore pattern. const commentWithoutAsterisks = comment.value .replace(/\*/g, ""); if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { return true; } // 3. Check for inline comments. if (options.ignoreInlineComments && isInlineComment(comment)) { return true; } // 4. Is this a consecutive comment (and are we tolerating those)? if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { return true; } // 5. Does the comment start with a possible URL? if (MAYBE_URL.test(commentWithoutAsterisks)) { return true; } // 6. Is the initial word character a letter? const commentWordCharsOnly = commentWithoutAsterisks .replace(WHITESPACE, ""); if (commentWordCharsOnly.length === 0) { return true; } const firstWordChar = commentWordCharsOnly[0]; if (!LETTER_PATTERN.test(firstWordChar)) { return true; } // 7. Check the case of the initial word character. const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); if (capitalize === "always" && isLowercase) { return false; } else if (capitalize === "never" && isUppercase) { return false; } return true; } /** * Process a comment to determine if it needs to be reported. * * @param {ASTNode} comment The comment node to process. * @returns {void} */ function processComment(comment) { const options = normalizedOptions[comment.type], commentValid = isCommentValid(comment, options); if (!commentValid) { const message = capitalize === "always" ? ALWAYS_MESSAGE : NEVER_MESSAGE; context.report({ node: null, // Intentionally using loc instead loc: comment.loc, message, fix(fixer) { const match = comment.value.match(LETTER_PATTERN); return fixer.replaceTextRange( // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() ); } }); } } //---------------------------------------------------------------------- // Public //---------------------------------------------------------------------- return { Program() { const comments = sourceCode.getAllComments(); comments.forEach(processComment); } }; } };
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "subaka", "kikii\u0257e" ], "DAY": [ "dewo", "aa\u0253nde", "mawbaare", "njeslaare", "naasaande", "mawnde", "hoore-biir" ], "ERANAMES": [ "Hade Iisa", "Caggal Iisa" ], "ERAS": [ "H-I", "C-I" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "siilo", "colte", "mbooy", "see\u0257to", "duujal", "korse", "morso", "juko", "siilto", "yarkomaa", "jolal", "bowte" ], "SHORTDAY": [ "dew", "aa\u0253", "maw", "nje", "naa", "mwd", "hbi" ], "SHORTMONTH": [ "sii", "col", "mbo", "see", "duu", "kor", "mor", "juk", "slt", "yar", "jol", "bow" ], "STANDALONEMONTH": [ "siilo", "colte", "mbooy", "see\u0257to", "duujal", "korse", "morso", "juko", "siilto", "yarkomaa", "jolal", "bowte" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM, y h:mm:ss a", "mediumDate": "d MMM, y", "mediumTime": "h:mm:ss a", "short": "d/M/y h:mm a", "shortDate": "d/M/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "MRO", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "ff-mr", "localeID": "ff_MR", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/* Highcharts funnel module (c) 2010-2014 Torstein Honsi License: www.highcharts.com/license */ (function(c){var q=c.getOptions(),w=q.plotOptions,r=c.seriesTypes,G=c.merge,F=function(){},C=c.each,x=c.pick;w.funnel=G(w.pie,{animation:!1,center:["50%","50%"],width:"90%",neckWidth:"30%",height:"100%",neckHeight:"25%",reversed:!1,dataLabels:{connectorWidth:1,connectorColor:"#606060"},size:!0,states:{select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}}});r.funnel=c.extendClass(r.pie,{type:"funnel",animate:F,translate:function(){var a=function(b,a){return/%$/.test(b)?a*parseInt(b,10)/100:parseInt(b, 10)},D=0,f=this.chart,d=this.options,c=d.reversed,n=d.ignoreHiddenPoint,g=f.plotWidth,h=f.plotHeight,q=0,f=d.center,i=a(f[0],g),r=a(f[1],h),w=a(d.width,g),k,s,e=a(d.height,h),t=a(d.neckWidth,g),u=a(d.neckHeight,h),y=e-u,a=this.data,z,A,x=d.dataLabels.position==="left"?1:0,B,l,E,p,j,v,m;this.getWidthAt=s=function(b){return b>e-u||e===u?t:t+(w-t)*((e-u-b)/(e-u))};this.getX=function(b,a){return i+(a?-1:1)*(s(c?h-b:b)/2+d.dataLabels.distance)};this.center=[i,r,e];this.centerX=i;C(a,function(b){if(!n|| b.visible!==!1)D+=b.y});C(a,function(b){m=null;A=D?b.y/D:0;l=r-e/2+q*e;j=l+A*e;k=s(l);B=i-k/2;E=B+k;k=s(j);p=i-k/2;v=p+k;l>y?(B=p=i-t/2,E=v=i+t/2):j>y&&(m=j,k=s(y),p=i-k/2,v=p+k,j=y);c&&(l=e-l,j=e-j,m=m?e-m:null);z=["M",B,l,"L",E,l,v,j];m&&z.push(v,m,p,m);z.push(p,j,"Z");b.shapeType="path";b.shapeArgs={d:z};b.percentage=A*100;b.plotX=i;b.plotY=(l+(m||j))/2;b.tooltipPos=[i,b.plotY];b.slice=F;b.half=x;if(!n||b.visible!==!1)q+=A})},drawPoints:function(){var a=this,c=a.options,f=a.chart.renderer;C(a.data, function(d){var o=d.options,n=d.graphic,g=d.shapeArgs;n?n.animate(g):d.graphic=f.path(g).attr({fill:d.color,stroke:x(o.borderColor,c.borderColor),"stroke-width":x(o.borderWidth,c.borderWidth)}).add(a.group)})},sortByAngle:function(a){a.sort(function(a,c){return a.plotY-c.plotY})},drawDataLabels:function(){var a=this.data,c=this.options.dataLabels.distance,f,d,o,n=a.length,g,h;for(this.center[2]-=2*c;n--;)o=a[n],d=(f=o.half)?1:-1,h=o.plotY,g=this.getX(h,f),o.labelPos=[0,h,g+(c-5)*d,h,g+c*d,h,f?"right": "left",0];r.pie.prototype.drawDataLabels.call(this)}});q.plotOptions.pyramid=c.merge(q.plotOptions.funnel,{neckWidth:"0%",neckHeight:"0%",reversed:!0});c.seriesTypes.pyramid=c.extendClass(c.seriesTypes.funnel,{type:"pyramid"})})(Highcharts);
/* AngularJS v1.2.7 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(E,p,F){'use strict';p.module("ngAnimate",["ng"]).config(["$provide","$animateProvider",function(R,L){function f(f){for(var l=0;l<f.length;l++){var h=f[l];if(h.nodeType==W)return h}}var q=p.noop,l=p.forEach,aa=L.$$selectors,W=1,h="$$ngAnimateState",C="ng-animate",k={running:!0};R.decorator("$animate",["$delegate","$injector","$sniffer","$rootElement","$timeout","$rootScope","$document",function(w,E,G,s,M,m,N){function F(a){if(a){var d=[],b={};a=a.substr(1).split(".");(G.transitions||G.animations)&& a.push("");for(var e=0;e<a.length;e++){var g=a[e],f=aa[g];f&&!b[g]&&(d.push(E.get(f)),b[g]=!0)}return d}}function r(a,d,b,e,g,k,m){function p(a){u();if(!0===a)v();else{if(a=b.data(h))a.done=v,b.data(h,a);s(t,"after",v)}}function s(e,f,g){var n=f+"End";l(e,function(l,h){var c=function(){a:{var c=f+"Complete",a=e[h];a[c]=!0;(a[n]||q)();for(a=0;a<e.length;a++)if(!e[a][c])break a;g()}};"before"!=f||"enter"!=a&&"move"!=a?l[f]?l[n]=B?l[f](b,d,c):l[f](b,c):c():c()})}function w(){m&&M(m,0,!1)}function u(){u.hasBeenRun|| (u.hasBeenRun=!0,k())}function v(){if(!v.hasBeenRun){v.hasBeenRun=!0;var a=b.data(h);a&&(B?D(b):(a.closeAnimationTimeout=M(function(){D(b)},0,!1),b.data(h,a)));w()}}var n,z,r=f(b);r&&(n=r.className,z=n+" "+d);if(r&&O(z)){z=(" "+z).replace(/\s+/g,".");e||(e=g?g.parent():b.parent());z=F(z);var B="addClass"==a||"removeClass"==a;g=b.data(h)||{};if(Q(b,e)||0===z.length)u(),v();else{var t=[];B&&(g.disabled||g.running&&g.structural)||l(z,function(e){if(!e.allowCancel||e.allowCancel(b,a,d)){var f=e[a];"leave"== a?(e=f,f=null):e=e["before"+a.charAt(0).toUpperCase()+a.substr(1)];t.push({before:e,after:f})}});0===t.length?(u(),w()):(e=" "+n+" ",g.running&&(M.cancel(g.closeAnimationTimeout),D(b),I(g.animations),g.beforeComplete?(g.done||q)(!0):B&&!g.structural&&(e="removeClass"==g.event?e.replace(g.className,""):e+g.className+" ")),n=" "+d+" ","addClass"==a&&0<=e.indexOf(n)||"removeClass"==a&&-1==e.indexOf(n)?(u(),w()):(b.addClass(C),b.data(h,{running:!0,event:a,className:d,structural:!B,animations:t,done:p}), s(t,"before",p)))}}else u(),v()}function J(a){a=f(a);l(a.querySelectorAll("."+C),function(a){a=p.element(a);var b=a.data(h);b&&(I(b.animations),D(a))})}function I(a){l(a,function(d){a.beforeComplete||(d.beforeEnd||q)(!0);a.afterComplete||(d.afterEnd||q)(!0)})}function D(a){f(a)==f(s)?k.disabled||(k.running=!1,k.structural=!1):(a.removeClass(C),a.removeData(h))}function Q(a,d){if(k.disabled)return!0;if(f(a)==f(s))return k.disabled||k.running;do{if(0===d.length)break;var b=f(d)==f(s),e=b?k:d.data(h), e=e&&(!!e.disabled||!!e.running);if(b||e)return e;if(b)break}while(d=d.parent());return!0}s.data(h,k);m.$$postDigest(function(){m.$$postDigest(function(){k.running=!1})});var K=L.classNameFilter(),O=K?function(a){return K.test(a)}:function(){return!0};return{enter:function(a,d,b,e){this.enabled(!1,a);w.enter(a,d,b);m.$$postDigest(function(){r("enter","ng-enter",a,d,b,q,e)})},leave:function(a,d){J(a);this.enabled(!1,a);m.$$postDigest(function(){r("leave","ng-leave",a,null,null,function(){w.leave(a)}, d)})},move:function(a,d,b,e){J(a);this.enabled(!1,a);w.move(a,d,b);m.$$postDigest(function(){r("move","ng-move",a,d,b,q,e)})},addClass:function(a,d,b){r("addClass",d,a,null,null,function(){w.addClass(a,d)},b)},removeClass:function(a,d,b){r("removeClass",d,a,null,null,function(){w.removeClass(a,d)},b)},enabled:function(a,d){switch(arguments.length){case 2:if(a)D(d);else{var b=d.data(h)||{};b.disabled=!0;d.data(h,b)}break;case 1:k.disabled=!a;break;default:a=!k.disabled}return!!a}}}]);L.register("", ["$window","$sniffer","$timeout",function(h,k,G){function s(c,a){G.cancel(V);T.push(a);var y=f(c);c=p.element(y);U.push(c);y=c.data(n);P=Math.max(P,(y.maxDelay+y.maxDuration)*R*B);y.animationCount=t;V=G(function(){l(T,function(c){c()});var c=[],a=t;l(U,function(a){c.push(a)});G(function(){M(c,a);c=null},P,!1);T=[];U=[];V=null;H={};P=0;t++},10,!1)}function M(c,a){l(c,function(c){(c=c.data(n))&&c.animationCount==a&&(c.closeAnimationFn||q)()})}function m(c,a){var y=a?H[a]:null;if(!y){var b=0,d=0,f=0, g=0,n,k,m,p;l(c,function(c){if(c.nodeType==W){c=h.getComputedStyle(c)||{};m=c[e+X];b=Math.max(N(m),b);p=c[e+S];n=c[e+Z];d=Math.max(N(n),d);k=c[x+Z];g=Math.max(N(k),g);var a=N(c[x+X]);0<a&&(a*=parseInt(c[x+u],10)||1);f=Math.max(a,f)}});y={total:0,transitionPropertyStyle:p,transitionDurationStyle:m,transitionDelayStyle:n,transitionDelay:d,transitionDuration:b,animationDelayStyle:k,animationDelay:g,animationDuration:f};a&&(H[a]=y)}return y}function N(c){var a=0;c=p.isString(c)?c.split(/\s*,\s*/):[]; l(c,function(c){a=Math.max(parseFloat(c)||0,a)});return a}function L(c){var a=c.parent(),b=a.data(v);b||(a.data(v,++Y),b=Y);return b+"-"+f(c).className}function r(c,a){var b=L(c),d=b+" "+a,g={},$=H[d]?++H[d].total:0;if(0<$){var h=a+"-stagger",g=b+" "+h;(b=!H[g])&&c.addClass(h);g=m(c,g);b&&c.removeClass(h)}c.addClass(a);d=m(c,d);h=Math.max(d.transitionDelay,d.animationDelay);b=Math.max(d.transitionDuration,d.animationDuration);if(0===b)return c.removeClass(a),!1;var k="";0<d.transitionDuration?f(c).style[e+ S]="none":f(c).style[x]="none 0s";l(a.split(" "),function(c,a){k+=(0<a?" ":"")+c+"-active"});c.data(n,{className:a,activeClassName:k,maxDuration:b,maxDelay:h,classes:a+" "+k,timings:d,stagger:g,ii:$});return!0}function J(c){var a=e+S;c=f(c);c.style[a]&&0<c.style[a].length&&(c.style[a]="")}function I(c){var a=x;c=f(c);c.style[a]&&0<c.style[a].length&&(c.style[a]="")}function D(c,a,d){function e(b){c.off(u,h);c.removeClass(r);b=c;b.removeClass(a);b.removeData(n);b=f(c);for(var d in q)b.style.removeProperty(q[d])} function h(a){a.stopPropagation();var c=a.originalEvent||a;a=c.$manualTimeStamp||c.timeStamp||Date.now();c=parseFloat(c.elapsedTime.toFixed(z));Math.max(a-w,0)>=v&&c>=s&&d()}var k=c.data(n),l=f(c);if(-1!=l.className.indexOf(a)&&k){var m=k.timings,p=k.stagger,s=k.maxDuration,r=k.activeClassName,v=Math.max(m.transitionDelay,m.animationDelay)*B,w=Date.now(),u=C+" "+g,t=k.ii,A="",q=[];if(0<m.transitionDuration){var x=m.transitionPropertyStyle;-1==x.indexOf("all")&&(A+=b+"transition-property: "+x+";", A+=b+"transition-duration: "+m.transitionDurationStyle+";",q.push(b+"transition-property"),q.push(b+"transition-duration"))}0<t&&(0<p.transitionDelay&&0===p.transitionDuration&&(A+=b+"transition-delay: "+Q(m.transitionDelayStyle,p.transitionDelay,t)+"; ",q.push(b+"transition-delay")),0<p.animationDelay&&0===p.animationDuration&&(A+=b+"animation-delay: "+Q(m.animationDelayStyle,p.animationDelay,t)+"; ",q.push(b+"animation-delay")));0<q.length&&(m=l.getAttribute("style")||"",l.setAttribute("style", m+" "+A));c.on(u,h);c.addClass(r);k.closeAnimationFn=function(){e();d()};return e}d()}function Q(a,b,d){var e="";l(a.split(","),function(a,c){e+=(0<c?",":"")+(d*b+parseInt(a,10))+"s"});return e}function K(a,b){if(r(a,b))return function(d){d&&(a.removeClass(b),a.removeData(n))}}function O(a,b,d){if(a.data(n))return D(a,b,d);a.removeClass(b);a.removeData(n);d()}function a(a,b,d){var e=K(a,b);if(e){var f=e;s(a,function(){J(a);I(a);f=O(a,b,d)});return function(a){(f||q)(a)}}d()}function d(a,b){var d= "";a=p.isArray(a)?a:a.split(/\s+/);l(a,function(a,c){a&&0<a.length&&(d+=(0<c?" ":"")+a+b)});return d}var b="",e,g,x,C;E.ontransitionend===F&&E.onwebkittransitionend!==F?(b="-webkit-",e="WebkitTransition",g="webkitTransitionEnd transitionend"):(e="transition",g="transitionend");E.onanimationend===F&&E.onwebkitanimationend!==F?(b="-webkit-",x="WebkitAnimation",C="webkitAnimationEnd animationend"):(x="animation",C="animationend");var X="Duration",S="Property",Z="Delay",u="IterationCount",v="$$ngAnimateKey", n="$$ngAnimateCSS3Data",z=3,R=1.5,B=1E3,t=0,H={},Y=0,T=[],U=[],V,P=0;return{allowCancel:function(a,b,e){var g=(a.data(n)||{}).classes;if(!g||0<=["enter","leave","move"].indexOf(b))return!0;var k=a.parent(),h=p.element(f(a).cloneNode());h.attr("style","position:absolute; top:-9999px; left:-9999px");h.removeAttr("id");h.empty();l(g.split(" "),function(a){h.removeClass(a)});h.addClass(d(e,"addClass"==b?"-add":"-remove"));k.append(h);a=m(h);h.remove();return 0<Math.max(a.transitionDuration,a.animationDuration)}, enter:function(c,b){return a(c,"ng-enter",b)},leave:function(c,b){return a(c,"ng-leave",b)},move:function(c,b){return a(c,"ng-move",b)},beforeAddClass:function(a,b,e){if(b=K(a,d(b,"-add")))return s(a,function(){J(a);I(a);e()}),b;e()},addClass:function(a,b,e){return O(a,d(b,"-add"),e)},beforeRemoveClass:function(a,b,e){if(b=K(a,d(b,"-remove")))return s(a,function(){J(a);I(a);e()}),b;e()},removeClass:function(a,b,e){return O(a,d(b,"-remove"),e)}}}])}])})(window,window.angular); //# sourceMappingURL=angular-animate.min.js.map
/*! Copyright (C) 2013 by Andrea Giammarchi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function (Object) { 'use strict'; // probably the very first script you want to load in any project // do not redefine same stuff twice anyway if (Object.eddy) return; Object.eddy = true; // all private variables var /*! (C) Andrea Giammarchi Mit Style License */ ArrayPrototype = Array.prototype, ObjectPrototype = Object.prototype, EventPrototype = Event.prototype, hasOwnProperty = ObjectPrototype.hasOwnProperty, push = ArrayPrototype.push, slice = ArrayPrototype.slice, unshift = ArrayPrototype.unshift, // IE < 9 has this problem which makes // eddy.js able to implement its features! // this would not have been possible in other // non ES5 compatible browsers so ... thanks IE! IE_WONT_ENUMERATE_THIS = 'toLocaleString', SECRET = {toLocaleString:1}.propertyIsEnumerable( IE_WONT_ENUMERATE_THIS ) ? '_@eddy' + Math.random() : IE_WONT_ENUMERATE_THIS, IE = SECRET === IE_WONT_ENUMERATE_THIS, // used in all ES5 compatible browsers (all but IE < 9) commonDescriptor = (Object.create || Object)(null), recycledArguments = [], defineProperty = IE ? function (self, property, descriptor) { self[property] = descriptor.value; } : Object.defineProperty, // http://jsperf.com/bind-no-args bind is still freaking slow so... bind = /* Object.bind || */ function (context) { // this is not a fully specd replacemenet for Function#bind // but works specifically for this use case like a charm var fn = this; return function () { return fn.apply(context, arguments); }; }, indexOf = ArrayPrototype.indexOf || function (value) { // if you want more standard indexOf use a proper polyfill // and include it before eddy.js var i = this.length; while (i-- && this[i] !== value) {} return i; }, // every triggered even has a timeStamp now = Date.now || function () { return new Date().getTime(); }, // for ES3+ and JScript native Objects // no hosted objects are considered here // see eddy.dom.js for that eddy = { /** * Returns a bound version of the specified method. * If called again with same method, the initial bound * object will be returned instead of creating a new one. * This will make the following assertion always true: * * @example * obj.boundTo('method') === obj.boundTo('method') * // same as * obj.boundTo(obj.method) === obj.boundTo(obj.method) * // same as * obj.boundTo('method') === obj.boundTo(obj.method) * * Bear in mind no arguments can be bound once, only the context. * Method could be either a function or a string. * In latter case, be aware Google Closure Compiler * might change methods name if compiled with * ADVANCED_OPTION resulting in a broken code. * Use methods instead of strings if you use such option. * @param method string|Function the method name to bind * @return Object the callable bound function/method. */ boundTo: function boundTo(method) { var all = hasOwnProperty.call(this, SECRET) ? this[SECRET] : setAndGet(this), m = all.m, b = all.b, fn = typeof method === 'string' ? this[method] : method, i = indexOf.call(m, fn); return i < 0 ? (b[push.call(m, fn) - 1] = bind.call(fn, this)) : b[i]; }, /** * Borrowed from node.js, it does exactly what node.js does. * * @example * {}.on('evt', function(arg1, arg2, argN){ * console.log(arg1, arg2, argN); * }).emit('evt', 1, 2, 3); * // {'0': 1, '1': 2, '2': 3} * * @param type string the event name to emit * @param [any=any] one or more arguments to pass through * @return boolean true if the event was emitted */ emit: function emit(type) { var has = hasOwnProperty.call(this, SECRET), listeners = has && this[SECRET].l, loop = has && hasOwnProperty.call(listeners, type), array = loop && listeners[type], args = loop && slice.call(arguments, 1), i = 0, length = loop ? array.length : i; while (i < length) { triggerEvent(this, array[i++], args); } return loop; }, /** * Borrowed from node.js, it does exactly what node.js does. * * @example * {}.on('evt', function a(){}).listeners('evt'); * // [ function a(){} ] * * @param type string the optional event name to emit */ listeners: function listeners(type) { return hasOwnProperty.call(this, SECRET) && hasOwnProperty.call(this[SECRET].l, type) && this[SECRET].l[type].slice() || []; }, /** * Counter part of `.on(type, handler)` * The equivalent of `removeListener` or `removeEventListener`. * It removes an event if already added and return same object * * @example * var obj = {}.on('evt', console.boundTo('log')); * obj.emit('evt', 'OK'); // "OK" true * obj * .off('evt', console.boundTo('log')) * .emit('evt') * ; // false * * @param type string the event name to un-listen to * @param handler Function|Object the handler used initially * @return Object the chained object that called `.off()` */ off: function off(type, handler) { var has = hasOwnProperty.call(this, SECRET), listeners = has && this[SECRET].l, array = has && hasOwnProperty.call(listeners, type) && listeners[type], i ; if (array) { i = indexOf.call(array, handler); if (-1 < i) { array.splice(i, 1); if (!array.length) { delete listeners[type]; } } } return this; }, /** * The equivalent of `addListener` or `addEventListener`. * It adds an event if not already added and return same object * * @example * var i = 0; * function genericEvent() { * console.log(++i); * } * var obj = {}; * obj * .on('evt', genericEvent) * .on('evt', genericEvent) * ; * obj.emit('evt'); // 1 * * @param type string the event name to listen to * @param handler Function|Object the handler used initially * @param [optional, **reserved**] boolean unshift instead of push * @return Object the chained object that called `.on()` */ on: function on(type, handler, capture) { var has = hasOwnProperty.call(this, SECRET), listeners = (has ? this[SECRET] : setAndGet(this)).l, array = has && hasOwnProperty.call(listeners, type) ? listeners[type] : listeners[type] = [] ; if (indexOf.call(array, handler) < 0) { (capture ? unshift : push).call(array, handler); } return this; }, /** * Assigns an event that will be dropped the very first time * it will be triggered/emitted/fired. * * @example * var i = 0; * var obj = {}.once('increment', function(){ * console.log(++i); * }); * obj.emit('increment'); // 1 true * obj.emit('increment'); // false * * @param type string the event name to emit * @param handler Function|Object the handler used initially * @param [optional, **reserved**] boolean unshift instead of push * @return Object the chained object that called `.once()` */ once: function once(type, handler, capture) { var // IE8 has duplicated expression/declaration bug // could not self.on(type, function once(){}, ...); cb = function(e) { self.off(type, cb, capture); triggerEvent(self, handler, arguments); }, self = this ; return self.on(type, cb, capture); }, /** * Triggers an event in a *DOMish* way. * The handler will be invoked with a single object * argument as event with at least a method called * `stopImmediatePropagation()` able to break the * method invocation loop. * * The event object will have always at least these properties: * type string the name of the event * timeStamp number when the event has been triggered * currentTarget object the original object that triggered * target object same as DOMish currentTarget * detail [any] optional argument passed through * eventually assigned to the event * * @example * var o = {}.on('evt', function(e){ * console.log(e.type); * console.log(e.detail === RegExp); * }); * o.trigger('evt', RegExp); * // "evt" true * * @param type string the event name to emit * @param [any=any] optional detail data * used as Event.detail property * @return boolean true if the event was triggered */ trigger: function trigger(evt, detail) { var has = hasOwnProperty.call(this, SECRET), listeners = has && this[SECRET].l, isString = typeof evt == 'string', type = isString ? evt : evt.type, loop = has && hasOwnProperty.call(listeners, type), array = loop && listeners[type].slice(0), event = isString ? new Event(this, type, detail) : evt, i = 0, length = loop ? array.length : i, isNotAnEventInstance = !(event instanceof Event); if (isNotAnEventInstance) { event._active = true; event.stopImmediatePropagation = EventPrototype.stopImmediatePropagation; } event.currentTarget = this; recycledArguments[0] = event; while (event._active && i < length) { triggerEvent(this, array[i++], recycledArguments); } if (isNotAnEventInstance) { delete event._active; delete event.stopImmediatePropagation; } return !event.defaultPrevented; } }, ifNotPresent = function(e, key, value) { if (!hasOwnProperty.call(e, key)) { e[key] = value; } }, WTF = false, key; /* eddy.js private helpers/shortcuts */ // the object used to trap listeners and bound functions function createSecret() { return { l: {}, m: [], b: [] }; } function setAndGet(self) { var value = createSecret(); commonDescriptor.value = value; defineProperty(self, SECRET, commonDescriptor); commonDescriptor.value = null; return value; } // check if the handler is a function OR an object // in latter case invoke `handler.handleEvent(args)` // compatible with DOM event handlers function triggerEvent(context, handler, args) { if (typeof handler == 'function') { handler.apply(context, args); } else { handler.handleEvent.apply(handler, args); } } /* the basic eddy.js Event class */ function Event(target, type, detail) { if (detail !== void 0) { ifNotPresent(this, 'detail', detail); } ifNotPresent(this, 'type', type); ifNotPresent(this, 'target', target); ifNotPresent(this, 'timeStamp', now()); } EventPrototype.defaultPrevented = false; EventPrototype._active = EventPrototype.cancelable = true; EventPrototype.preventDefault = function () { this.defaultPrevented = true; }; EventPrototype.stopImmediatePropagation = function () { this._active = false; }; // assign in the least obtrusive way eddy properties for (key in eddy) { if (hasOwnProperty.call(eddy, key)) { defineProperty(ObjectPrototype, key, { enumerable: false, configurable: true, writable: true, value: eddy[key] }); } } (function(forEach){ function fn(key) { function callback(value) { /*jshint validthis:true */ value[key].apply(value, this); } return function () { forEach.call(this, callback, arguments); return this; }; } for(var key in eddy) { if ( eddy.hasOwnProperty(key) && !/^listeners|boundTo$/.test(key) ) { defineProperty( ArrayPrototype, key, { enumerable: false, configurable: true, writable: true, value: fn(key) } ); } } }(ArrayPrototype.forEach)); var dom = { boundTo: eddy.boundTo, data: function data(key, value) { /*jshint eqnull:true */ var hasDataset = 'dataset' in this, void0; if (arguments.length < 2) { return hasDataset ? (key in this.dataset ? this.dataset[key] : void0) : (value = this.getAttribute( 'data-' + key.replace( data.gre || (data.gre = /-[a-z]/g), data.gplace || (data.gplace = function(m, c) { return c.toUpperCase(); }) ) )) == null ? void0 : value ; } if (hasDataset) { if (value == null) { return delete this.dataset[key]; } this.dataset[key] = value; return value; } else { if (!data.sre) { data.sre = /([a-z])([A-Z])/g; data.splace = function(m, l, U) { return l + '-' + U.toLowerCase(); }; } key = 'data-' + key.replace(data.sre, data.splace); if (value == null) { return !this.removeAttribute(key); } return this.setAttribute(key, value), value; } }, emit: function emit(type) { var e = new CustomEvent(type); e.arguments = ArrayPrototype.slice.call(arguments, 1); return this.dispatchEvent(e); }, listeners: function listeners(type) { return []; }, off: function (type, handler, capture) { this.removeEventListener(type, handler, capture); return this; }, on: function (type, handler, capture) { this.addEventListener(type, handler, capture); return this; }, once: eddy.once, trigger: function trigger(evt, detail) { var isString = typeof evt == 'string', type = isString ? evt : evt.type, e = isString ? new CustomEvent( type, ( commonDescriptor.detail = detail, commonDescriptor ) ) : evt ; commonDescriptor.detail = null; Event.call(e, this, type); return this.dispatchEvent(e); } }; commonDescriptor.cancelable = true; commonDescriptor.bubbles = true; // assign properties only if not there already try { document.createEvent('Event').target = document; } catch(Nokia_Xpress) { WTF = true; ifNotPresent = function(e, key, value) { if (!hasOwnProperty.call(e, key)) { try { e[key] = value; } catch(Nokia_Xpress) {} } }; } (function(window){ var Window = window.Window, WindowPrototype = Window ? Window.prototype : window, ElementPrototype = ( window.Node || window.Element || window.HTMLElement ).prototype, DocumentPrototype = ( window.Document || window.HTMLDocument ).prototype, XMLHttpRequestPrototype = ( window.XMLHttpRequest || function(){} ).prototype, key, current ; for (key in dom) { if (hasOwnProperty.call(dom, key)) { current = { enumerable: false, configurable: true, writable: true, value: dom[key] }; defineProperty( WindowPrototype, key, current ); defineProperty( ElementPrototype, key, current ); defineProperty( DocumentPrototype, key, current ); if (key !== 'data') { defineProperty( XMLHttpRequestPrototype, key, current ); } } } }(window)); }(Object));
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { unit: { options: { files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/chai/chai.js', 'angular-css.js', 'test/spec.js' ] }, frameworks: ['mocha'], browsers: [ 'Chrome', 'PhantomJS', 'Firefox' ], singleRun: true } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright (c) <%= grunt.template.today("yyyy") %> DOOR3, Alex Castillo | MIT License */' }, build: { src: '<%= pkg.name %>.js', dest: '<%= pkg.name %>.min.js' } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma']); grunt.registerTask('default', [ 'test', 'uglify' ]); };
/* RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. Available via the MIT or new BSD license. see: http://github.com/jrburke/requirejs for details */ var requirejs,require,define; (function(ba){function J(b){return"[object Function]"===N.call(b)}function K(b){return"[object Array]"===N.call(b)}function z(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function O(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function t(b,c){return ha.call(b,c)}function m(b,c){return t(b,c)&&b[c]}function H(b,c){for(var d in b)if(t(b,d)&&c(b[d],d))break}function S(b,c,d,m){c&&H(c,function(c,l){if(d||!t(b,l))m&&"string"!==typeof c?(b[l]||(b[l]={}),S(b[l], c,d,m)):b[l]=c});return b}function v(b,c){return function(){return c.apply(b,arguments)}}function ca(b){throw b;}function da(b){if(!b)return b;var c=ba;z(b.split("."),function(b){c=c[b]});return c}function B(b,c,d,m){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=m;d&&(c.originalError=d);return c}function ia(b){function c(a,f,C){var e,n,b,c,d,T,k,g=f&&f.split("/");e=g;var l=j.map,h=l&&l["*"];if(a&&"."===a.charAt(0))if(f){e=m(j.pkgs,f)?g=[f]:g.slice(0,g.length- 1);f=a=e.concat(a.split("/"));for(e=0;f[e];e+=1)if(n=f[e],"."===n)f.splice(e,1),e-=1;else if(".."===n)if(1===e&&(".."===f[2]||".."===f[0]))break;else 0<e&&(f.splice(e-1,2),e-=2);e=m(j.pkgs,f=a[0]);a=a.join("/");e&&a===f+"/"+e.main&&(a=f)}else 0===a.indexOf("./")&&(a=a.substring(2));if(C&&l&&(g||h)){f=a.split("/");for(e=f.length;0<e;e-=1){b=f.slice(0,e).join("/");if(g)for(n=g.length;0<n;n-=1)if(C=m(l,g.slice(0,n).join("/")))if(C=m(C,b)){c=C;d=e;break}if(c)break;!T&&(h&&m(h,b))&&(T=m(h,b),k=e)}!c&& T&&(c=T,d=k);c&&(f.splice(0,d,c),a=f.join("/"))}return a}function d(a){A&&z(document.getElementsByTagName("script"),function(f){if(f.getAttribute("data-requiremodule")===a&&f.getAttribute("data-requirecontext")===k.contextName)return f.parentNode.removeChild(f),!0})}function p(a){var f=m(j.paths,a);if(f&&K(f)&&1<f.length)return d(a),f.shift(),k.require.undef(a),k.require([a]),!0}function g(a){var f,b=a?a.indexOf("!"):-1;-1<b&&(f=a.substring(0,b),a=a.substring(b+1,a.length));return[f,a]}function l(a, f,b,e){var n,D,i=null,d=f?f.name:null,l=a,h=!0,j="";a||(h=!1,a="_@r"+(N+=1));a=g(a);i=a[0];a=a[1];i&&(i=c(i,d,e),D=m(r,i));a&&(i?j=D&&D.normalize?D.normalize(a,function(a){return c(a,d,e)}):c(a,d,e):(j=c(a,d,e),a=g(j),i=a[0],j=a[1],b=!0,n=k.nameToUrl(j)));b=i&&!D&&!b?"_unnormalized"+(O+=1):"";return{prefix:i,name:j,parentMap:f,unnormalized:!!b,url:n,originalName:l,isDefine:h,id:(i?i+"!"+j:j)+b}}function s(a){var f=a.id,b=m(q,f);b||(b=q[f]=new k.Module(a));return b}function u(a,f,b){var e=a.id,n=m(q, e);if(t(r,e)&&(!n||n.defineEmitComplete))"defined"===f&&b(r[e]);else if(n=s(a),n.error&&"error"===f)b(n.error);else n.on(f,b)}function w(a,f){var b=a.requireModules,e=!1;if(f)f(a);else if(z(b,function(f){if(f=m(q,f))f.error=a,f.events.error&&(e=!0,f.emit("error",a))}),!e)h.onError(a)}function x(){U.length&&(ja.apply(I,[I.length-1,0].concat(U)),U=[])}function y(a){delete q[a];delete W[a]}function G(a,f,b){var e=a.map.id;a.error?a.emit("error",a.error):(f[e]=!0,z(a.depMaps,function(e,c){var d=e.id, g=m(q,d);g&&(!a.depMatched[c]&&!b[d])&&(m(f,d)?(a.defineDep(c,r[d]),a.check()):G(g,f,b))}),b[e]=!0)}function E(){var a,f,b,e,n=(b=1E3*j.waitSeconds)&&k.startTime+b<(new Date).getTime(),c=[],i=[],g=!1,l=!0;if(!X){X=!0;H(W,function(b){a=b.map;f=a.id;if(b.enabled&&(a.isDefine||i.push(b),!b.error))if(!b.inited&&n)p(f)?g=e=!0:(c.push(f),d(f));else if(!b.inited&&(b.fetched&&a.isDefine)&&(g=!0,!a.prefix))return l=!1});if(n&&c.length)return b=B("timeout","Load timeout for modules: "+c,null,c),b.contextName= k.contextName,w(b);l&&z(i,function(a){G(a,{},{})});if((!n||e)&&g)if((A||ea)&&!Y)Y=setTimeout(function(){Y=0;E()},50);X=!1}}function F(a){t(r,a[0])||s(l(a[0],null,!0)).init(a[1],a[2])}function L(a){var a=a.currentTarget||a.srcElement,b=k.onScriptLoad;a.detachEvent&&!Z?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=k.onScriptError;(!a.detachEvent||Z)&&a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function M(){var a;for(x();I.length;){a= I.shift();if(null===a[0])return w(B("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));F(a)}}var X,$,k,P,Y,j={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{},config:{}},q={},W={},aa={},I=[],r={},V={},N=1,O=1;P={require:function(a){return a.require?a.require:a.require=k.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?a.exports:a.exports=r[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){var b= m(j.pkgs,a.map.id);return(b?m(j.config,a.map.id+"/"+b.main):m(j.config,a.map.id))||{}},exports:r[a.map.id]}}};$=function(a){this.events=m(aa,a.id)||{};this.map=a;this.shim=m(j.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};$.prototype={init:function(a,b,c,e){e=e||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=v(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited= !0;this.ignore=e.ignore;e.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;k.startTime=(new Date).getTime();var a=this.map;if(this.shim)k.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],v(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a= this.map.url;V[a]||(V[a]=!0,k.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var e=this.exports,n=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(J(n)){if(this.events.error&&this.map.isDefine||h.onError!==ca)try{e=k.execCb(c,n,b,e)}catch(d){a=d}else e=k.execCb(c,n,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!== this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else e=n;this.exports=e;if(this.map.isDefine&&!this.ignore&&(r[c]=e,h.onResourceLoad))h.onResourceLoad(k,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete= !0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=l(a.prefix);this.depMaps.push(d);u(d,"defined",v(this,function(e){var n,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,C=k.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=l(a.prefix+"!"+d,this.map.parentMap),u(e,"defined",v(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})), d=m(q,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",v(this,function(a){this.emit("error",a)}));d.enable()}}else n=v(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),n.error=v(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];H(q,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),n.fromText=v(this,function(e,c){var d=a.name,g=l(d),i=Q;c&&(e=c);i&&(Q=!1);s(g);t(j.config,b)&&(j.config[d]=j.config[b]);try{h.exec(e)}catch(D){return w(B("fromtexteval", "fromText eval for "+b+" failed: "+D,D,[b]))}i&&(Q=!0);this.depMaps.push(g);k.completeLoad(d);C([d],n)}),e.load(a.name,C,n,j)}));k.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;z(this.depMaps,v(this,function(a,b){var c,e;if("string"===typeof a){a=l(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(P,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;u(a,"defined",v(this,function(a){this.defineDep(b, a);this.check()}));this.errback&&u(a,"error",v(this,this.errback))}c=a.id;e=q[c];!t(P,c)&&(e&&!e.enabled)&&k.enable(a,this)}));H(this.pluginMaps,v(this,function(a){var b=m(q,a.id);b&&!b.enabled&&k.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){z(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};k={config:j,contextName:b,registry:q,defined:r,urlFetched:V,defQueue:I,Module:$,makeModuleMap:l, nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.pkgs,c=j.shim,e={paths:!0,config:!0,map:!0};H(a,function(a,b){e[b]?"map"===b?(j.map||(j.map={}),S(j[b],a,!0,!0)):S(j[b],a,!0):j[b]=a});a.shim&&(H(a.shim,function(a,b){K(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=k.makeShimExports(a);c[b]=a}),j.shim=c);a.packages&&(z(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name, location:a.location||a.name,main:(a.main||"main").replace(ka,"").replace(fa,"")}}),j.pkgs=b);H(q,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=l(b))});if(a.deps||a.callback)k.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,f){function d(e,c,g){var i,j;f.enableBuildCallback&&(c&&J(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(J(c))return w(B("requireargs", "Invalid require call"),g);if(a&&t(P,e))return P[e](q[a.id]);if(h.get)return h.get(k,e,a,d);i=l(e,a,!1,!0);i=i.id;return!t(r,i)?w(B("notloaded",'Module name "'+i+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[i]}M();k.nextTick(function(){M();j=s(l(null,a));j.skipMap=f.skipMap;j.init(e,c,g,{enabled:!0});E()});return d}f=f||{};S(d,{isBrowser:A,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1<f))d=b.substring(f,b.length),b= b.substring(0,f);return k.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return t(r,l(b,a,!1,!0).id)},specified:function(b){b=l(b,a,!1,!0).id;return t(r,b)||t(q,b)}});a||(d.undef=function(b){x();var c=l(b,a,!0),d=m(q,b);delete r[b];delete V[c.url];delete aa[b];d&&(d.events.defined&&(aa[b]=d.events),y(b))});return d},enable:function(a){m(q,a.id)&&s(a).enable()},completeLoad:function(a){var b,c,e=m(j.shim,a)||{},d=e.exports;for(x();I.length;){c=I.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]=== a&&(b=!0);F(c)}c=m(q,a);if(!b&&!t(r,a)&&c&&!c.inited){if(j.enforceDefine&&(!d||!da(d)))return p(a)?void 0:w(B("nodefine","No define call for "+a,null,[a]));F([a,e.deps||[],e.exportsFn])}E()},nameToUrl:function(a,b,c){var d,g,l,i,k,p;if(h.jsExtRegExp.test(a))i=a+(b||"");else{d=j.paths;g=j.pkgs;i=a.split("/");for(k=i.length;0<k;k-=1)if(p=i.slice(0,k).join("/"),l=m(g,p),p=m(d,p)){K(p)&&(p=p[0]);i.splice(0,k,p);break}else if(l){a=a===l.name?l.location+"/"+l.main:l.location;i.splice(0,k,a);break}i=i.join("/"); i+=b||(/\?/.test(i)||c?"":".js");i=("/"===i.charAt(0)||i.match(/^[\w\+\.\-]+:/)?"":j.baseUrl)+i}return j.urlArgs?i+((-1===i.indexOf("?")?"?":"&")+j.urlArgs):i},load:function(a,b){h.load(k,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||la.test((a.currentTarget||a.srcElement).readyState))R=null,a=L(a),k.completeLoad(a.id)},onScriptError:function(a){var b=L(a);if(!p(b.id))return w(B("scripterror","Script error for: "+b.id,a,[b.id]))}};k.require=k.makeRequire(); return k}var h,x,y,E,L,F,R,M,s,ga,ma=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,na=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,fa=/\.js$/,ka=/^\.\//;x=Object.prototype;var N=x.toString,ha=x.hasOwnProperty,ja=Array.prototype.splice,A=!!("undefined"!==typeof window&&navigator&&window.document),ea=!A&&"undefined"!==typeof importScripts,la=A&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,Z="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),G={},u={},U=[],Q= !1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(J(requirejs))return;u=requirejs;requirejs=void 0}"undefined"!==typeof require&&!J(require)&&(u=require,require=void 0);h=requirejs=function(b,c,d,p){var g,l="_";!K(b)&&"string"!==typeof b&&(g=b,K(c)?(b=c,c=d,d=p):b=[]);g&&g.context&&(l=g.context);(p=m(G,l))||(p=G[l]=h.s.newContext(l));g&&p.configure(g);return p.require(b,c,d)};h.config=function(b){return h(b)};h.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b, 4)}:function(b){b()};require||(require=h);h.version="2.1.6";h.jsExtRegExp=/^\/|:|\?|\.js$/;h.isBrowser=A;x=h.s={contexts:G,newContext:ia};h({});z(["toUrl","undef","defined","specified"],function(b){h[b]=function(){var c=G._;return c.require[b].apply(c,arguments)}});if(A&&(y=x.head=document.getElementsByTagName("head")[0],E=document.getElementsByTagName("base")[0]))y=x.head=E.parentNode;h.onError=ca;h.load=function(b,c,d){var h=b&&b.config||{},g;if(A)return g=h.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml", "html:script"):document.createElement("script"),g.type=h.scriptType||"text/javascript",g.charset="utf-8",g.async=!0,g.setAttribute("data-requirecontext",b.contextName),g.setAttribute("data-requiremodule",c),g.attachEvent&&!(g.attachEvent.toString&&0>g.attachEvent.toString().indexOf("[native code"))&&!Z?(Q=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,M=g,E?y.insertBefore(g,E):y.appendChild(g), M=null,g;if(ea)try{importScripts(d),b.completeLoad(c)}catch(l){b.onError(B("importscripts","importScripts failed for "+c+" at "+d,l,[c]))}};A&&O(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(L=b.getAttribute("data-main"))return s=L,u.baseUrl||(F=s.split("/"),s=F.pop(),ga=F.length?F.join("/")+"/":"./",u.baseUrl=ga),s=s.replace(fa,""),h.jsExtRegExp.test(s)&&(s=L),u.deps=u.deps?u.deps.concat(s):[s],!0});define=function(b,c,d){var h,g;"string"!==typeof b&&(d=c,c=b,b=null); K(c)||(d=c,c=null);!c&&J(d)&&(c=[],d.length&&(d.toString().replace(ma,"").replace(na,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(Q){if(!(h=M))R&&"interactive"===R.readyState||O(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return R=b}),h=R;h&&(b||(b=h.getAttribute("data-requiremodule")),g=G[h.getAttribute("data-requirecontext")])}(g?g.defQueue:U).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)}; h(u)}})(this);
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/_base/config",["../has","require"],function(_1,_2){ var _3={}; if(1){ var _4=_2.rawConfig,p; for(p in _4){ _3[p]=_4[p]; } }else{ var _5=function(_6,_7,_8){ for(p in _6){ p!="has"&&_1.add(_7+p,_6[p],0,_8); } }; var _9=(function(){ return this; })(); _3=1?_2.rawConfig:_9.dojoConfig||_9.djConfig||{}; _5(_3,"config",1); _5(_3.has,"",1); } if(!_3.locale&&typeof navigator!="undefined"){ _3.locale=(navigator.language||navigator.userLanguage).toLowerCase(); } return _3; });
(function ( $ ) { /** * Holds google map object and related utility entities. * @constructor */ function GMapContext(domElement, options) { var _map = new google.maps.Map(domElement, options); var _marker = new google.maps.Marker({ position: new google.maps.LatLng(54.19335, -3.92695), map: _map, title: "Drag Me", draggable: true }); return { map: _map, marker: _marker, circle: null, location: _marker.position, radius: options.radius, locationName: options.locationName, settings: options.settings, domContainer: domElement, geodecoder: new google.maps.Geocoder() } } // Utility functions for Google Map Manipulations var GmUtility = { /** * Draw a circle over the the map. Returns circle object. * Also writes new circle object in gmapContext. * * @param center - LatLng of the center of the circle * @param radius - radius in meters * @param gmapContext - context * @param options */ drawCircle: function(gmapContext, center, radius, options) { if (gmapContext.circle != null) { gmapContext.circle.setMap(null); } if (radius > 0) { radius *= 1; options = $.extend({ strokeColor: "#0000FF", strokeOpacity: 0.35, strokeWeight: 2, fillColor: "#0000FF", fillOpacity: 0.20 }, options); options.map = gmapContext.map; options.radius = radius; options.center = center; gmapContext.circle = new google.maps.Circle(options); return gmapContext.circle; } return null; }, /** * * @param gMapContext * @param location * @param callback */ setPosition: function(gMapContext, location, callback) { gMapContext.location = location; gMapContext.marker.setPosition(location); gMapContext.map.panTo(location); this.drawCircle(gMapContext, location, gMapContext.radius, {}); if (gMapContext.settings.enableReverseGeocode) { gMapContext.geodecoder.geocode({latLng: gMapContext.location}, function(results, status){ if (status == google.maps.GeocoderStatus.OK && results.length > 0){ gMapContext.locationName = results[0].formatted_address; } if (callback) { callback.call(this, gMapContext); } }); } else { if (callback) { callback.call(this, gmapContext); } } }, locationFromLatLng: function(lnlg) { return {latitude: lnlg.lat(), longitude: lnlg.lng()} } } function isPluginApplied(domObj) { return getContextForElement(domObj) != undefined; } function getContextForElement(domObj) { return $(domObj).data("locationpicker"); } function updateInputValues(inputBinding, gmapContext){ if (!inputBinding) return; var currentLocation = GmUtility.locationFromLatLng(gmapContext.location); if (inputBinding.latitudeInput) { inputBinding.latitudeInput.val(currentLocation.latitude); } if (inputBinding.longitudeInput) { inputBinding.longitudeInput.val(currentLocation.longitude); } if (inputBinding.radiusInput) { inputBinding.radiusInput.val(gmapContext.radius); } if (inputBinding.locationNameInput) { inputBinding.locationNameInput.val(gmapContext.locationName); } } function setupInputListenersInput(inputBinding, gmapContext) { if (inputBinding) { if (inputBinding.radiusInput){ inputBinding.radiusInput.on("change", function() { gmapContext.radius = $(this).val(); GmUtility.setPosition(gmapContext, gmapContext.location); }); } if (inputBinding.locationNameInput && gmapContext.settings.enableAutocomplete) { gmapContext.autocomplete = new google.maps.places.Autocomplete(inputBinding.locationNameInput.get(0)); google.maps.event.addListener(gmapContext.autocomplete, 'place_changed', function() { var place = gmapContext.autocomplete.getPlace(); if (!place.geometry) { gmapContext.onlocationnotfound(); return; } GmUtility.setPosition(gmapContext, place.geometry.location, function() { updateInputValues(inputBinding, gmapContext); }); }); } } } /** * Initialization: * $("#myMap").locationpicker(options); * @param options * @param params * @returns {*} */ $.fn.locationpicker = function( options, params ) { if (typeof options == 'string') { // Command provided var _targetDomElement = this.get(0); // Plug-in is not applied - nothing to do. if (!isPluginApplied(_targetDomElement)) return; var gmapContext = getContextForElement(_targetDomElement); switch (options) { case "location": if (params == undefined) { // Getter var location = GmUtility.locationFromLatLng(gmapContext.location); location.radius = gmapContext.radius; location.name = gmapContext.locationName; return location; } else { // Setter if (params.radius) { gmapContext.radius = params.radius; } GmUtility.setPosition(gmapContext, new google.maps.LatLng(params.latitude, params.longitude), function(gmapContext) { updateInputValues(gmapContext.settings.inputBinding, gmapContext); }); } break; case "subscribe": /** * Provides interface for subscribing for GoogleMap events. * See Google API documentation for details. * Parameters: * - event: string, name of the event * - callback: function, callback function to be invoked */ if (options == undefined) { // Getter is not available return null; } else { var event = params.event; var callback = params.callback; if (!event || ! callback) { console.error("LocationPicker: Invalid arguments for method \"subscribe\"") return null; } google.maps.event.addListener(gmapContext.map, event, callback); } break; } return null; } return this.each(function() { var $target = $(this); // If plug-in hasn't been applied before - initialize, otherwise - skip if (isPluginApplied(this)) return; // Plug-in initialization is required // Defaults var settings = $.extend({}, $.fn.locationpicker.defaults, options ); // Initialize var gmapContext = new GMapContext(this, { zoom: settings.zoom, center: new google.maps.LatLng(settings.location.latitude, settings.location.longitude), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, disableDoubleClickZoom: false, scrollwheel: settings.scrollwheel, streetViewControl: false, radius: settings.radius, locationName: settings.locationName, settings: settings }); $target.data("locationpicker", gmapContext); // Subscribe GMap events google.maps.event.addListener(gmapContext.marker, "dragend", function(event) { GmUtility.setPosition(gmapContext, gmapContext.marker.position, function(context){ var currentLocation = GmUtility.locationFromLatLng(gmapContext.location); context.settings.onchanged(currentLocation, context.radius, true); updateInputValues(gmapContext.settings.inputBinding, gmapContext); }); }); GmUtility.setPosition(gmapContext, new google.maps.LatLng(settings.location.latitude, settings.location.longitude), function(context){ updateInputValues(settings.inputBinding, gmapContext); context.settings.oninitialized($target); }); // Set up input bindings if needed setupInputListenersInput(settings.inputBinding, gmapContext); }); }; $.fn.locationpicker.defaults = { location: {latitude: 40.7324319, longitude: -73.82480799999996}, locationName: "", radius: 500, zoom: 15, scrollwheel: true, inputBinding: { latitudeInput: null, longitudeInput: null, radiusInput: null, locationNameInput: null }, enableAutocomplete: false, enableReverseGeocode: true, onchanged: function(currentLocation, radius, isMarkerDropped) {}, onlocationnotfound: function(locationName) {}, oninitialized: function (component) {} } }( jQuery ));
!function(t){"use strict";t.fn.select2.locales.he={formatNoMatches:function(){return"לא נמצאו התאמות"},formatInputTooShort:function(t,n){var e=n-t.length;return"נא להזין עוד "+e+" תווים נוספים"},formatInputTooLong:function(t,n){var e=t.length-n;return"נא להזין פחות "+e+" תווים"},formatSelectionTooBig:function(t){return"ניתן לבחור "+t+" פריטים"},formatLoadMore:function(){return"טוען תוצאות נוספות…"},formatSearching:function(){return"מחפש…"}},t.extend(t.fn.select2.defaults,t.fn.select2.locales.he)}(jQuery);
// ==UserScript== // @id iitc-plugin-bing-maps // @name IITC plugin: Bing maps // @category 地圖 // @version 0.1.3.20170210.164403 // @namespace https://github.com/jonatkins/ingress-intel-total-conversion // @updateURL https://raw.githubusercontent.com/ifchen0/IITC_TW/master/build/Release/plugins/basemap-bing.meta.js // @downloadURL https://raw.githubusercontent.com/ifchen0/IITC_TW/master/build/Release/plugins/basemap-bing.user.js // @description [Release-2017-02-10-164403] Add the maps.bing.com map layers. // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript==
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var request = require('superagent'); var fs = require('fs'); var parse = require('csv-parse'); var stringify = require('csv-stringify'); var transform = require('stream-transform'); var util = require('util'); var xml2js = require('xml2js'); var output = []; var parser = parse({'columns':true}); var input = fs.createReadStream('./input/uuid.csv'); var output = fs.createWriteStream('./output/uuid.csv'); var stringifier = stringify({ header: true }); //var v1APIBase = 'https://beta.deltamktgresearch.com/api/cdr?uuid='; var v1APIBase = 'https://voicereach365.com/api/cdr?uuid='; var fileLocation = { prefix: '/usr/local/share/freeswitch/logs/xml_cdr/', postfix: '.cdr.xml' }; function writeLog(logs, isError){ logs.push(''); logs.push('--------------------------------------------------'); logs.push(''); if(isError){ console.error(logs.join('\n')); return; } console.log(logs.join('\n')); } var transformer = transform(function(record, callback){ var log = []; log.push('Processing : ' + record.uuid); var location = fileLocation.prefix + record.uuid + fileLocation.postfix; record.status = ''; record.exception = ''; record.statusCode = ''; record.responseTxt = ''; log.push('reading file : ' + location); fs.readFile(location, 'utf-8', function(err, xml) { if (err) { record.status = 'file-read-error'; record.exception = util.inspect(err, {depth: 4}); callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, true); return; } var xmlParser = new xml2js.Parser(); xmlParser.parseString(xml, function (err, result) { if (err) { record.status = 'xml-file-parse-error'; record.exception = util.inspect(err, {depth: 4}); callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, true); return; } if(result.cdr){ if(result.cdr.variables && result.cdr.variables.length){ if(!result.cdr.variables[0].ls_con_ref && !result.cdr.variables[0].sip_h_pro_username){ log.push('finding producer UUID'); var producerUUID = result.cdr.variables[0].originator[0]; log.push('found producerUUID: ' + producerUUID); location = fileLocation.prefix + producerUUID + fileLocation.postfix; fs.readFile(location, 'utf-8', function(err, producerXml) { if (err) { record.status = 'file-read-error'; record.exception = util.inspect(err, {depth: 4}); callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, true); return; } log.push('reading complete, sending file to V1 api @ ' + v1APIBase + producerUUID); writeLog(log); request .post(v1APIBase + producerUUID) .type('form') .send({ cdr: producerXml }) .end(function(err, response) { if (err) { record.status = 'post-request-error'; record.exception = util.inspect(err, {depth: 4}); callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, true); return; } log.push('server response received: ' + record.uuid); record.status = 'success'; record.statusCode = response.statusCode; record.responseTxt = response.text; callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, false); return; }); }); } else { log.push('reading complete, sending file to V1 api @ ' + v1APIBase + record.uuid); writeLog(log); request .post(v1APIBase + record.uuid) .type('form') .send({ cdr: xml }) .end(function(err, response) { if (err) { record.status = 'post-request-error'; record.exception = util.inspect(err, {depth: 4}); callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, true); return; } log.push('server response received: ' + record.uuid); record.status = 'success'; record.statusCode = response.statusCode; record.responseTxt = response.text; callback(null, record); log.push(util.inspect(record, {depth: 4, colors: true})); writeLog(log, false); return; }); } } } }); }); }/*, {parallel: 10}*/); input .pipe(parser) // read and parse the input file as a csv .pipe(transformer) // for each record run the trasformer to send data to server .pipe(stringifier) // change response from trasformer to csv .pipe(output); // write output to file
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. "use strict"; // This file relies on the fact that the following declarations have been made // in runtime.js: // var $Object = global.Object; // Keep reference to original values of some global properties. This // has the added benefit that the code in this file is isolated from // changes to these properties. var $floor = MathFloor; var $abs = MathAbs; // Instance class name can only be set on functions. That is the only // purpose for MathConstructor. function MathConstructor() {} var $Math = new MathConstructor(); // ------------------------------------------------------------------- // ECMA 262 - 15.8.2.1 function MathAbs(x) { if (%_IsSmi(x)) return x >= 0 ? x : -x; x = TO_NUMBER_INLINE(x); if (x === 0) return 0; // To handle -0. return x > 0 ? x : -x; } // ECMA 262 - 15.8.2.2 function MathAcosJS(x) { return %MathAcos(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.3 function MathAsinJS(x) { return %MathAsin(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.4 function MathAtanJS(x) { return %MathAtan(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.5 // The naming of y and x matches the spec, as does the order in which // ToNumber (valueOf) is called. function MathAtan2JS(y, x) { return %MathAtan2(TO_NUMBER_INLINE(y), TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.6 function MathCeil(x) { return -MathFloor(-x); } // ECMA 262 - 15.8.2.8 function MathExp(x) { return %MathExpRT(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.9 function MathFloor(x) { x = TO_NUMBER_INLINE(x); // It's more common to call this with a positive number that's out // of range than negative numbers; check the upper bound first. if (x < 0x80000000 && x > 0) { // Numbers in the range [0, 2^31) can be floored by converting // them to an unsigned 32-bit value using the shift operator. // We avoid doing so for -0, because the result of Math.floor(-0) // has to be -0, which wouldn't be the case with the shift. return TO_UINT32(x); } else { return %MathFloorRT(x); } } // ECMA 262 - 15.8.2.10 function MathLog(x) { return %_MathLogRT(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.11 function MathMax(arg1, arg2) { // length == 2 var length = %_ArgumentsLength(); if (length == 2) { arg1 = TO_NUMBER_INLINE(arg1); arg2 = TO_NUMBER_INLINE(arg2); if (arg2 > arg1) return arg2; if (arg1 > arg2) return arg1; if (arg1 == arg2) { // Make sure -0 is considered less than +0. return (arg1 === 0 && %_IsMinusZero(arg1)) ? arg2 : arg1; } // All comparisons failed, one of the arguments must be NaN. return NAN; } var r = -INFINITY; for (var i = 0; i < length; i++) { var n = %_Arguments(i); if (!IS_NUMBER(n)) n = NonNumberToNumber(n); // Make sure +0 is considered greater than -0. if (NUMBER_IS_NAN(n) || n > r || (r === 0 && n === 0 && %_IsMinusZero(r))) { r = n; } } return r; } // ECMA 262 - 15.8.2.12 function MathMin(arg1, arg2) { // length == 2 var length = %_ArgumentsLength(); if (length == 2) { arg1 = TO_NUMBER_INLINE(arg1); arg2 = TO_NUMBER_INLINE(arg2); if (arg2 > arg1) return arg1; if (arg1 > arg2) return arg2; if (arg1 == arg2) { // Make sure -0 is considered less than +0. return (arg1 === 0 && %_IsMinusZero(arg1)) ? arg1 : arg2; } // All comparisons failed, one of the arguments must be NaN. return NAN; } var r = INFINITY; for (var i = 0; i < length; i++) { var n = %_Arguments(i); if (!IS_NUMBER(n)) n = NonNumberToNumber(n); // Make sure -0 is considered less than +0. if (NUMBER_IS_NAN(n) || n < r || (r === 0 && n === 0 && %_IsMinusZero(n))) { r = n; } } return r; } // ECMA 262 - 15.8.2.13 function MathPow(x, y) { return %_MathPow(TO_NUMBER_INLINE(x), TO_NUMBER_INLINE(y)); } // ECMA 262 - 15.8.2.14 var rngstate; // Initialized to a Uint32Array during genesis. function MathRandom() { var r0 = (MathImul(18273, rngstate[0] & 0xFFFF) + (rngstate[0] >>> 16)) | 0; rngstate[0] = r0; var r1 = (MathImul(36969, rngstate[1] & 0xFFFF) + (rngstate[1] >>> 16)) | 0; rngstate[1] = r1; var x = ((r0 << 16) + (r1 & 0xFFFF)) | 0; // Division by 0x100000000 through multiplication by reciprocal. return (x < 0 ? (x + 0x100000000) : x) * 2.3283064365386962890625e-10; } // ECMA 262 - 15.8.2.15 function MathRound(x) { return %RoundNumber(TO_NUMBER_INLINE(x)); } // ECMA 262 - 15.8.2.17 function MathSqrt(x) { return %_MathSqrtRT(TO_NUMBER_INLINE(x)); } // Non-standard extension. function MathImul(x, y) { return %NumberImul(TO_NUMBER_INLINE(x), TO_NUMBER_INLINE(y)); } // ES6 draft 09-27-13, section 20.2.2.28. function MathSign(x) { x = TO_NUMBER_INLINE(x); if (x > 0) return 1; if (x < 0) return -1; // -0, 0 or NaN. return x; } // ES6 draft 09-27-13, section 20.2.2.34. function MathTrunc(x) { x = TO_NUMBER_INLINE(x); if (x > 0) return MathFloor(x); if (x < 0) return MathCeil(x); // -0, 0 or NaN. return x; } // ES6 draft 09-27-13, section 20.2.2.33. function MathTanh(x) { if (!IS_NUMBER(x)) x = NonNumberToNumber(x); // Idempotent for +/-0. if (x === 0) return x; // Returns +/-1 for +/-Infinity. if (!NUMBER_IS_FINITE(x)) return MathSign(x); var exp1 = MathExp(x); var exp2 = MathExp(-x); return (exp1 - exp2) / (exp1 + exp2); } // ES6 draft 09-27-13, section 20.2.2.5. function MathAsinh(x) { if (!IS_NUMBER(x)) x = NonNumberToNumber(x); // Idempotent for NaN, +/-0 and +/-Infinity. if (x === 0 || !NUMBER_IS_FINITE(x)) return x; if (x > 0) return MathLog(x + MathSqrt(x * x + 1)); // This is to prevent numerical errors caused by large negative x. return -MathLog(-x + MathSqrt(x * x + 1)); } // ES6 draft 09-27-13, section 20.2.2.3. function MathAcosh(x) { if (!IS_NUMBER(x)) x = NonNumberToNumber(x); if (x < 1) return NAN; // Idempotent for NaN and +Infinity. if (!NUMBER_IS_FINITE(x)) return x; return MathLog(x + MathSqrt(x + 1) * MathSqrt(x - 1)); } // ES6 draft 09-27-13, section 20.2.2.7. function MathAtanh(x) { if (!IS_NUMBER(x)) x = NonNumberToNumber(x); // Idempotent for +/-0. if (x === 0) return x; // Returns NaN for NaN and +/- Infinity. if (!NUMBER_IS_FINITE(x)) return NAN; return 0.5 * MathLog((1 + x) / (1 - x)); } // ES6 draft 09-27-13, section 20.2.2.21. function MathLog10(x) { return MathLog(x) * 0.434294481903251828; // log10(x) = log(x)/log(10). } // ES6 draft 09-27-13, section 20.2.2.22. function MathLog2(x) { return MathLog(x) * 1.442695040888963407; // log2(x) = log(x)/log(2). } // ES6 draft 09-27-13, section 20.2.2.17. function MathHypot(x, y) { // Function length is 2. // We may want to introduce fast paths for two arguments and when // normalization to avoid overflow is not necessary. For now, we // simply assume the general case. var length = %_ArgumentsLength(); var args = new InternalArray(length); var max = 0; for (var i = 0; i < length; i++) { var n = %_Arguments(i); if (!IS_NUMBER(n)) n = NonNumberToNumber(n); if (n === INFINITY || n === -INFINITY) return INFINITY; n = MathAbs(n); if (n > max) max = n; args[i] = n; } // Kahan summation to avoid rounding errors. // Normalize the numbers to the largest one to avoid overflow. if (max === 0) max = 1; var sum = 0; var compensation = 0; for (var i = 0; i < length; i++) { var n = args[i] / max; var summand = n * n - compensation; var preliminary = sum + summand; compensation = (preliminary - sum) - summand; sum = preliminary; } return MathSqrt(sum) * max; } // ES6 draft 09-27-13, section 20.2.2.16. function MathFroundJS(x) { return %MathFround(TO_NUMBER_INLINE(x)); } // ES6 draft 07-18-14, section 20.2.2.11 function MathClz32(x) { x = ToUint32(TO_NUMBER_INLINE(x)); if (x == 0) return 32; var result = 0; // Binary search. if ((x & 0xFFFF0000) === 0) { x <<= 16; result += 16; }; if ((x & 0xFF000000) === 0) { x <<= 8; result += 8; }; if ((x & 0xF0000000) === 0) { x <<= 4; result += 4; }; if ((x & 0xC0000000) === 0) { x <<= 2; result += 2; }; if ((x & 0x80000000) === 0) { x <<= 1; result += 1; }; return result; } // ES6 draft 09-27-13, section 20.2.2.9. // Cube root approximation, refer to: http://metamerist.com/cbrt/cbrt.htm // Using initial approximation adapted from Kahan's cbrt and 4 iterations // of Newton's method. function MathCbrt(x) { if (!IS_NUMBER(x)) x = NonNumberToNumber(x); if (x == 0 || !NUMBER_IS_FINITE(x)) return x; return x >= 0 ? CubeRoot(x) : -CubeRoot(-x); } macro NEWTON_ITERATION_CBRT(x, approx) (1.0 / 3.0) * (x / (approx * approx) + 2 * approx); endmacro function CubeRoot(x) { var approx_hi = MathFloor(%_DoubleHi(x) / 3) + 0x2A9F7893; var approx = %_ConstructDouble(approx_hi, 0); approx = NEWTON_ITERATION_CBRT(x, approx); approx = NEWTON_ITERATION_CBRT(x, approx); approx = NEWTON_ITERATION_CBRT(x, approx); return NEWTON_ITERATION_CBRT(x, approx); } // ------------------------------------------------------------------- function SetUpMath() { %CheckIsBootstrapping(); %InternalSetPrototype($Math, $Object.prototype); %AddNamedProperty(global, "Math", $Math, DONT_ENUM); %FunctionSetInstanceClassName(MathConstructor, 'Math'); // Set up math constants. InstallConstants($Math, $Array( // ECMA-262, section 15.8.1.1. "E", 2.7182818284590452354, // ECMA-262, section 15.8.1.2. "LN10", 2.302585092994046, // ECMA-262, section 15.8.1.3. "LN2", 0.6931471805599453, // ECMA-262, section 15.8.1.4. "LOG2E", 1.4426950408889634, "LOG10E", 0.4342944819032518, "PI", 3.1415926535897932, "SQRT1_2", 0.7071067811865476, "SQRT2", 1.4142135623730951 )); // Set up non-enumerable functions of the Math object and // set their names. InstallFunctions($Math, DONT_ENUM, $Array( "random", MathRandom, "abs", MathAbs, "acos", MathAcosJS, "asin", MathAsinJS, "atan", MathAtanJS, "ceil", MathCeil, "cos", MathCos, // implemented by third_party/fdlibm "exp", MathExp, "floor", MathFloor, "log", MathLog, "round", MathRound, "sin", MathSin, // implemented by third_party/fdlibm "sqrt", MathSqrt, "tan", MathTan, // implemented by third_party/fdlibm "atan2", MathAtan2JS, "pow", MathPow, "max", MathMax, "min", MathMin, "imul", MathImul, "sign", MathSign, "trunc", MathTrunc, "sinh", MathSinh, // implemented by third_party/fdlibm "cosh", MathCosh, // implemented by third_party/fdlibm "tanh", MathTanh, "asinh", MathAsinh, "acosh", MathAcosh, "atanh", MathAtanh, "log10", MathLog10, "log2", MathLog2, "hypot", MathHypot, "fround", MathFroundJS, "clz32", MathClz32, "cbrt", MathCbrt, "log1p", MathLog1p, // implemented by third_party/fdlibm "expm1", MathExpm1 // implemented by third_party/fdlibm )); %SetInlineBuiltinFlag(MathCeil); %SetInlineBuiltinFlag(MathRandom); %SetInlineBuiltinFlag(MathSin); %SetInlineBuiltinFlag(MathCos); } SetUpMath();
describe('reglite', function () { it('should not contain any bugs', function () { return true; }); });
'use strict' const merge = require('../merge') const subscriber = require('../subscriber') const iterator = require('../iterator') const set = require('../set') module.exports = function switcher (target, map, prevMap) { const elemprops = target.components.element.properties const properties = target.properties const $switch = { map: target.map, $remove: true } const val = { val: 1, $switch } const path = target.$.slice(0, -1) for (let key in properties) { const keyO = key[0] if (keyO !== '$' && keyO !== '_') { const prop = properties[key] const base = prop.base if (base && base.isElement && elemprops[key] !== prop) { $switch[key] = base.$map(void 0, val) $switch[key].val = 1 } } } map = merge(target.$.slice(0, -1), val, map) subscriber(map, target, 't') return map }
require (['../../js/jquery-1.6.2.min'], function ($) { require({ baseUrl: '../../js/' }, [ "navigation", "add", "edit" ], function( nav, add, edit ) { jQuery ("article").addClass("closed"); jQuery ("article h2").bind ("click", function () { var $parent = jQuery (this).parent(); var id = $parent.toggleClass("closed").attr("data-itemid"); if (!$parent.hasClass('cached')) { jQuery.get('get-item.php?item_id=' + id, function(data) { jQuery('.result').html(data); $parent.removeClass("new") .addClass("cached") .children(".description") .prepend(data); }); } }); jQuery ("#choose-label").bind ("change", function (e) { selected_label = jQuery(this).val(); if (selected_label != "reload") location.href = selected_label == "favorite" ? "index.php?showFavorites=1" : "index.php?label=" + selected_label; else location.href = location.href; }); jQuery ("article a.favorite").bind ("click", function (e) { e.preventDefault(); var $thisButton = jQuery(this); jQuery.get($thisButton.attr("href"), function(data) { $thisButton.toggleClass("active"); }); }); }); });
#!/usr/bin/env node var spawn = require('child_process').spawn var path = require('path') var node = process.execPath var fs = require('fs') var yaml = require('js-yaml') var queue = [] var running = false for (var i = 2; i < process.argv.length; i++) { generate(process.argv[i], false) generate(process.argv[i], true) } function generate (file, bail) { if (running) { queue.push([file, bail]) return } running = true file = path.resolve(file) var f = file if (f.indexOf(process.cwd()) === 0) { f = './' + file.substr(process.cwd().length + 1) } var outfile = file.replace(/\.js$/, (bail ? '-bail' : '') + '.tap') console.error(outfile) var output = '' var c = spawn(node, [file], { env: { TAP_BAIL: bail ? 1 : 0 } }) c.stdout.on('data', function (d) { output += d }) c.on('close', function () { var timep = '# time=[0-9.]+(ms)?' var timere = new RegExp(timep, 'g') output = output.replace(process.cwd(), '___/.*?/~~~') output = output.split(/\.js:[0-9]+:[0-9]+\b/) .join('.js:___/[0-9]+/~~~:___/[0-9]+/~~~') output = output.replace(timere, '___/' + timep + '/~~~') output = output.split(file).join('___/.*/~~~' + path.basename(file)) output = output.split(f).join('___/.*/~~~' + path.basename(f)) output = output.split(node + ' ___/').join('\0N1\0') output = output.split(path.basename(node) + ' ___/').join('\0N1\0') output = output.split(node).join('\0N2\0') output = output.split(path.basename(node)).join('\0N2\0') output = output.split('\0N1\0').join('___/.*(node|iojs)(\.exe)?') output = output.split('\0N2\0').join('___/.*(node|iojs)(\.exe)?/~~~') output = yamlishToJson(output) fs.writeFileSync(outfile, output) running = false if (queue.length) { var q = queue.shift() generate(q[0], q[1]) } }) } function deStackify (data) { return Object.keys(data).sort().reduce(function (res, k) { if (k === 'stack' && typeof data[k] === 'string') { return res } else if (k === 'time' && typeof data[k] === 'number') { return res } else if (typeof data[k] === 'object' && data[k]) { res[k] = deStackify(data[k]) } else { res[k] = data[k] } return res }, Array.isArray(data) ? [] : {}) } function yamlishToJson (output) { var lines = output.split(/\n/) var ret = '' var inyaml = false var y = '' var startlen = 0 for (var i = 0; i < lines.length; i++) { var line = lines[i] if (inyaml) { if (line.match(/^\s+\.\.\.$/) && line.length === startlen) { var data = yaml.safeLoad(y) data = deStackify(data) data = JSON.stringify(data) ret += new Array(startlen - 2).join(' ') + data + '\n' + line + '\n' inyaml = false y = '' } else { y += line + '\n' } } else if (line.match(/^\s*---$/)) { startlen = line.length inyaml = true y = '' ret += line + '\n' } else { ret += line + '\n' } } if (inyaml) { throw new Error('neverending yaml\n' + y) } return ret }
var cwd = process.cwd(); var index = require(cwd); var _expect = require("chai").expect; var testName = TEST_NAME; describe("TEST_NAME with .test.js extension", function() { it("should return name without extension", function() { _expect(testName).to.equal("test_name"); }); });
var painless = require('../../assertion/painless') var test = painless.createGroup('Test number/isInteger') var t = painless.assert var isInteger = require('../../../src/number/isInteger') test('should be true if numbers are integers', function () { t.true(isInteger(0)) t.true(isInteger(-0)) t.true(isInteger(1)) t.true(isInteger(5034)) t.true(isInteger(-5034)) t.true(isInteger(9007199254740991)) t.true(isInteger(-9007199254740991)) t.true(isInteger(1.0)) }) test('should be false if numbers are not integers', function () { t.false(isInteger(1.1)) t.false(isInteger(NaN)) t.false(isInteger(Infinity)) t.false(isInteger(-Infinity)) t.false(isInteger(null)) t.false(isInteger(undefined)) })
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var _ = require('underscore'), Backbone = require('backbone'); Backbone.ReactModel = Backbone.Model.extend({ property: function(name, component) { var _this = this, components = {}; this.properties = this.properties || {}; if(typeof name === 'object') components = name; else if(component === void 0) return this.properties[name]; else components[name] = component; _.each(components, function(component, name) { _this[name] = _this.properties[name] = component; // parent <- child var handler = _.bind(vent, _this); _this.listenTo(component, 'add change destroy remove reset', handler); _this.toReactProps(name); // parent -> child var listener = _.bind(pass, _this); _this.on('change:'+name, listener); listener(); function vent(model, collectionOrValue, options) { this.trigger("change:_"+name, this, this.toReactProps(name), options); this.trigger("change", this, options); } function pass(model, value) { if(value === void 0) value = this.get(name); if(typeof value === 'object') { component.set(value, {remove: false}); this.toReactProps(name); } this.unset(name); } }); return this; }, helper: function(name, fn) { var _this = this, fns = {}; this.helpers = this.helpers || {}; if(typeof name === 'object') fns = name; else if(fn === void 0) return this.helpers[name]; else fns[name] = fn; _.each(fns, function(fn, name) { if(typeof fn === 'string') fn = _this[name]; _this.helpers[name] = _.bind(fn, _this); }); return this; }, toReactProps: function(name) { var _this = this; this._reactors = this._reactors || {}; if(typeof name === 'string') { component = this.properties[name]; data = this._reactors[name] = _.result(component, 'toReact') || component.toJSON(); return data; } _.each(this.properties, function(component, name) { _this._reactors[name] = _.result(component, 'toReact') || component.toJSON(); }); return this._reactors; }, toReact: function() { return _.extend(this.toJSON(), this._reactors, this.helpers); } }); Backbone.ReactCollection = Backbone.Collection.extend({ toReact: function() { return this.map(function(model) { return _.result(model, 'toReact') || model.toJSON(); }); } }); module.exports = Backbone; },{"backbone":2,"underscore":4}],2:[function(require,module,exports){ // Backbone.js 1.1.2 // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(root, factory) { // Set up Backbone appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'exports'], function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'); factory(root, exports, _); // Finally, as a browser global. } else { root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } }(this, function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.1.2'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true}, options); // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !options.wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model, options); } return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); var i, l, id, model, attrs, existing, sort; var at = options.at; var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { attrs = models[i] || {}; if (attrs instanceof Model) { id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute || 'id']; } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; if (merge) { attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); this._addReference(model, options); } // Do not add multiple models with the same `id`. model = existing || model; if (order && (model.isNew() || !modelMap[model.id])) order.push(model); modelMap[model.id] = true; } // Remove nonexistent models if appropriate. if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) return attrs; options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; if (!model.collection) model.collection = this; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain', 'sample']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); router.execute(callback, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = decodeURI(this.location.pathname + this.location.search); var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">'); this.iframe = frame.hide().appendTo('body')[0].contentWindow; this.navigate(fragment); } // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { Backbone.$(window).on('popstate', this.checkUrl); } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) { Backbone.$(window).on('hashchange', this.checkUrl); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } // Determine if we need to change the base url, for a pushState link // opened by a non-pushState browser. this.fragment = fragment; var loc = this.location; // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + '#' + this.fragment); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && this.atRoot() && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment); } } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl); if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); if (current === this.fragment && this.iframe) { current = this.getFragment(this.getHash(this.iframe)); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { fragment = this.fragment = this.getFragment(fragment); return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; var url = this.root + (fragment = this.getFragment(fragment || '')); // Strip the hash for matching. fragment = fragment.replace(pathStripper, ''); if (this.fragment === fragment) return; this.fragment = fragment; // Don't include a trailing slash on the root. if (fragment === '' && url !== '/') url = url.slice(0, -1); // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) { // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if(!options.replace) this.iframe.document.open().close(); this._updateHash(this.iframe.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); model.trigger('error', model, resp, options); }; }; return Backbone; })); },{"underscore":3}],3:[function(require,module,exports){ // Underscore.js 1.6.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.6.0'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return obj; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } return obj; }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; any(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context); each(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, function(value, index, list) { return !predicate.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context); each(obj, function(value, index, list) { if (!(result = result && predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context); each(obj, function(value, index, list) { if (result || (result = predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } var result = -Infinity, lastComputed = -Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed > lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } var result = Infinity, lastComputed = Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed < lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Shuffle an array, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { if (value == null) return _.identity; if (_.isFunction(value)) return value; return _.property(value); }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, iterator, context) { iterator = lookupIterator(iterator); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iterator, context) { var result = {}; iterator = lookupIterator(iterator); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, key, value) { _.has(result, key) ? result[key].push(value) : result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, key, value) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, key) { _.has(result, key) ? result[key]++ : result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } each(input, function(value) { if (_.isArray(value) || _.isArguments(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Split an array into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(array, predicate) { var pass = [], fail = []; each(array, function(elem) { (predicate(elem) ? pass : fail).push(elem); }); return [pass, fail]; }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.contains(other, item); }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var length = _.max(_.pluck(arguments, 'length').concat(0)); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, '' + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < length; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(length); while(idx < length) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) throw new Error('bindAll must be passed function names'); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = new Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = new Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor)) && ('constructor' in a && 'constructor' in b)) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; _.constant = function(value) { return function () { return value; }; }; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { return function(obj) { if (obj === attrs) return true; //avoid comparing an object to itself. for (var key in attrs) { if (attrs[key] !== obj[key]) return false; } return true; } }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(Math.max(0, n)); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }).call(this); },{}],4:[function(require,module,exports){ module.exports=require(3) },{}]},{},[1]);
exports.up = function(knex) { return knex.schema .createTable('User', function(table) { table.bigincrements('id').primary(); table .string('username') .index() .unique() .notNullable(); table.string('email'); }) .createTable('Pet', function(table) { table.bigincrements('id').primary(); table.string('name'); table .biginteger('userid') .unsigned() .notNullable(); table.foreign('userid').references('User.id'); }) .createTable('Ignoreme', function(table) { table.bigincrements('id').primary(); table.string('description'); }) .then(function() { return knex('Ignoreme').insert({ description: 'wat' }); }); }; exports.down = function(knex) { return knex.schema .dropTable('Pet') .dropTable('User') .dropTable('Ignoreme'); };
export const $_ = predicates => model => { for (let key in predicates) { if (predicates.hasOwnProperty(key)) { if (!predicates[key](model[key])) return false; } } return true; } export const $in = value => arr => Array.contains(arr, value); export const $nin = value => arr => !Array.contains(arr, value); export const $ne = value => key => key !== value; export const $eq = value => key => key === value; export const $lt = value => key => key < value; export const $lte = value => key => key <= value; export const $gt = value => key => key > value; export const $gte = value => key => key >= value; export const $mod = (divisor, remainder) => v => v % divisor === (remainder || 0);
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { exports.cssText = ".ace-dawn .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-dawn .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-dawn .ace_gutter {\ width: 50px;\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-dawn .ace_gutter-layer {\ width: 100%;\ text-align: right;\ }\ \ .ace-dawn .ace_gutter-layer .ace_gutter-cell {\ padding-right: 6px;\ }\ \ .ace-dawn .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-dawn .ace_scroller {\ background-color: #F9F9F9;\ }\ \ .ace-dawn .ace_text-layer {\ cursor: text;\ color: #080808;\ }\ \ .ace-dawn .ace_cursor {\ border-left: 2px solid #000000;\ }\ \ .ace-dawn .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ \ .ace-dawn .ace_marker-layer .ace_selection {\ background: rgba(39, 95, 255, 0.30);\ }\ \ .ace-dawn .ace_marker-layer .ace_step {\ background: rgb(198, 219, 174);\ }\ \ .ace-dawn .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(75, 75, 126, 0.50);\ }\ \ .ace-dawn .ace_marker-layer .ace_active_line {\ background: rgba(36, 99, 180, 0.12);\ }\ \ \ .ace-dawn .ace_invisible {\ color: rgba(75, 75, 126, 0.50);\ }\ \ .ace-dawn .ace_keyword {\ color:#794938;\ }\ \ .ace-dawn .ace_keyword.ace_operator {\ \ }\ \ .ace-dawn .ace_constant {\ color:#811F24;\ }\ \ .ace-dawn .ace_constant.ace_language {\ \ }\ \ .ace-dawn .ace_constant.ace_library {\ \ }\ \ .ace-dawn .ace_constant.ace_numeric {\ \ }\ \ .ace-dawn .ace_invalid {\ \ }\ \ .ace-dawn .ace_invalid.ace_illegal {\ text-decoration:underline;\ font-style:italic;\ color:#F8F8F8;\ background-color:#B52A1D;\ }\ \ .ace-dawn .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#B52A1D;\ }\ \ .ace-dawn .ace_support {\ color:#691C97;\ }\ \ .ace-dawn .ace_support.ace_function {\ color:#693A17;\ }\ \ .ace-dawn .ace_function.ace_buildin {\ \ }\ \ .ace-dawn .ace_string {\ color:#0B6125;\ }\ \ .ace-dawn .ace_string.ace_regexp {\ color:#CF5628;\ }\ \ .ace-dawn .ace_comment {\ font-style:italic;\ color:#5A525F;\ }\ \ .ace-dawn .ace_comment.ace_doc {\ \ }\ \ .ace-dawn .ace_comment.ace_doc.ace_tag {\ \ }\ \ .ace-dawn .ace_variable {\ color:#234A97;\ }\ \ .ace-dawn .ace_variable.ace_language {\ \ }\ \ .ace-dawn .ace_xml_pe {\ \ }\ \ .ace-dawn .ace_meta {\ \ }\ \ .ace-dawn .ace_meta.ace_tag {\ \ }\ \ .ace-dawn .ace_meta.ace_tag.ace_input {\ \ }\ \ .ace-dawn .ace_entity.ace_other.ace_attribute-name {\ \ }\ \ .ace-dawn .ace_entity.ace_name {\ \ }\ \ .ace-dawn .ace_entity.ace_name.ace_function {\ \ }\ \ .ace-dawn .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-dawn .ace_markup.ace_heading {\ color:#19356D;\ }\ \ .ace-dawn .ace_markup.ace_heading.ace_1 {\ \ }\ \ .ace-dawn .ace_markup.ace_heading.ace_2 {\ \ }\ \ .ace-dawn .ace_markup.ace_heading.ace_3 {\ \ }\ \ .ace-dawn .ace_markup.ace_heading.ace_4 {\ \ }\ \ .ace-dawn .ace_markup.ace_heading.ace_5 {\ \ }\ \ .ace-dawn .ace_markup.ace_heading.ace_6 {\ \ }\ \ .ace-dawn .ace_markup.ace_list {\ color:#693A17;\ }\ \ .ace-dawn .ace_collab.ace_user1 {\ \ }"; exports.cssClass = "ace-dawn"; });
/** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v25.1.0 * @link http://www.ag-grid.com/ * @license MIT */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Autowired, Optional } from "./context/context"; import { RefSelector } from "./widgets/componentAnnotations"; import { Events } from "./events"; import { SideBarDefParser } from "./entities/sideBar"; import { ModuleNames } from "./modules/moduleNames"; import { ModuleRegistry } from "./modules/moduleRegistry"; import { ManagedFocusComponent } from "./widgets/managedFocusComponent"; import { addCssClass, removeCssClass, isVisible } from "./utils/dom"; import { findIndex, last } from "./utils/array"; import { FocusController } from "./focusController"; var GridCore = /** @class */ (function (_super) { __extends(GridCore, _super); function GridCore() { return _super.call(this, undefined, true) || this; } GridCore.prototype.postConstruct = function () { var _this = this; this.logger = this.loggerFactory.create('GridCore'); var template = this.createTemplate(); this.setTemplate(template); // register with services that need grid core [ this.gridApi, this.rowRenderer, this.popupService, this.focusController ].forEach(function (service) { return service.registerGridCore(_this); }); if (ModuleRegistry.isRegistered(ModuleNames.ClipboardModule)) { this.clipboardService.registerGridCore(this); } this.gridOptionsWrapper.addLayoutElement(this.getGui()); this.eGridDiv.appendChild(this.getGui()); this.addDestroyFunc(function () { _this.eGridDiv.removeChild(_this.getGui()); }); // if using angular, watch for quickFilter changes if (this.$scope) { var quickFilterUnregisterFn = this.$scope.$watch(this.quickFilterOnScope, function (newFilter) { return _this.filterManager.setQuickFilter(newFilter); }); this.addDestroyFunc(quickFilterUnregisterFn); } // important to set rtl before doLayout, as setting the RTL class impacts the scroll position, // which doLayout indirectly depends on this.addRtlSupport(); this.logger.log('ready'); this.gridOptionsWrapper.addLayoutElement(this.eRootWrapperBody); var unsubscribeFromResize = this.resizeObserverService.observeResize(this.eGridDiv, this.onGridSizeChanged.bind(this)); this.addDestroyFunc(function () { return unsubscribeFromResize(); }); var eGui = this.getGui(); this.addManagedListener(this, Events.EVENT_KEYBOARD_FOCUS, function () { addCssClass(eGui, FocusController.AG_KEYBOARD_FOCUS); }); this.addManagedListener(this, Events.EVENT_MOUSE_FOCUS, function () { removeCssClass(eGui, FocusController.AG_KEYBOARD_FOCUS); }); _super.prototype.postConstruct.call(this); }; GridCore.prototype.getFocusableElement = function () { return this.eRootWrapperBody; }; GridCore.prototype.createTemplate = function () { var sideBarModuleLoaded = ModuleRegistry.isRegistered(ModuleNames.SideBarModule); var statusBarModuleLoaded = ModuleRegistry.isRegistered(ModuleNames.StatusBarModule); var rowGroupingLoaded = ModuleRegistry.isRegistered(ModuleNames.RowGroupingModule); var enterpriseCoreLoaded = ModuleRegistry.isRegistered(ModuleNames.EnterpriseCoreModule); var dropZones = rowGroupingLoaded ? '<ag-grid-header-drop-zones></ag-grid-header-drop-zones>' : ''; var sideBar = sideBarModuleLoaded ? '<ag-side-bar ref="sideBar"></ag-side-bar>' : ''; var statusBar = statusBarModuleLoaded ? '<ag-status-bar ref="statusBar"></ag-status-bar>' : ''; var watermark = enterpriseCoreLoaded ? '<ag-watermark></ag-watermark>' : ''; var template = /* html */ "<div ref=\"eRootWrapper\" class=\"ag-root-wrapper\">\n " + dropZones + "\n <div class=\"ag-root-wrapper-body\" ref=\"rootWrapperBody\">\n <ag-grid-comp ref=\"gridPanel\"></ag-grid-comp>\n " + sideBar + "\n </div>\n " + statusBar + "\n <ag-pagination></ag-pagination>\n " + watermark + "\n </div>"; return template; }; GridCore.prototype.getFocusableContainers = function () { var focusableContainers = [ this.gridPanel.getGui() ]; if (this.sideBarComp) { focusableContainers.push(this.sideBarComp.getGui()); } return focusableContainers.filter(function (el) { return isVisible(el); }); }; GridCore.prototype.focusNextInnerContainer = function (backwards) { var focusableContainers = this.getFocusableContainers(); var idxWithFocus = findIndex(focusableContainers, function (container) { return container.contains(document.activeElement); }); var nextIdx = idxWithFocus + (backwards ? -1 : 1); if (nextIdx < 0 || nextIdx >= focusableContainers.length) { return false; } if (nextIdx === 0) { return this.focusGridHeader(); } return this.focusController.focusInto(focusableContainers[nextIdx]); }; GridCore.prototype.focusInnerElement = function (fromBottom) { var focusableContainers = this.getFocusableContainers(); if (fromBottom) { if (focusableContainers.length > 1) { return this.focusController.focusInto(last(focusableContainers)); } var lastColumn = last(this.columnController.getAllDisplayedColumns()); if (this.focusController.focusGridView(lastColumn, true)) { return true; } } return this.focusGridHeader(); }; GridCore.prototype.focusGridHeader = function () { var firstColumn = this.columnController.getAllDisplayedColumns()[0]; if (!firstColumn) { return false; } if (firstColumn.getParent()) { firstColumn = this.columnController.getColumnGroupAtLevel(firstColumn, 0); } this.focusController.focusHeaderPosition({ headerRowIndex: 0, column: firstColumn }); return true; }; GridCore.prototype.onGridSizeChanged = function () { var event = { type: Events.EVENT_GRID_SIZE_CHANGED, api: this.gridApi, columnApi: this.columnApi, clientWidth: this.eGridDiv.clientWidth, clientHeight: this.eGridDiv.clientHeight }; this.eventService.dispatchEvent(event); }; GridCore.prototype.addRtlSupport = function () { var cssClass = this.gridOptionsWrapper.isEnableRtl() ? 'ag-rtl' : 'ag-ltr'; addCssClass(this.getGui(), cssClass); }; GridCore.prototype.getRootGui = function () { return this.getGui(); }; GridCore.prototype.isSideBarVisible = function () { if (!this.sideBarComp) { return false; } return this.sideBarComp.isDisplayed(); }; GridCore.prototype.setSideBarVisible = function (show) { if (!this.sideBarComp) { if (show) { console.warn('AG Grid: sideBar is not loaded'); } return; } this.sideBarComp.setDisplayed(show); }; GridCore.prototype.setSideBarPosition = function (position) { if (!this.sideBarComp) { console.warn('AG Grid: sideBar is not loaded'); return; } this.sideBarComp.setSideBarPosition(position); }; GridCore.prototype.closeToolPanel = function () { if (!this.sideBarComp) { console.warn('AG Grid: toolPanel is only available in AG Grid Enterprise'); return; } this.sideBarComp.close(); }; GridCore.prototype.getSideBar = function () { return this.gridOptions.sideBar; }; GridCore.prototype.getToolPanelInstance = function (key) { if (!this.sideBarComp) { console.warn('AG Grid: toolPanel is only available in AG Grid Enterprise'); return; } return this.sideBarComp.getToolPanelInstance(key); }; GridCore.prototype.refreshSideBar = function () { if (this.sideBarComp) { this.sideBarComp.refresh(); } }; GridCore.prototype.setSideBar = function (def) { if (!this.sideBarComp) { return; } this.eRootWrapperBody.removeChild(this.sideBarComp.getGui()); this.gridOptions.sideBar = SideBarDefParser.parse(def); this.sideBarComp.reset(); this.eRootWrapperBody.appendChild(this.sideBarComp.getGui()); }; GridCore.prototype.getOpenedToolPanel = function () { if (!this.sideBarComp) { return null; } return this.sideBarComp.openedItem(); }; GridCore.prototype.openToolPanel = function (key) { if (!this.sideBarComp) { console.warn('AG Grid: toolPanel is only available in AG Grid Enterprise'); return; } this.sideBarComp.openToolPanel(key); }; GridCore.prototype.isToolPanelShowing = function () { return this.sideBarComp.isToolPanelShowing(); }; GridCore.prototype.destroy = function () { this.logger.log('Grid DOM removed'); _super.prototype.destroy.call(this); }; // Valid values for position are bottom, middle and top GridCore.prototype.ensureNodeVisible = function (comparator, position) { if (position === void 0) { position = null; } if (this.doingVirtualPaging) { throw new Error('Cannot use ensureNodeVisible when doing virtual paging, as we cannot check rows that are not in memory'); } // look for the node index we want to display var rowCount = this.rowModel.getRowCount(); var comparatorIsAFunction = typeof comparator === 'function'; var indexToSelect = -1; // go through all the nodes, find the one we want to show for (var i = 0; i < rowCount; i++) { var node = this.rowModel.getRow(i); if (comparatorIsAFunction) { if (comparator(node)) { indexToSelect = i; break; } } else { // check object equality against node and data if (comparator === node || comparator === node.data) { indexToSelect = i; break; } } } if (indexToSelect >= 0) { this.gridPanel.ensureIndexVisible(indexToSelect, position); } }; GridCore.prototype.onTabKeyDown = function () { }; __decorate([ Autowired('gridOptions') ], GridCore.prototype, "gridOptions", void 0); __decorate([ Autowired('rowModel') ], GridCore.prototype, "rowModel", void 0); __decorate([ Autowired('resizeObserverService') ], GridCore.prototype, "resizeObserverService", void 0); __decorate([ Autowired('rowRenderer') ], GridCore.prototype, "rowRenderer", void 0); __decorate([ Autowired('filterManager') ], GridCore.prototype, "filterManager", void 0); __decorate([ Autowired('eGridDiv') ], GridCore.prototype, "eGridDiv", void 0); __decorate([ Autowired('$scope') ], GridCore.prototype, "$scope", void 0); __decorate([ Autowired('quickFilterOnScope') ], GridCore.prototype, "quickFilterOnScope", void 0); __decorate([ Autowired('popupService') ], GridCore.prototype, "popupService", void 0); __decorate([ Autowired('columnController') ], GridCore.prototype, "columnController", void 0); __decorate([ Autowired('loggerFactory') ], GridCore.prototype, "loggerFactory", void 0); __decorate([ Autowired('columnApi') ], GridCore.prototype, "columnApi", void 0); __decorate([ Autowired('gridApi') ], GridCore.prototype, "gridApi", void 0); __decorate([ Optional('clipboardService') ], GridCore.prototype, "clipboardService", void 0); __decorate([ RefSelector('gridPanel') ], GridCore.prototype, "gridPanel", void 0); __decorate([ RefSelector('sideBar') ], GridCore.prototype, "sideBarComp", void 0); __decorate([ RefSelector('rootWrapperBody') ], GridCore.prototype, "eRootWrapperBody", void 0); return GridCore; }(ManagedFocusComponent)); export { GridCore };
const flatten = arr => Array.prototype.concat(...arr) /* const flatten = arr => arr.reduce( (flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), [] ) */ module.exports = flatten
version https://git-lfs.github.com/spec/v1 oid sha256:9f3f7f239a524560b08a4eb3b14846e27617b6145c9fa5a193b61e34a82bfa65 size 49127
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); define(["require", "exports", "react", "office-ui-fabric-react/lib/Checkbox", "office-ui-fabric-react/lib/Layer", "office-ui-fabric-react/lib/Toggle", "./Layer.Example.scss"], function (require, exports, React, Checkbox_1, Layer_1, Toggle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LayerHostedExample = (function (_super) { __extends(LayerHostedExample, _super); function LayerHostedExample() { var _this = _super.call(this) || this; _this.state = { showLayer: false, showHost: true }; return _this; } LayerHostedExample.prototype.render = function () { var _this = this; var _a = this.state, showLayer = _a.showLayer, showHost = _a.showHost; var content = (React.createElement("div", { className: 'LayerExample-content ms-u-scaleUpIn100' }, "This is example layer content.")); return (React.createElement("div", null, React.createElement(Toggle_1.Toggle, { label: 'Show host', checked: showHost, onChanged: function (checked) { return _this.setState({ showHost: checked }); } }), showHost && (React.createElement(Layer_1.LayerHost, { id: 'layerhost1', className: 'LayerExample-customHost' })), React.createElement("p", { id: 'foo' }, "In some cases, you may need to contain layered content within an area. Create an instance of a LayerHost along with an id, and provide a hostId on the layer to render it within the specific host. (Note that it's important that you don't include children within the LayerHost. It's meant to contain Layered content only.)"), React.createElement(Checkbox_1.Checkbox, { label: 'Render the box below in a Layer and target it at hostId=layerhost1', checked: showLayer, onChange: function (ev, checked) { return _this.setState({ showLayer: checked }); } }), showLayer ? (React.createElement(Layer_1.Layer, { hostId: 'layerhost1', onLayerDidMount: function () { return console.log('didmount'); }, onLayerWillUnmount: function () { return console.log('willunmount'); } }, content)) : content, React.createElement("div", { className: 'LayerExample-nonLayered' }, "I am normally below the content."))); }; return LayerHostedExample; }(React.Component)); exports.LayerHostedExample = LayerHostedExample; }); //# sourceMappingURL=Layer.Hosted.Example.js.map
;!(function() { window.Mapbender = Mapbender || {}; window.Mapbender.Search = window.Mapbender.Search || {} var tableDefaults = { lengthChange: false, pageLength: 15, searching: true, info: true, processing: false, ordering: true, paging: true, autoWidth: false, oLanguage: { sInfo: '_START_ / _END_ (_TOTAL_)', oPaginate: { sNext: 'Weiter', sPrevious: 'Zurück' } } }; function escapeHtml(text) { 'use strict'; return text.replace(/["&'\/<>]/g, function (a) { return { '"': '&quot;', '&': '&amp;', "'": '&#39;', '/': '&#47;', '<': '&lt;', '>': '&gt;' }[a]; }); } Mapbender.Search.TableRenderer = function(buttonTemplate) { this.buttonTemplate = buttonTemplate; }; Mapbender.Search.TableRenderer.prototype.updateTable = function($table, query) { var tableApi = $table.dataTable().api(); tableApi.destroy(); $table.empty(); this.initializeTable($table, query); }; Mapbender.Search.TableRenderer.prototype.initializeTable = function($table, query) { var self = this; var columns = query.fields.map(function(definition) { return { title: definition.title, data: function(feature) { var data = self.dataFromFeature_(feature)[definition.fieldName]; if (typeof(data) == 'string') { data = escapeHtml(data); } return data; } }; }); var tableOptions = Object.assign({}, tableDefaults, { columns: columns, createdRow: function(tr, feature) { $(tr).data({feature: feature}); feature.tableRow = tr; } }); // Add buttons column tableOptions.columnDefs = [{ targets: -1, width: '1%', orderable: false, searchable: false, defaultContent: this.buttonTemplate }]; tableOptions.columns.push({ data: null, title: '' }); $table.dataTable(tableOptions); }; Mapbender.Search.TableRenderer.prototype.replaceRows = function(table, data) { var tableApi = $(table).dataTable().api(); tableApi.clear(); tableApi.rows.add(data); tableApi.draw(); }; Mapbender.Search.TableRenderer.prototype.pageToRow = function(table, tr) { var tableApi = $(table).dataTable().api(); var rowsPerPage = tableApi.page.len(); var rowIndex = tableApi.rows({order: 'current'}).nodes().indexOf(tr); var pageWithRow = Math.floor(rowIndex / rowsPerPage); tableApi.page(pageWithRow).draw(false); }; Mapbender.Search.TableRenderer.prototype.toggleDetails = function(tr, schema) { var $tr = $(tr); var tableApi = $tr.closest('table').dataTable().api(); var row = tableApi.row(tr); if (row.child.isShown()) { row.child.hide(); } else { var markup = this.renderDetails_(schema, $(tr).data('feature')); if (markup) { row.child(markup); row.child.show(); } } }; Mapbender.Search.TableRenderer.prototype.renderDetails_ = function(schema, feature) { var rows = []; var fieldDefs = schema.fields || []; var data = this.dataFromFeature_(feature); for (var i = 0; i < fieldDefs.length; ++i) { var field = fieldDefs[i].name; if (data[field]) { rows.push($(document.createElement('tr')) .append($('<th>').text(fieldDefs[i].title + ": ")) .append($('<td>').text(data[field]))); } } if (rows.length) { return $(document.createElement('table')).append(rows); } else { return null; } }; Mapbender.Search.TableRenderer.prototype.dataFromFeature_ = function(feature) { return feature.getProperties && feature.getProperties() || feature.attributes || {}; }; }());
import ImageUtils from './ImageUtils' const tiffTags = { 0x0112: 'orientation', 0x0132: 'dateTaken', 0x010F: 'cameraMake', 0x0110: 'cameraModel' } const JPEG_START_OF_IMAGE_MARKER = 0xFFD8 const EXIF_MARKER = 0xFFE1 class ImageExifReader { constructor( image ){ this.image = image this.dataView = ImageUtils.dataViewFromImage( image ) this.isLittleEndian = true } isJpeg(){ return this.dataView.getUint16( 0 ) === JPEG_START_OF_IMAGE_MARKER } read(){ if( !this.isJpeg() ) return null const startOfExifData = this._findStartOfExifData() if( !startOfExifData ) return null return this._readEXIFData( startOfExifData ) } _findStartOfExifData(){ let offset = 2 while( offset < this.dataView.byteLength ){ if( this.dataView.getUint16( offset ) !== EXIF_MARKER ){ // Move to next marker - 2 bytes for marker, unint16 for size of marker data offset += 2 + this.dataView.getUint16( offset + 2 ) } return offset + 4 } return null } // This must be called before doing any reads from the dataView _chooseEndianessFromTiffHeader( tiffHeaderOffset ){ if( this.dataView.getUint16( tiffHeaderOffset ) === 0x4949 ){ // Intel Format this.isLittleEndian = true }else if( this.dataView.getUint16( tiffHeaderOffset ) === 0x4D4D ){ // Motorola Format this.isLittleEndian = false }else{ this.isLittleEndian = void 0 // let browser choose } } _isValidExifStructure( start ){ if( this._getStringFromBuffer( this.dataView, start, 4 ) !== 'Exif' ) return false if( this.dataView.getUint16( start + 8, this.isLittleEndian ) !== 0x002A ) return false // 42 = tiff file marker return true } _readEXIFData( start ){ const tiffHeaderOffset = start + 6 this._chooseEndianessFromTiffHeader( tiffHeaderOffset ) if( !this._isValidExifStructure( start ) ) return null const firstIFDOffset = this.dataView.getUint32( tiffHeaderOffset + 4, this.isLittleEndian ) if( firstIFDOffset < 0x00000008 ) return null return this._readTags( tiffHeaderOffset, tiffHeaderOffset + firstIFDOffset ) } _readTags( tiffStart, dirStart ){ const numberOfEntries = this.dataView.getUint16( dirStart, this.isLittleEndian ) const tags = {} for( let i = 0; i < numberOfEntries; i++ ){ const entryOffset = dirStart + i * 12 + 2 // each entry is 12 bytes const tag = tiffTags[ this.dataView.getUint16( entryOffset, this.isLittleEndian ) ] if( !tag ) continue tags[tag] = this._readTagValue( entryOffset, tiffStart ) } return tags } _readTagValue( entryOffset, tiffStart ){ const type = this.dataView.getUint16( entryOffset + 2, this.isLittleEndian ) const numValues = this.dataView.getUint32( entryOffset + 4, this.isLittleEndian ) const inlineValueOffset = entryOffset + 8 const externalValueOffset = tiffStart + this.dataView.getUint32( inlineValueOffset, this.isLittleEndian ) switch( type ){ case 2: // ascii, 8-bit byte const valueOffset = numValues > 4 ? externalValueOffset : inlineValueOffset return this._getStringFromBuffer( this.dataView, valueOffset, numValues - 1 ) case 3: // short, 16 bit int if( numValues === 1 ){ return this.dataView.getUint16( inlineValueOffset ) } else { const valuesOffset = numValues > 2 ? externalValueOffset : inlineValueOffset const vals = [] for( let n = 0; n < numValues; n++ ){ const valuesItemOffset = n * 2 vals[n] = this.dataView.getUint16( valuesOffset + valuesItemOffset ) } return vals } default: break } } _getStringFromBuffer( buffer, start, length ){ let outstr = '' for( let n = start; n < start + length; n++ ){ outstr += String.fromCharCode( buffer.getUint8( n, this.isLittleEndian ) ) } return outstr } } export default ImageExifReader
import React from 'react'; import {Flex} from 'reflexbox'; import {Card, CardTitle, CardText} from 'material-ui'; export default () => ( <Flex auto column align='center' justify='center'> <Card> <CardTitle title='Admin' /> <CardText> <Flex column> <span>{'You are an admin!'}</span> </Flex> </CardText> </Card> </Flex> );
import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS, LOAD_PROFILE_FAILURE } from '../actions/account'; import { getToken } from '../utils/apiUtils' function initializeState() { const token = getToken(); return Object.assign({}, { loggingIn: false, loggedIn: token != null, error: null }); } export default function login(state = initializeState(), action) { switch (action.type) { case LOGIN_REQUEST: return Object.assign({}, state, {loggingIn: true, loggedIn: false}); case LOGIN_SUCCESS: return Object.assign({}, state, {loggingIn: false, loggedIn: true, error: null}); case LOGIN_FAILURE: return Object.assign({}, state, {loggingIn: false, loggedIn: false, error: action.error}); case LOAD_PROFILE_FAILURE: case LOGOUT_SUCCESS: return Object.assign({}, state, {loggingIn: false, loggedIn: false}); default: return state; } }
'use strict'; var log = require('winston'); module.exports = function(req, res, next) { if(req.isAuthenticated()) log.info('User', req.user.name, req.method, req.url); else log.info('Unauthorized ' + req.method + ' to ' + req.url); next(); }
((window["webpackJsonp"] = window["webpackJsonp"] || []).push([["static/development/pages/index.js"],{ /***/ "./components/Footer.js": /*!******************************!*\ !*** ./components/Footer.js ***! \******************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); var _jsxFileName = "/Users/inlife/Projects/inlife.github.io/components/Footer.js"; /* harmony default export */ __webpack_exports__["default"] = (function () { return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "footer", __source: { fileName: _jsxFileName, lineNumber: 2 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 3 }, __self: this }, "made with ", react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "smaller", __source: { fileName: _jsxFileName, lineNumber: 3 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-heart red", __source: { fileName: _jsxFileName, lineNumber: 3 }, __self: this })), " 2018")); }); /***/ }), /***/ "./config.js": /*!*******************!*\ !*** ./config.js ***! \*******************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var name = 'Vladyslav Hrytsenko'; var role = 'Software Engineer'; var site = 'https://inlife.github.io/'; var yearsOfExp = new Date().getFullYear() - 2010; var keywords = ['inlife', 'inlife360'].concat(name.split(' '), role.split(' ')).join(' '); var description = "Hey! I am ".concat(name, ", ").concat(role, " with >").concat(yearsOfExp, " years of experience."); /* harmony default export */ __webpack_exports__["default"] = ({ name: name, role: role, site: site, keywords: keywords, description: description, yearsOfExp: yearsOfExp }); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/array/from.js": /*!*******************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/array/from.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/array/from */ "./node_modules/core-js/library/fn/array/from.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/array/is-array */ "./node_modules/core-js/library/fn/array/is-array.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/get-iterator.js": /*!*********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/get-iterator.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/get-iterator */ "./node_modules/core-js/library/fn/get-iterator.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/is-iterable.js": /*!********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/is-iterable.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/is-iterable */ "./node_modules/core-js/library/fn/is-iterable.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/json/stringify.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/json/stringify.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/json/stringify */ "./node_modules/core-js/library/fn/json/stringify.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/assign.js": /*!**********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/assign.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/assign */ "./node_modules/core-js/library/fn/object/assign.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/create.js": /*!**********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/create.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/create */ "./node_modules/core-js/library/fn/object/create.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js": /*!*******************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/define-property */ "./node_modules/core-js/library/fn/object/define-property.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-descriptor.js": /*!*******************************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-descriptor.js ***! \*******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/get-own-property-descriptor */ "./node_modules/core-js/library/fn/object/get-own-property-descriptor.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-symbols.js": /*!****************************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-symbols.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/get-own-property-symbols */ "./node_modules/core-js/library/fn/object/get-own-property-symbols.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/get-prototype-of.js": /*!********************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/get-prototype-of.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/get-prototype-of */ "./node_modules/core-js/library/fn/object/get-prototype-of.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/keys.js": /*!********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/keys.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/keys */ "./node_modules/core-js/library/fn/object/keys.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/object/set-prototype-of.js": /*!********************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/object/set-prototype-of.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/object/set-prototype-of */ "./node_modules/core-js/library/fn/object/set-prototype-of.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/promise.js": /*!****************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/promise.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/promise */ "./node_modules/core-js/library/fn/promise.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/reflect/construct.js": /*!**************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/reflect/construct.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/reflect/construct */ "./node_modules/core-js/library/fn/reflect/construct.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/set.js": /*!************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/set.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/set */ "./node_modules/core-js/library/fn/set.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/symbol.js": /*!***************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/symbol.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/symbol */ "./node_modules/core-js/library/fn/symbol/index.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/core-js/symbol/iterator.js": /*!************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/core-js/symbol/iterator.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! core-js/library/fn/symbol/iterator */ "./node_modules/core-js/library/fn/symbol/iterator.js"); /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/arrayWithHoles.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/arrayWithHoles.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Array$isArray = __webpack_require__(/*! ../core-js/array/is-array */ "./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js"); function _arrayWithHoles(arr) { if (_Array$isArray(arr)) return arr; } module.exports = _arrayWithHoles; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/arrayWithoutHoles.js": /*!**************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/arrayWithoutHoles.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Array$isArray = __webpack_require__(/*! ../core-js/array/is-array */ "./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js"); function _arrayWithoutHoles(arr) { if (_Array$isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } module.exports = _arrayWithoutHoles; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/assertThisInitialized.js": /*!******************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/assertThisInitialized.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js": /*!*************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Promise = __webpack_require__(/*! ../core-js/promise */ "./node_modules/@babel/runtime-corejs2/core-js/promise.js"); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { _Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new _Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } module.exports = _asyncToGenerator; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/construct.js": /*!******************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/construct.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Reflect$construct = __webpack_require__(/*! ../core-js/reflect/construct */ "./node_modules/@babel/runtime-corejs2/core-js/reflect/construct.js"); var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/setPrototypeOf.js"); function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !_Reflect$construct) return false; if (_Reflect$construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(_Reflect$construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { module.exports = _construct = _Reflect$construct; } else { module.exports = _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } module.exports = _construct; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js": /*!********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/createClass.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$defineProperty = __webpack_require__(/*! ../core-js/object/define-property */ "./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; _Object$defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } module.exports = _createClass; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$defineProperty = __webpack_require__(/*! ../core-js/object/define-property */ "./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js"); function _defineProperty(obj, key, value) { if (key in obj) { _Object$defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$getPrototypeOf = __webpack_require__(/*! ../core-js/object/get-prototype-of */ "./node_modules/@babel/runtime-corejs2/core-js/object/get-prototype-of.js"); var _Object$setPrototypeOf = __webpack_require__(/*! ../core-js/object/set-prototype-of */ "./node_modules/@babel/runtime-corejs2/core-js/object/set-prototype-of.js"); function _getPrototypeOf(o) { module.exports = _getPrototypeOf = _Object$setPrototypeOf ? _Object$getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || _Object$getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/inherits.js": /*!*****************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/inherits.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$create = __webpack_require__(/*! ../core-js/object/create */ "./node_modules/@babel/runtime-corejs2/core-js/object/create.js"); var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/setPrototypeOf.js"); function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = _Object$create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js": /*!******************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = _interopRequireDefault; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireWildcard.js": /*!*******************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/interopRequireWildcard.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$getOwnPropertyDescriptor = __webpack_require__(/*! ../core-js/object/get-own-property-descriptor */ "./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-descriptor.js"); var _Object$defineProperty = __webpack_require__(/*! ../core-js/object/define-property */ "./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = _Object$defineProperty && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { _Object$defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } module.exports = _interopRequireWildcard; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/iterableToArray.js": /*!************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/iterableToArray.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Array$from = __webpack_require__(/*! ../core-js/array/from */ "./node_modules/@babel/runtime-corejs2/core-js/array/from.js"); var _isIterable = __webpack_require__(/*! ../core-js/is-iterable */ "./node_modules/@babel/runtime-corejs2/core-js/is-iterable.js"); function _iterableToArray(iter) { if (_isIterable(Object(iter)) || Object.prototype.toString.call(iter) === "[object Arguments]") return _Array$from(iter); } module.exports = _iterableToArray; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/iterableToArrayLimit.js": /*!*****************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/iterableToArrayLimit.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _getIterator = __webpack_require__(/*! ../core-js/get-iterator */ "./node_modules/@babel/runtime-corejs2/core-js/get-iterator.js"); function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = _getIterator(arr), _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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } module.exports = _iterableToArrayLimit; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/nonIterableRest.js": /*!************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/nonIterableRest.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } module.exports = _nonIterableRest; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/nonIterableSpread.js": /*!**************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/nonIterableSpread.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } module.exports = _nonIterableSpread; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/objectSpread.js": /*!*********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/objectSpread.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$getOwnPropertyDescriptor = __webpack_require__(/*! ../core-js/object/get-own-property-descriptor */ "./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-descriptor.js"); var _Object$getOwnPropertySymbols = __webpack_require__(/*! ../core-js/object/get-own-property-symbols */ "./node_modules/@babel/runtime-corejs2/core-js/object/get-own-property-symbols.js"); var _Object$keys = __webpack_require__(/*! ../core-js/object/keys */ "./node_modules/@babel/runtime-corejs2/core-js/object/keys.js"); var defineProperty = __webpack_require__(/*! ./defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js"); function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = _Object$keys(source); if (typeof _Object$getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(_Object$getOwnPropertySymbols(source).filter(function (sym) { return _Object$getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { defineProperty(target, key, source[key]); }); } return target; } module.exports = _objectSpread; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js": /*!**********************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/@babel/runtime-corejs2/helpers/typeof.js"); var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime-corejs2/helpers/assertThisInitialized.js"); function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } module.exports = _possibleConstructorReturn; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/setPrototypeOf.js": /*!***********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/setPrototypeOf.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Object$setPrototypeOf = __webpack_require__(/*! ../core-js/object/set-prototype-of */ "./node_modules/@babel/runtime-corejs2/core-js/object/set-prototype-of.js"); function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = _Object$setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/slicedToArray.js": /*!**********************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/slicedToArray.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles */ "./node_modules/@babel/runtime-corejs2/helpers/arrayWithHoles.js"); var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit */ "./node_modules/@babel/runtime-corejs2/helpers/iterableToArrayLimit.js"); var nonIterableRest = __webpack_require__(/*! ./nonIterableRest */ "./node_modules/@babel/runtime-corejs2/helpers/nonIterableRest.js"); function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } module.exports = _slicedToArray; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/toConsumableArray.js": /*!**************************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/toConsumableArray.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var arrayWithoutHoles = __webpack_require__(/*! ./arrayWithoutHoles */ "./node_modules/@babel/runtime-corejs2/helpers/arrayWithoutHoles.js"); var iterableToArray = __webpack_require__(/*! ./iterableToArray */ "./node_modules/@babel/runtime-corejs2/helpers/iterableToArray.js"); var nonIterableSpread = __webpack_require__(/*! ./nonIterableSpread */ "./node_modules/@babel/runtime-corejs2/helpers/nonIterableSpread.js"); function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } module.exports = _toConsumableArray; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/helpers/typeof.js": /*!***************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/helpers/typeof.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _Symbol$iterator = __webpack_require__(/*! ../core-js/symbol/iterator */ "./node_modules/@babel/runtime-corejs2/core-js/symbol/iterator.js"); var _Symbol = __webpack_require__(/*! ../core-js/symbol */ "./node_modules/@babel/runtime-corejs2/core-js/symbol.js"); function _typeof2(obj) { if (typeof _Symbol === "function" && typeof _Symbol$iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof _Symbol === "function" && obj.constructor === _Symbol && obj !== _Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } function _typeof(obj) { if (typeof _Symbol === "function" && _typeof2(_Symbol$iterator) === "symbol") { module.exports = _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof _Symbol === "function" && obj.constructor === _Symbol && obj !== _Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } module.exports = _typeof; /***/ }), /***/ "./node_modules/@babel/runtime-corejs2/regenerator/index.js": /*!******************************************************************!*\ !*** ./node_modules/@babel/runtime-corejs2/regenerator/index.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime-module.js"); /***/ }), /***/ "./node_modules/core-js/library/fn/array/from.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/fn/array/from.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../../modules/es6.array.from */ "./node_modules/core-js/library/modules/es6.array.from.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Array.from; /***/ }), /***/ "./node_modules/core-js/library/fn/array/is-array.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/library/fn/array/is-array.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.array.is-array */ "./node_modules/core-js/library/modules/es6.array.is-array.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Array.isArray; /***/ }), /***/ "./node_modules/core-js/library/fn/get-iterator.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/fn/get-iterator.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/web.dom.iterable */ "./node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); module.exports = __webpack_require__(/*! ../modules/core.get-iterator */ "./node_modules/core-js/library/modules/core.get-iterator.js"); /***/ }), /***/ "./node_modules/core-js/library/fn/is-iterable.js": /*!********************************************************!*\ !*** ./node_modules/core-js/library/fn/is-iterable.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/web.dom.iterable */ "./node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); module.exports = __webpack_require__(/*! ../modules/core.is-iterable */ "./node_modules/core-js/library/modules/core.is-iterable.js"); /***/ }), /***/ "./node_modules/core-js/library/fn/json/stringify.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/library/fn/json/stringify.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js"); var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); module.exports = function stringify(it) { // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }), /***/ "./node_modules/core-js/library/fn/object/assign.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/fn/object/assign.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.assign */ "./node_modules/core-js/library/modules/es6.object.assign.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object.assign; /***/ }), /***/ "./node_modules/core-js/library/fn/object/create.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/fn/object/create.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.create */ "./node_modules/core-js/library/modules/es6.object.create.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object; module.exports = function create(P, D) { return $Object.create(P, D); }; /***/ }), /***/ "./node_modules/core-js/library/fn/object/define-property.js": /*!*******************************************************************!*\ !*** ./node_modules/core-js/library/fn/object/define-property.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.define-property */ "./node_modules/core-js/library/modules/es6.object.define-property.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object; module.exports = function defineProperty(it, key, desc) { return $Object.defineProperty(it, key, desc); }; /***/ }), /***/ "./node_modules/core-js/library/fn/object/get-own-property-descriptor.js": /*!*******************************************************************************!*\ !*** ./node_modules/core-js/library/fn/object/get-own-property-descriptor.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.get-own-property-descriptor */ "./node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object; module.exports = function getOwnPropertyDescriptor(it, key) { return $Object.getOwnPropertyDescriptor(it, key); }; /***/ }), /***/ "./node_modules/core-js/library/fn/object/get-own-property-symbols.js": /*!****************************************************************************!*\ !*** ./node_modules/core-js/library/fn/object/get-own-property-symbols.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.symbol */ "./node_modules/core-js/library/modules/es6.symbol.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object.getOwnPropertySymbols; /***/ }), /***/ "./node_modules/core-js/library/fn/object/get-prototype-of.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/fn/object/get-prototype-of.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.get-prototype-of */ "./node_modules/core-js/library/modules/es6.object.get-prototype-of.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object.getPrototypeOf; /***/ }), /***/ "./node_modules/core-js/library/fn/object/keys.js": /*!********************************************************!*\ !*** ./node_modules/core-js/library/fn/object/keys.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.keys */ "./node_modules/core-js/library/modules/es6.object.keys.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object.keys; /***/ }), /***/ "./node_modules/core-js/library/fn/object/set-prototype-of.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/fn/object/set-prototype-of.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.set-prototype-of */ "./node_modules/core-js/library/modules/es6.object.set-prototype-of.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Object.setPrototypeOf; /***/ }), /***/ "./node_modules/core-js/library/fn/promise.js": /*!****************************************************!*\ !*** ./node_modules/core-js/library/fn/promise.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/es6.object.to-string */ "./node_modules/core-js/library/modules/es6.object.to-string.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../modules/web.dom.iterable */ "./node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.promise */ "./node_modules/core-js/library/modules/es6.promise.js"); __webpack_require__(/*! ../modules/es7.promise.finally */ "./node_modules/core-js/library/modules/es7.promise.finally.js"); __webpack_require__(/*! ../modules/es7.promise.try */ "./node_modules/core-js/library/modules/es7.promise.try.js"); module.exports = __webpack_require__(/*! ../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Promise; /***/ }), /***/ "./node_modules/core-js/library/fn/reflect/construct.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/fn/reflect/construct.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.reflect.construct */ "./node_modules/core-js/library/modules/es6.reflect.construct.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Reflect.construct; /***/ }), /***/ "./node_modules/core-js/library/fn/set.js": /*!************************************************!*\ !*** ./node_modules/core-js/library/fn/set.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/es6.object.to-string */ "./node_modules/core-js/library/modules/es6.object.to-string.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../modules/web.dom.iterable */ "./node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.set */ "./node_modules/core-js/library/modules/es6.set.js"); __webpack_require__(/*! ../modules/es7.set.to-json */ "./node_modules/core-js/library/modules/es7.set.to-json.js"); __webpack_require__(/*! ../modules/es7.set.of */ "./node_modules/core-js/library/modules/es7.set.of.js"); __webpack_require__(/*! ../modules/es7.set.from */ "./node_modules/core-js/library/modules/es7.set.from.js"); module.exports = __webpack_require__(/*! ../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Set; /***/ }), /***/ "./node_modules/core-js/library/fn/symbol/index.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/fn/symbol/index.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.symbol */ "./node_modules/core-js/library/modules/es6.symbol.js"); __webpack_require__(/*! ../../modules/es6.object.to-string */ "./node_modules/core-js/library/modules/es6.object.to-string.js"); __webpack_require__(/*! ../../modules/es7.symbol.async-iterator */ "./node_modules/core-js/library/modules/es7.symbol.async-iterator.js"); __webpack_require__(/*! ../../modules/es7.symbol.observable */ "./node_modules/core-js/library/modules/es7.symbol.observable.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "./node_modules/core-js/library/modules/_core.js").Symbol; /***/ }), /***/ "./node_modules/core-js/library/fn/symbol/iterator.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/fn/symbol/iterator.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.string.iterator */ "./node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../../modules/web.dom.iterable */ "./node_modules/core-js/library/modules/web.dom.iterable.js"); module.exports = __webpack_require__(/*! ../../modules/_wks-ext */ "./node_modules/core-js/library/modules/_wks-ext.js").f('iterator'); /***/ }), /***/ "./node_modules/core-js/library/modules/_a-function.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_a-function.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_add-to-unscopables.js": /*!*********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_add-to-unscopables.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function () { /* empty */ }; /***/ }), /***/ "./node_modules/core-js/library/modules/_an-instance.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_an-instance.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_an-object.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_an-object.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_array-from-iterable.js": /*!**********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_array-from-iterable.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var forOf = __webpack_require__(/*! ./_for-of */ "./node_modules/core-js/library/modules/_for-of.js"); module.exports = function (iter, ITERATOR) { var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_array-includes.js": /*!*****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_array-includes.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var toLength = __webpack_require__(/*! ./_to-length */ "./node_modules/core-js/library/modules/_to-length.js"); var toAbsoluteIndex = __webpack_require__(/*! ./_to-absolute-index */ "./node_modules/core-js/library/modules/_to-absolute-index.js"); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_array-methods.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_array-methods.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var IObject = __webpack_require__(/*! ./_iobject */ "./node_modules/core-js/library/modules/_iobject.js"); var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var toLength = __webpack_require__(/*! ./_to-length */ "./node_modules/core-js/library/modules/_to-length.js"); var asc = __webpack_require__(/*! ./_array-species-create */ "./node_modules/core-js/library/modules/_array-species-create.js"); module.exports = function (TYPE, $create) { 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 NO_HOLES = TYPE == 5 || IS_FIND_INDEX; var create = $create || asc; return function ($this, callbackfn, that) { var O = toObject($this); var self = IObject(O); var f = ctx(callbackfn, that, 3); var length = toLength(self.length); var index = 0; var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; var val, res; for (;length > index; index++) if (NO_HOLES || index in self) { val = self[index]; res = f(val, index, O); if (TYPE) { if (IS_MAP) result[index] = res; // map else if (res) switch (TYPE) { case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if (IS_EVERY) return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_array-species-constructor.js": /*!****************************************************************************!*\ !*** ./node_modules/core-js/library/modules/_array-species-constructor.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var isArray = __webpack_require__(/*! ./_is-array */ "./node_modules/core-js/library/modules/_is-array.js"); var SPECIES = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('species'); module.exports = function (original) { var C; if (isArray(original)) { C = original.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return C === undefined ? Array : C; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_array-species-create.js": /*!***********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_array-species-create.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = __webpack_require__(/*! ./_array-species-constructor */ "./node_modules/core-js/library/modules/_array-species-constructor.js"); module.exports = function (original, length) { return new (speciesConstructor(original))(length); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_bind.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_bind.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var invoke = __webpack_require__(/*! ./_invoke */ "./node_modules/core-js/library/modules/_invoke.js"); var arraySlice = [].slice; var factories = {}; var construct = function (F, len, args) { if (!(len in factories)) { for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; // eslint-disable-next-line no-new-func factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; module.exports = Function.bind || function bind(that /* , ...args */) { var fn = aFunction(this); var partArgs = arraySlice.call(arguments, 1); var bound = function (/* args... */) { var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if (isObject(fn.prototype)) bound.prototype = fn.prototype; return bound; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_classof.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_classof.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(/*! ./_cof */ "./node_modules/core-js/library/modules/_cof.js"); var TAG = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_cof.js": /*!******************************************************!*\ !*** ./node_modules/core-js/library/modules/_cof.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_collection-strong.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_collection-strong.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var dP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f; var create = __webpack_require__(/*! ./_object-create */ "./node_modules/core-js/library/modules/_object-create.js"); var redefineAll = __webpack_require__(/*! ./_redefine-all */ "./node_modules/core-js/library/modules/_redefine-all.js"); var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var anInstance = __webpack_require__(/*! ./_an-instance */ "./node_modules/core-js/library/modules/_an-instance.js"); var forOf = __webpack_require__(/*! ./_for-of */ "./node_modules/core-js/library/modules/_for-of.js"); var $iterDefine = __webpack_require__(/*! ./_iter-define */ "./node_modules/core-js/library/modules/_iter-define.js"); var step = __webpack_require__(/*! ./_iter-step */ "./node_modules/core-js/library/modules/_iter-step.js"); var setSpecies = __webpack_require__(/*! ./_set-species */ "./node_modules/core-js/library/modules/_set-species.js"); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js"); var fastKey = __webpack_require__(/*! ./_meta */ "./node_modules/core-js/library/modules/_meta.js").fastKey; var validate = __webpack_require__(/*! ./_validate-collection */ "./node_modules/core-js/library/modules/_validate-collection.js"); var SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function (that, key) { // fast case var index = fastKey(key); var entry; if (index !== 'F') return that._i[index]; // frozen object case for (entry = that._f; entry; entry = entry.n) { if (entry.k == key) return entry; } }; module.exports = { getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance(that, C, NAME, '_i'); that._t = NAME; // collection type that._i = create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear() { for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { entry.r = true; if (entry.p) entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function (key) { var that = validate(this, NAME); var entry = getEntry(that, key); if (entry) { var next = entry.n; var prev = entry.p; delete that._i[entry.i]; entry.r = true; if (prev) prev.n = next; if (next) next.p = prev; if (that._f == entry) that._f = next; if (that._l == entry) that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /* , that = undefined */) { validate(this, NAME); var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var entry; while (entry = entry ? entry.n : this._f) { f(entry.v, entry.k, this); // revert to the last existing entry while (entry && entry.r) entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key) { return !!getEntry(validate(this, NAME), key); } }); if (DESCRIPTORS) dP(C.prototype, 'size', { get: function () { return validate(this, NAME)[SIZE]; } }); return C; }, def: function (that, key, value) { var entry = getEntry(that, key); var prev, index; // change existing entry if (entry) { entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if (!that._f) that._f = entry; if (prev) prev.n = entry; that[SIZE]++; // add to index if (index !== 'F') that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function (C, NAME, IS_MAP) { // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function (iterated, kind) { this._t = validate(iterated, NAME); // target this._k = kind; // kind this._l = undefined; // previous }, function () { var that = this; var kind = that._k; var entry = that._l; // revert to the last existing entry while (entry && entry.r) entry = entry.p; // get next entry if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { // or finish the iteration that._t = undefined; return step(1); } // return step by kind if (kind == 'keys') return step(0, entry.k); if (kind == 'values') return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; /***/ }), /***/ "./node_modules/core-js/library/modules/_collection-to-json.js": /*!*********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_collection-to-json.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = __webpack_require__(/*! ./_classof */ "./node_modules/core-js/library/modules/_classof.js"); var from = __webpack_require__(/*! ./_array-from-iterable */ "./node_modules/core-js/library/modules/_array-from-iterable.js"); module.exports = function (NAME) { return function toJSON() { if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_collection.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_collection.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var meta = __webpack_require__(/*! ./_meta */ "./node_modules/core-js/library/modules/_meta.js"); var fails = __webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js"); var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); var redefineAll = __webpack_require__(/*! ./_redefine-all */ "./node_modules/core-js/library/modules/_redefine-all.js"); var forOf = __webpack_require__(/*! ./_for-of */ "./node_modules/core-js/library/modules/_for-of.js"); var anInstance = __webpack_require__(/*! ./_an-instance */ "./node_modules/core-js/library/modules/_an-instance.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js"); var dP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f; var each = __webpack_require__(/*! ./_array-methods */ "./node_modules/core-js/library/modules/_array-methods.js")(0); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js"); module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { var Base = global[NAME]; var C = Base; var ADDER = IS_MAP ? 'set' : 'add'; var proto = C && C.prototype; var O = {}; if (!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { new C().entries().next(); }))) { // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { C = wrapper(function (target, iterable) { anInstance(target, C, NAME, '_c'); target._c = new Base(); if (iterable != undefined) forOf(iterable, IS_MAP, target[ADDER], target); }); each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','), function (KEY) { var IS_ADDER = KEY == 'add' || KEY == 'set'; if (KEY in proto && !(IS_WEAK && KEY == 'clear')) hide(C.prototype, KEY, function (a, b) { anInstance(this, C, KEY); if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false; var result = this._c[KEY](a === 0 ? 0 : a, b); return IS_ADDER ? this : result; }); }); IS_WEAK || dP(C.prototype, 'size', { get: function () { return this._c.size; } }); } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F, O); if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); return C; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_core.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_core.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var core = module.exports = { version: '2.6.1' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /***/ "./node_modules/core-js/library/modules/_create-property.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/library/modules/_create-property.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $defineProperty = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "./node_modules/core-js/library/modules/_property-desc.js"); module.exports = function (object, index, value) { if (index in object) $defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_ctx.js": /*!******************************************************!*\ !*** ./node_modules/core-js/library/modules/_ctx.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_defined.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_defined.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_descriptors.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_descriptors.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js")(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "./node_modules/core-js/library/modules/_dom-create.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_dom-create.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var document = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js").document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_enum-bug-keys.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_enum-bug-keys.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /***/ "./node_modules/core-js/library/modules/_enum-keys.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_enum-keys.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(/*! ./_object-keys */ "./node_modules/core-js/library/modules/_object-keys.js"); var gOPS = __webpack_require__(/*! ./_object-gops */ "./node_modules/core-js/library/modules/_object-gops.js"); var pIE = __webpack_require__(/*! ./_object-pie */ "./node_modules/core-js/library/modules/_object-pie.js"); module.exports = function (it) { var result = getKeys(it); var getSymbols = gOPS.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = pIE.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_export.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/_export.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /***/ "./node_modules/core-js/library/modules/_fails.js": /*!********************************************************!*\ !*** ./node_modules/core-js/library/modules/_fails.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /***/ "./node_modules/core-js/library/modules/_for-of.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/_for-of.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var call = __webpack_require__(/*! ./_iter-call */ "./node_modules/core-js/library/modules/_iter-call.js"); var isArrayIter = __webpack_require__(/*! ./_is-array-iter */ "./node_modules/core-js/library/modules/_is-array-iter.js"); var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var toLength = __webpack_require__(/*! ./_to-length */ "./node_modules/core-js/library/modules/_to-length.js"); var getIterFn = __webpack_require__(/*! ./core.get-iterator-method */ "./node_modules/core-js/library/modules/core.get-iterator-method.js"); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /***/ "./node_modules/core-js/library/modules/_global.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/_global.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /***/ "./node_modules/core-js/library/modules/_has.js": /*!******************************************************!*\ !*** ./node_modules/core-js/library/modules/_has.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_hide.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_hide.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "./node_modules/core-js/library/modules/_property-desc.js"); module.exports = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js") ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_html.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_html.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js").document; module.exports = document && document.documentElement; /***/ }), /***/ "./node_modules/core-js/library/modules/_ie8-dom-define.js": /*!*****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_ie8-dom-define.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js") && !__webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js")(function () { return Object.defineProperty(__webpack_require__(/*! ./_dom-create */ "./node_modules/core-js/library/modules/_dom-create.js")('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "./node_modules/core-js/library/modules/_invoke.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/_invoke.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iobject.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_iobject.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(/*! ./_cof */ "./node_modules/core-js/library/modules/_cof.js"); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_is-array-iter.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_is-array-iter.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_is-array.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/library/modules/_is-array.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(/*! ./_cof */ "./node_modules/core-js/library/modules/_cof.js"); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_is-object.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_is-object.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iter-call.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iter-call.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iter-create.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iter-create.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__(/*! ./_object-create */ "./node_modules/core-js/library/modules/_object-create.js"); var descriptor = __webpack_require__(/*! ./_property-desc */ "./node_modules/core-js/library/modules/_property-desc.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js"); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js")(IteratorPrototype, __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iter-define.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iter-define.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js"); var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var redefine = __webpack_require__(/*! ./_redefine */ "./node_modules/core-js/library/modules/_redefine.js"); var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); var $iterCreate = __webpack_require__(/*! ./_iter-create */ "./node_modules/core-js/library/modules/_iter-create.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js"); var getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "./node_modules/core-js/library/modules/_object-gpo.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iter-detect.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iter-detect.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iter-step.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iter-step.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_iterators.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_iterators.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /***/ "./node_modules/core-js/library/modules/_library.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_library.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = true; /***/ }), /***/ "./node_modules/core-js/library/modules/_meta.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_meta.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(/*! ./_uid */ "./node_modules/core-js/library/modules/_uid.js")('meta'); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var setDesc = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js")(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /***/ "./node_modules/core-js/library/modules/_microtask.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_microtask.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var macrotask = __webpack_require__(/*! ./_task */ "./node_modules/core-js/library/modules/_task.js").set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __webpack_require__(/*! ./_cof */ "./node_modules/core-js/library/modules/_cof.js")(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function () { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify(); else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (isNode) { notify = function () { process.nextTick(flush); }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 } else if (Observer && !(global.navigator && global.navigator.standalone)) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 var promise = Promise.resolve(undefined); notify = function () { promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_new-promise-capability.js": /*!*************************************************************************!*\ !*** ./node_modules/core-js/library/modules/_new-promise-capability.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-assign.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-assign.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(/*! ./_object-keys */ "./node_modules/core-js/library/modules/_object-keys.js"); var gOPS = __webpack_require__(/*! ./_object-gops */ "./node_modules/core-js/library/modules/_object-gops.js"); var pIE = __webpack_require__(/*! ./_object-pie */ "./node_modules/core-js/library/modules/_object-pie.js"); var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var IObject = __webpack_require__(/*! ./_iobject */ "./node_modules/core-js/library/modules/_iobject.js"); var $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js")(function () { var A = {}; var B = {}; // eslint-disable-next-line no-undef var S = Symbol(); var K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function (k) { B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars var T = toObject(target); var aLen = arguments.length; var index = 1; var getSymbols = gOPS.f; var isEnum = pIE.f; while (aLen > index) { var S = IObject(arguments[index++]); var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); var length = keys.length; var j = 0; var key; while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; } return T; } : $assign; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-create.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-create.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var dPs = __webpack_require__(/*! ./_object-dps */ "./node_modules/core-js/library/modules/_object-dps.js"); var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "./node_modules/core-js/library/modules/_enum-bug-keys.js"); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "./node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(/*! ./_dom-create */ "./node_modules/core-js/library/modules/_dom-create.js")('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__(/*! ./_html */ "./node_modules/core-js/library/modules/_html.js").appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-dp.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-dp.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "./node_modules/core-js/library/modules/_ie8-dom-define.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "./node_modules/core-js/library/modules/_to-primitive.js"); var dP = Object.defineProperty; exports.f = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js") ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-dps.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-dps.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js"); var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var getKeys = __webpack_require__(/*! ./_object-keys */ "./node_modules/core-js/library/modules/_object-keys.js"); module.exports = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js") ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-gopd.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-gopd.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(/*! ./_object-pie */ "./node_modules/core-js/library/modules/_object-pie.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "./node_modules/core-js/library/modules/_property-desc.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "./node_modules/core-js/library/modules/_to-primitive.js"); var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "./node_modules/core-js/library/modules/_ie8-dom-define.js"); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js") ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-gopn-ext.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-gopn-ext.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var gOPN = __webpack_require__(/*! ./_object-gopn */ "./node_modules/core-js/library/modules/_object-gopn.js").f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-gopn.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-gopn.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(/*! ./_object-keys-internal */ "./node_modules/core-js/library/modules/_object-keys-internal.js"); var hiddenKeys = __webpack_require__(/*! ./_enum-bug-keys */ "./node_modules/core-js/library/modules/_enum-bug-keys.js").concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-gops.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-gops.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-gpo.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-gpo.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "./node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-keys-internal.js": /*!***********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-keys-internal.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var arrayIndexOf = __webpack_require__(/*! ./_array-includes */ "./node_modules/core-js/library/modules/_array-includes.js")(false); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "./node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-keys.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-keys.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(/*! ./_object-keys-internal */ "./node_modules/core-js/library/modules/_object-keys-internal.js"); var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "./node_modules/core-js/library/modules/_enum-bug-keys.js"); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-pie.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-pie.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /***/ "./node_modules/core-js/library/modules/_object-sap.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_object-sap.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var fails = __webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js"); module.exports = function (KEY, exec) { var fn = (core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_perform.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_perform.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /***/ "./node_modules/core-js/library/modules/_promise-resolve.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/library/modules/_promise-resolve.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var newPromiseCapability = __webpack_require__(/*! ./_new-promise-capability */ "./node_modules/core-js/library/modules/_new-promise-capability.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; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_property-desc.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/_property-desc.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_redefine-all.js": /*!***************************************************************!*\ !*** ./node_modules/core-js/library/modules/_redefine-all.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); module.exports = function (target, src, safe) { for (var key in src) { if (safe && target[key]) target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_redefine.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/library/modules/_redefine.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); /***/ }), /***/ "./node_modules/core-js/library/modules/_set-collection-from.js": /*!**********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_set-collection-from.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://tc39.github.io/proposal-setmap-offrom/ var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var forOf = __webpack_require__(/*! ./_for-of */ "./node_modules/core-js/library/modules/_for-of.js"); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { var mapFn = arguments[1]; var mapping, A, n, cb; aFunction(this); mapping = mapFn !== undefined; if (mapping) aFunction(mapFn); if (source == undefined) return new this(); A = []; if (mapping) { n = 0; cb = ctx(mapFn, arguments[2], 2); forOf(source, false, function (nextItem) { A.push(cb(nextItem, n++)); }); } else { forOf(source, false, A.push, A); } return new this(A); } }); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_set-collection-of.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_set-collection-of.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://tc39.github.io/proposal-setmap-offrom/ var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { of: function of() { var length = arguments.length; var A = new Array(length); while (length--) A[length] = arguments[length]; return new this(A); } }); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_set-proto.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_set-proto.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var check = function (O, proto) { anObject(O); if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function (test, buggy, set) { try { set = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js")(Function.call, __webpack_require__(/*! ./_object-gopd */ "./node_modules/core-js/library/modules/_object-gopd.js").f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch (e) { buggy = true; } return function setPrototypeOf(O, proto) { check(O, proto); if (buggy) O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }), /***/ "./node_modules/core-js/library/modules/_set-species.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/_set-species.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var dP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js"); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js"); var SPECIES = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('species'); module.exports = function (KEY) { var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_set-to-string-tag.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_set-to-string-tag.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f; var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var TAG = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_shared-key.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_shared-key.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(/*! ./_shared */ "./node_modules/core-js/library/modules/_shared.js")('keys'); var uid = __webpack_require__(/*! ./_uid */ "./node_modules/core-js/library/modules/_uid.js"); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_shared.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/_shared.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js") ? 'pure' : 'global', copyright: '© 2018 Denis Pushkarev (zloirock.ru)' }); /***/ }), /***/ "./node_modules/core-js/library/modules/_species-constructor.js": /*!**********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_species-constructor.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); var SPECIES = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_string-at.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_string-at.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(/*! ./_to-integer */ "./node_modules/core-js/library/modules/_to-integer.js"); var defined = __webpack_require__(/*! ./_defined */ "./node_modules/core-js/library/modules/_defined.js"); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_task.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/library/modules/_task.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var invoke = __webpack_require__(/*! ./_invoke */ "./node_modules/core-js/library/modules/_invoke.js"); var html = __webpack_require__(/*! ./_html */ "./node_modules/core-js/library/modules/_html.js"); var cel = __webpack_require__(/*! ./_dom-create */ "./node_modules/core-js/library/modules/_dom-create.js"); var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function () { var id = +this; // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function (event) { run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (__webpack_require__(/*! ./_cof */ "./node_modules/core-js/library/modules/_cof.js")(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function (id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in cel('script')) { defer = function (id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-absolute-index.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-absolute-index.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(/*! ./_to-integer */ "./node_modules/core-js/library/modules/_to-integer.js"); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-integer.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-integer.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-iobject.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-iobject.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(/*! ./_iobject */ "./node_modules/core-js/library/modules/_iobject.js"); var defined = __webpack_require__(/*! ./_defined */ "./node_modules/core-js/library/modules/_defined.js"); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-length.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-length.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(/*! ./_to-integer */ "./node_modules/core-js/library/modules/_to-integer.js"); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-object.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-object.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(/*! ./_defined */ "./node_modules/core-js/library/modules/_defined.js"); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_to-primitive.js": /*!***************************************************************!*\ !*** ./node_modules/core-js/library/modules/_to-primitive.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_uid.js": /*!******************************************************!*\ !*** ./node_modules/core-js/library/modules/_uid.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_user-agent.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_user-agent.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var navigator = global.navigator; module.exports = navigator && navigator.userAgent || ''; /***/ }), /***/ "./node_modules/core-js/library/modules/_validate-collection.js": /*!**********************************************************************!*\ !*** ./node_modules/core-js/library/modules/_validate-collection.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; /***/ }), /***/ "./node_modules/core-js/library/modules/_wks-define.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/_wks-define.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var LIBRARY = __webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js"); var wksExt = __webpack_require__(/*! ./_wks-ext */ "./node_modules/core-js/library/modules/_wks-ext.js"); var defineProperty = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; /***/ }), /***/ "./node_modules/core-js/library/modules/_wks-ext.js": /*!**********************************************************!*\ !*** ./node_modules/core-js/library/modules/_wks-ext.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js"); /***/ }), /***/ "./node_modules/core-js/library/modules/_wks.js": /*!******************************************************!*\ !*** ./node_modules/core-js/library/modules/_wks.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(/*! ./_shared */ "./node_modules/core-js/library/modules/_shared.js")('wks'); var uid = __webpack_require__(/*! ./_uid */ "./node_modules/core-js/library/modules/_uid.js"); var Symbol = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js").Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /***/ "./node_modules/core-js/library/modules/core.get-iterator-method.js": /*!**************************************************************************!*\ !*** ./node_modules/core-js/library/modules/core.get-iterator-method.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(/*! ./_classof */ "./node_modules/core-js/library/modules/_classof.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'); var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); module.exports = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js").getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /***/ "./node_modules/core-js/library/modules/core.get-iterator.js": /*!*******************************************************************!*\ !*** ./node_modules/core-js/library/modules/core.get-iterator.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var get = __webpack_require__(/*! ./core.get-iterator-method */ "./node_modules/core-js/library/modules/core.get-iterator-method.js"); module.exports = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js").getIterator = function (it) { var iterFn = get(it); if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/core.is-iterable.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/library/modules/core.is-iterable.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(/*! ./_classof */ "./node_modules/core-js/library/modules/_classof.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator'); var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); module.exports = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js").isIterable = function (it) { var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O // eslint-disable-next-line no-prototype-builtins || Iterators.hasOwnProperty(classof(O)); }; /***/ }), /***/ "./node_modules/core-js/library/modules/es6.array.from.js": /*!****************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.array.from.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var call = __webpack_require__(/*! ./_iter-call */ "./node_modules/core-js/library/modules/_iter-call.js"); var isArrayIter = __webpack_require__(/*! ./_is-array-iter */ "./node_modules/core-js/library/modules/_is-array-iter.js"); var toLength = __webpack_require__(/*! ./_to-length */ "./node_modules/core-js/library/modules/_to-length.js"); var createProperty = __webpack_require__(/*! ./_create-property */ "./node_modules/core-js/library/modules/_create-property.js"); var getIterFn = __webpack_require__(/*! ./core.get-iterator-method */ "./node_modules/core-js/library/modules/core.get-iterator-method.js"); $export($export.S + $export.F * !__webpack_require__(/*! ./_iter-detect */ "./node_modules/core-js/library/modules/_iter-detect.js")(function (iter) { Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var aLen = arguments.length; var mapfn = aLen > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var index = 0; var iterFn = getIterFn(O); var length, result, step, iterator; if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for (result = new C(length); length > index; index++) { createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.array.is-array.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.array.is-array.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); $export($export.S, 'Array', { isArray: __webpack_require__(/*! ./_is-array */ "./node_modules/core-js/library/modules/_is-array.js") }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.array.iterator.js": /*!********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.array.iterator.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__(/*! ./_add-to-unscopables */ "./node_modules/core-js/library/modules/_add-to-unscopables.js"); var step = __webpack_require__(/*! ./_iter-step */ "./node_modules/core-js/library/modules/_iter-step.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(/*! ./_iter-define */ "./node_modules/core-js/library/modules/_iter-define.js")(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.assign.js": /*!*******************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.assign.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); $export($export.S + $export.F, 'Object', { assign: __webpack_require__(/*! ./_object-assign */ "./node_modules/core-js/library/modules/_object-assign.js") }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.create.js": /*!*******************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.create.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: __webpack_require__(/*! ./_object-create */ "./node_modules/core-js/library/modules/_object-create.js") }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.define-property.js": /*!****************************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.define-property.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js"), 'Object', { defineProperty: __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js").f }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js": /*!****************************************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var $getOwnPropertyDescriptor = __webpack_require__(/*! ./_object-gopd */ "./node_modules/core-js/library/modules/_object-gopd.js").f; __webpack_require__(/*! ./_object-sap */ "./node_modules/core-js/library/modules/_object-sap.js")('getOwnPropertyDescriptor', function () { return function getOwnPropertyDescriptor(it, key) { return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.get-prototype-of.js": /*!*****************************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.get-prototype-of.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var $getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "./node_modules/core-js/library/modules/_object-gpo.js"); __webpack_require__(/*! ./_object-sap */ "./node_modules/core-js/library/modules/_object-sap.js")('getPrototypeOf', function () { return function getPrototypeOf(it) { return $getPrototypeOf(toObject(it)); }; }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.keys.js": /*!*****************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.keys.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(/*! ./_to-object */ "./node_modules/core-js/library/modules/_to-object.js"); var $keys = __webpack_require__(/*! ./_object-keys */ "./node_modules/core-js/library/modules/_object-keys.js"); __webpack_require__(/*! ./_object-sap */ "./node_modules/core-js/library/modules/_object-sap.js")('keys', function () { return function keys(it) { return $keys(toObject(it)); }; }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.set-prototype-of.js": /*!*****************************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.set-prototype-of.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(/*! ./_set-proto */ "./node_modules/core-js/library/modules/_set-proto.js").set }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.object.to-string.js": /*!**********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.object.to-string.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /***/ }), /***/ "./node_modules/core-js/library/modules/es6.promise.js": /*!*************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.promise.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js"); var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var ctx = __webpack_require__(/*! ./_ctx */ "./node_modules/core-js/library/modules/_ctx.js"); var classof = __webpack_require__(/*! ./_classof */ "./node_modules/core-js/library/modules/_classof.js"); var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); var anInstance = __webpack_require__(/*! ./_an-instance */ "./node_modules/core-js/library/modules/_an-instance.js"); var forOf = __webpack_require__(/*! ./_for-of */ "./node_modules/core-js/library/modules/_for-of.js"); var speciesConstructor = __webpack_require__(/*! ./_species-constructor */ "./node_modules/core-js/library/modules/_species-constructor.js"); var task = __webpack_require__(/*! ./_task */ "./node_modules/core-js/library/modules/_task.js").set; var microtask = __webpack_require__(/*! ./_microtask */ "./node_modules/core-js/library/modules/_microtask.js")(); var newPromiseCapabilityModule = __webpack_require__(/*! ./_new-promise-capability */ "./node_modules/core-js/library/modules/_new-promise-capability.js"); var perform = __webpack_require__(/*! ./_perform */ "./node_modules/core-js/library/modules/_perform.js"); var userAgent = __webpack_require__(/*! ./_user-agent */ "./node_modules/core-js/library/modules/_user-agent.js"); var promiseResolve = __webpack_require__(/*! ./_promise-resolve */ "./node_modules/core-js/library/modules/_promise-resolve.js"); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var versions = process && process.versions; var v8 = versions && versions.v8 || ''; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise // 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 && v8.indexOf('6.6') !== 0 && userAgent.indexOf('Chrome/66') === -1; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); // may throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { if (domain && !exited) domain.exit(); reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(/*! ./_redefine-all */ "./node_modules/core-js/library/modules/_redefine-all.js")($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js")($Promise, PROMISE); __webpack_require__(/*! ./_set-species */ "./node_modules/core-js/library/modules/_set-species.js")(PROMISE); Wrapper = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js")[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(/*! ./_iter-detect */ "./node_modules/core-js/library/modules/_iter-detect.js")(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.reflect.construct.js": /*!***********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.reflect.construct.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var create = __webpack_require__(/*! ./_object-create */ "./node_modules/core-js/library/modules/_object-create.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "./node_modules/core-js/library/modules/_a-function.js"); var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var fails = __webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js"); var bind = __webpack_require__(/*! ./_bind */ "./node_modules/core-js/library/modules/_bind.js"); var rConstruct = (__webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js").Reflect || {}).construct; // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails(function () { function F() { /* empty */ } return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); }); var ARGS_BUG = !fails(function () { rConstruct(function () { /* empty */ }); }); $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { construct: function construct(Target, args /* , newTarget */) { aFunction(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); if (Target == newTarget) { // w/o altered newTarget, optimization for 0-4 arguments switch (args.length) { case 0: return new Target(); case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args))(); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype; var instance = create(isObject(proto) ? proto : Object.prototype); var result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.set.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.set.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var strong = __webpack_require__(/*! ./_collection-strong */ "./node_modules/core-js/library/modules/_collection-strong.js"); var validate = __webpack_require__(/*! ./_validate-collection */ "./node_modules/core-js/library/modules/_validate-collection.js"); var SET = 'Set'; // 23.2 Set Objects module.exports = __webpack_require__(/*! ./_collection */ "./node_modules/core-js/library/modules/_collection.js")(SET, function (get) { return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value) { return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); } }, strong); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.string.iterator.js": /*!*********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.string.iterator.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__(/*! ./_string-at */ "./node_modules/core-js/library/modules/_string-at.js")(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(/*! ./_iter-define */ "./node_modules/core-js/library/modules/_iter-define.js")(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /***/ "./node_modules/core-js/library/modules/es6.symbol.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/es6.symbol.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // ECMAScript 6 symbols shim var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var has = __webpack_require__(/*! ./_has */ "./node_modules/core-js/library/modules/_has.js"); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "./node_modules/core-js/library/modules/_descriptors.js"); var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var redefine = __webpack_require__(/*! ./_redefine */ "./node_modules/core-js/library/modules/_redefine.js"); var META = __webpack_require__(/*! ./_meta */ "./node_modules/core-js/library/modules/_meta.js").KEY; var $fails = __webpack_require__(/*! ./_fails */ "./node_modules/core-js/library/modules/_fails.js"); var shared = __webpack_require__(/*! ./_shared */ "./node_modules/core-js/library/modules/_shared.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js"); var uid = __webpack_require__(/*! ./_uid */ "./node_modules/core-js/library/modules/_uid.js"); var wks = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js"); var wksExt = __webpack_require__(/*! ./_wks-ext */ "./node_modules/core-js/library/modules/_wks-ext.js"); var wksDefine = __webpack_require__(/*! ./_wks-define */ "./node_modules/core-js/library/modules/_wks-define.js"); var enumKeys = __webpack_require__(/*! ./_enum-keys */ "./node_modules/core-js/library/modules/_enum-keys.js"); var isArray = __webpack_require__(/*! ./_is-array */ "./node_modules/core-js/library/modules/_is-array.js"); var anObject = __webpack_require__(/*! ./_an-object */ "./node_modules/core-js/library/modules/_an-object.js"); var isObject = __webpack_require__(/*! ./_is-object */ "./node_modules/core-js/library/modules/_is-object.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "./node_modules/core-js/library/modules/_to-iobject.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "./node_modules/core-js/library/modules/_to-primitive.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "./node_modules/core-js/library/modules/_property-desc.js"); var _create = __webpack_require__(/*! ./_object-create */ "./node_modules/core-js/library/modules/_object-create.js"); var gOPNExt = __webpack_require__(/*! ./_object-gopn-ext */ "./node_modules/core-js/library/modules/_object-gopn-ext.js"); var $GOPD = __webpack_require__(/*! ./_object-gopd */ "./node_modules/core-js/library/modules/_object-gopd.js"); var $DP = __webpack_require__(/*! ./_object-dp */ "./node_modules/core-js/library/modules/_object-dp.js"); var $keys = __webpack_require__(/*! ./_object-keys */ "./node_modules/core-js/library/modules/_object-keys.js"); var gOPD = $GOPD.f; var dP = $DP.f; var gOPN = gOPNExt.f; var $Symbol = global.Symbol; var $JSON = global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE = 'prototype'; var HIDDEN = wks('_hidden'); var TO_PRIMITIVE = wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = shared('symbol-registry'); var AllSymbols = shared('symbols'); var OPSymbols = shared('op-symbols'); var ObjectProto = Object[PROTOTYPE]; var USE_NATIVE = typeof $Symbol == 'function'; var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function () { return _create(dP({}, 'a', { get: function () { return dP(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP(it, key, D); if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); } : dP; var wrap = function (tag) { var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if (has(AllSymbols, key)) { if (!D.enumerable) { if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _create(D, { enumerable: createDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P) { anObject(it); var keys = enumKeys(P = toIObject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = toPrimitive(key, true)); if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = toIObject(it); key = toPrimitive(key, true); if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; var D = gOPD(it, key); if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN(toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString() { return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(/*! ./_object-gopn */ "./node_modules/core-js/library/modules/_object-gopn.js").f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(/*! ./_object-pie */ "./node_modules/core-js/library/modules/_object-pie.js").f = $propertyIsEnumerable; __webpack_require__(/*! ./_object-gops */ "./node_modules/core-js/library/modules/_object-gops.js").f = $getOwnPropertySymbols; if (DESCRIPTORS && !__webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js")) { redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function (name) { return wrap(wks(name)); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js")($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.promise.finally.js": /*!*********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.promise.finally.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-finally var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var core = __webpack_require__(/*! ./_core */ "./node_modules/core-js/library/modules/_core.js"); var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var speciesConstructor = __webpack_require__(/*! ./_species-constructor */ "./node_modules/core-js/library/modules/_species-constructor.js"); var promiseResolve = __webpack_require__(/*! ./_promise-resolve */ "./node_modules/core-js/library/modules/_promise-resolve.js"); $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then( isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally ); } }); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.promise.try.js": /*!*****************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.promise.try.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-try var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); var newPromiseCapability = __webpack_require__(/*! ./_new-promise-capability */ "./node_modules/core-js/library/modules/_new-promise-capability.js"); var perform = __webpack_require__(/*! ./_perform */ "./node_modules/core-js/library/modules/_perform.js"); $export($export.S, 'Promise', { 'try': function (callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.set.from.js": /*!**************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.set.from.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from __webpack_require__(/*! ./_set-collection-from */ "./node_modules/core-js/library/modules/_set-collection-from.js")('Set'); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.set.of.js": /*!************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.set.of.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of __webpack_require__(/*! ./_set-collection-of */ "./node_modules/core-js/library/modules/_set-collection-of.js")('Set'); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.set.to-json.js": /*!*****************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.set.to-json.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js"); $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(/*! ./_collection-to-json */ "./node_modules/core-js/library/modules/_collection-to-json.js")('Set') }); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.symbol.async-iterator.js": /*!***************************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.symbol.async-iterator.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./_wks-define */ "./node_modules/core-js/library/modules/_wks-define.js")('asyncIterator'); /***/ }), /***/ "./node_modules/core-js/library/modules/es7.symbol.observable.js": /*!***********************************************************************!*\ !*** ./node_modules/core-js/library/modules/es7.symbol.observable.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./_wks-define */ "./node_modules/core-js/library/modules/_wks-define.js")('observable'); /***/ }), /***/ "./node_modules/core-js/library/modules/web.dom.iterable.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/library/modules/web.dom.iterable.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./es6.array.iterator */ "./node_modules/core-js/library/modules/es6.array.iterator.js"); var global = __webpack_require__(/*! ./_global */ "./node_modules/core-js/library/modules/_global.js"); var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js"); var TO_STRING_TAG = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /***/ "./node_modules/define-properties/index.js": /*!*************************************************!*\ !*** ./node_modules/define-properties/index.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(/*! object-keys */ "./node_modules/object-keys/index.js"); var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; var toStr = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { origDefineProperty(obj, 'x', { enumerable: false, value: obj }); // eslint-disable-next-line no-unused-vars, no-restricted-syntax for (var _ in obj) { // jscs:ignore disallowUnusedVariables return false; } return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }), /***/ "./node_modules/function-bind/implementation.js": /*!******************************************************!*\ !*** ./node_modules/function-bind/implementation.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /***/ "./node_modules/function-bind/index.js": /*!*********************************************!*\ !*** ./node_modules/function-bind/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/function-bind/implementation.js"); module.exports = Function.prototype.bind || implementation; /***/ }), /***/ "./node_modules/has-symbols/shams.js": /*!*******************************************!*\ !*** ./node_modules/has-symbols/shams.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint complexity: [2, 17], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /***/ "./node_modules/has/src/index.js": /*!***************************************!*\ !*** ./node_modules/has/src/index.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), /***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js": /*!**********************************************************************************!*\ !*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = getPrototypeOf && getPrototypeOf(Object); function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!REACT_STATICS[key] && !KNOWN_STATICS[key] && (!blacklist || !blacklist[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } module.exports = hoistNonReactStatics; /***/ }), /***/ "./node_modules/next/dist/lib/EventEmitter.js": /*!****************************************************!*\ !*** ./node_modules/next/dist/lib/EventEmitter.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _set = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/set */ "./node_modules/@babel/runtime-corejs2/core-js/set.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var EventEmitter = /*#__PURE__*/ function () { function EventEmitter() { (0, _classCallCheck2.default)(this, EventEmitter); (0, _defineProperty2.default)(this, "listeners", {}); } (0, _createClass2.default)(EventEmitter, [{ key: "on", value: function on(event, cb) { if (!this.listeners[event]) { this.listeners[event] = new _set.default(); } if (this.listeners[event].has(cb)) { throw new Error("The listener already exising in event: ".concat(event)); } this.listeners[event].add(cb); return this; } }, { key: "emit", value: function emit(event) { for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { data[_key - 1] = arguments[_key]; } var listeners = this.listeners[event]; var hasListeners = listeners && listeners.size; if (!hasListeners) { return false; } listeners.forEach(function (cb) { return cb.apply(void 0, data); }); // eslint-disable-line standard/no-callback-literal return true; } }, { key: "off", value: function off(event, cb) { this.listeners[event].delete(cb); return this; } }]); return EventEmitter; }(); exports.default = EventEmitter; /***/ }), /***/ "./node_modules/next/dist/lib/head.js": /*!********************************************!*\ !*** ./node_modules/next/dist/lib/head.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultHead = defaultHead; exports.default = void 0; var _set = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/set */ "./node_modules/@babel/runtime-corejs2/core-js/set.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js")); var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/getPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js")); var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/inherits */ "./node_modules/@babel/runtime-corejs2/helpers/inherits.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var _react = _interopRequireDefault(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "./node_modules/prop-types/index.js")); var _sideEffect = _interopRequireDefault(__webpack_require__(/*! ./side-effect */ "./node_modules/next/dist/lib/side-effect.js")); var Head = /*#__PURE__*/ function (_React$Component) { (0, _inherits2.default)(Head, _React$Component); function Head() { (0, _classCallCheck2.default)(this, Head); return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Head).apply(this, arguments)); } (0, _createClass2.default)(Head, [{ key: "render", value: function render() { return null; } }]); return Head; }(_react.default.Component); (0, _defineProperty2.default)(Head, "contextTypes", { headManager: _propTypes.default.object }); var NEXT_HEAD_IDENTIFIER = 'next-head'; function defaultHead() { var className = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NEXT_HEAD_IDENTIFIER; return [_react.default.createElement("meta", { key: "charSet", charSet: "utf-8", className: className })]; } function reduceComponents(components) { return components.map(function (component) { return _react.default.Children.toArray(component.props.children); }).reduce(function (a, b) { return a.concat(b); }, []).reduce(function (a, b) { if (_react.default.Fragment && b.type === _react.default.Fragment) { return a.concat(_react.default.Children.toArray(b.props.children)); } return a.concat(b); }, []).reverse().concat(defaultHead('')).filter(Boolean).filter(unique()).reverse().map(function (c, i) { var className = (c.props && c.props.className ? c.props.className + ' ' : '') + NEXT_HEAD_IDENTIFIER; var key = c.key || i; return _react.default.cloneElement(c, { key: key, className: className }); }); } function mapOnServer(head) { return head; } function onStateChange(head) { if (this.context && this.context.headManager) { this.context.headManager.updateHead(head); } } var METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp', 'property']; var ALLOWED_DUPLICATES = ['article:tag', 'og:image', 'og:image:alt', 'og:image:width', 'og:image:height', 'og:image:type', 'og:image:secure_url', 'og:image:url']; /* returns a function for filtering head child elements which shouldn't be duplicated, like <title/>, except we explicit allow it in ALLOWED_DUPLICATES array */ function unique() { var keys = new _set.default(); var tags = new _set.default(); var metaTypes = new _set.default(); var metaCategories = {}; return function (h) { if (h.key && h.key.indexOf('.$') === 0) { if (keys.has(h.key)) return false; keys.add(h.key); } switch (h.type) { case 'title': case 'base': if (tags.has(h.type)) return false; tags.add(h.type); break; case 'meta': for (var i = 0, len = METATYPES.length; i < len; i++) { var metatype = METATYPES[i]; if (!h.props.hasOwnProperty(metatype)) continue; if (metatype === 'charSet') { if (metaTypes.has(metatype)) return false; metaTypes.add(metatype); } else { var category = h.props[metatype]; var categories = metaCategories[metatype] || new _set.default(); if (categories.has(category) && ALLOWED_DUPLICATES.indexOf(category) === -1) return false; categories.add(category); metaCategories[metatype] = categories; } } break; } return true; }; } var _default = (0, _sideEffect.default)(reduceComponents, onStateChange, mapOnServer)(Head); exports.default = _default; /***/ }), /***/ "./node_modules/next/dist/lib/link.js": /*!********************************************!*\ !*** ./node_modules/next/dist/lib/link.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireWildcard */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireWildcard.js"); var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _stringify = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/json/stringify */ "./node_modules/@babel/runtime-corejs2/core-js/json/stringify.js")); var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/typeof */ "./node_modules/@babel/runtime-corejs2/helpers/typeof.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js")); var _getPrototypeOf3 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/getPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js")); var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/inherits */ "./node_modules/@babel/runtime-corejs2/helpers/inherits.js")); var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/assertThisInitialized */ "./node_modules/@babel/runtime-corejs2/helpers/assertThisInitialized.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var _url = __webpack_require__(/*! url */ "./node_modules/url/url.js"); var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "./node_modules/prop-types/index.js")); var _router = _interopRequireWildcard(__webpack_require__(/*! ./router */ "./node_modules/next/dist/lib/router/index.js")); var _utils = __webpack_require__(/*! ./utils */ "./node_modules/next/dist/lib/utils.js"); /* global __NEXT_DATA__ */ function isLocal(href) { var url = (0, _url.parse)(href, false, true); var origin = (0, _url.parse)((0, _utils.getLocationOrigin)(), false, true); return !url.host || url.protocol === origin.protocol && url.host === origin.host; } function memoizedFormatUrl(formatUrl) { var lastHref = null; var lastAs = null; var lastResult = null; return function (href, as) { if (href === lastHref && as === lastAs) { return lastResult; } var result = formatUrl(href, as); lastHref = href; lastAs = as; lastResult = result; return result; }; } var Link = /*#__PURE__*/ function (_Component) { (0, _inherits2.default)(Link, _Component); function Link() { var _getPrototypeOf2; var _this; (0, _classCallCheck2.default)(this, Link); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(Link)).call.apply(_getPrototypeOf2, [this].concat(args))); (0, _defineProperty2.default)((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)), "formatUrls", memoizedFormatUrl(function (href, asHref) { return { href: href && (0, _typeof2.default)(href) === 'object' ? (0, _url.format)(href) : href, as: asHref && (0, _typeof2.default)(asHref) === 'object' ? (0, _url.format)(asHref) : asHref }; })); (0, _defineProperty2.default)((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)), "linkClicked", function (e) { var _e$currentTarget = e.currentTarget, nodeName = _e$currentTarget.nodeName, target = _e$currentTarget.target; if (nodeName === 'A' && (target && target !== '_self' || e.metaKey || e.ctrlKey || e.shiftKey || e.nativeEvent && e.nativeEvent.which === 2)) { // ignore click for new tab / new window behavior return; } var _this$formatUrls = _this.formatUrls(_this.props.href, _this.props.as), href = _this$formatUrls.href, as = _this$formatUrls.as; if (!isLocal(href)) { // ignore click if it's outside our scope return; } var pathname = window.location.pathname; href = (0, _url.resolve)(pathname, href); as = as ? (0, _url.resolve)(pathname, as) : href; e.preventDefault(); // avoid scroll for urls with anchor refs var scroll = _this.props.scroll; if (scroll == null) { scroll = as.indexOf('#') < 0; } // replace state instead of push if prop is present var replace = _this.props.replace; var changeMethod = replace ? 'replace' : 'push'; // straight up redirect _router.default[changeMethod](href, as, { shallow: _this.props.shallow }).then(function (success) { if (!success) return; if (scroll) { window.scrollTo(0, 0); document.body.focus(); } }).catch(function (err) { if (_this.props.onError) _this.props.onError(err); }); }); return _this; } (0, _createClass2.default)(Link, [{ key: "componentDidMount", value: function componentDidMount() { this.prefetch(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if ((0, _stringify.default)(this.props.href) !== (0, _stringify.default)(prevProps.href)) { this.prefetch(); } } // The function is memoized so that no extra lifecycles are needed // as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html }, { key: "prefetch", value: function prefetch() { if (!this.props.prefetch) return; if (typeof window === 'undefined') return; // Prefetch the JSON page if asked (only in the client) var pathname = window.location.pathname; var _this$formatUrls2 = this.formatUrls(this.props.href, this.props.as), parsedHref = _this$formatUrls2.href; var href = (0, _url.resolve)(pathname, parsedHref); _router.default.prefetch(href); } }, { key: "render", value: function render() { var _this2 = this; var children = this.props.children; var _this$formatUrls3 = this.formatUrls(this.props.href, this.props.as), href = _this$formatUrls3.href, as = _this$formatUrls3.as; // Deprecated. Warning shown by propType check. If the childen provided is a string (<Link>example</Link>) we wrap it in an <a> tag if (typeof children === 'string') { children = _react.default.createElement("a", null, children); } // This will return the first child, if multiple are provided it will throw an error var child = _react.Children.only(children); var props = { onClick: function onClick(e) { if (child.props && typeof child.props.onClick === 'function') { child.props.onClick(e); } if (!e.defaultPrevented) { _this2.linkClicked(e); } } // If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is // defined, we specify the current 'href', so that repetition is not needed by the user }; if (this.props.passHref || child.type === 'a' && !('href' in child.props)) { props.href = as || href; } // Add the ending slash to the paths. So, we can serve the // "<page>/index.html" directly. if (props.href && typeof __NEXT_DATA__ !== 'undefined' && __NEXT_DATA__.nextExport) { props.href = (0, _router._rewriteUrlForNextExport)(props.href); } return _react.default.cloneElement(child, props); } }]); return Link; }(_react.Component); if (true) { var warn = (0, _utils.execOnce)(console.error); // This module gets removed by webpack.IgnorePlugin var exact = __webpack_require__(/*! prop-types-exact */ "./node_modules/prop-types-exact/build/index.js"); Link.propTypes = exact({ href: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object]).isRequired, as: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object]), prefetch: _propTypes.default.bool, replace: _propTypes.default.bool, shallow: _propTypes.default.bool, passHref: _propTypes.default.bool, scroll: _propTypes.default.bool, children: _propTypes.default.oneOfType([_propTypes.default.element, function (props, propName) { var value = props[propName]; if (typeof value === 'string') { warn("Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>"); } return null; }]).isRequired }); } var _default = Link; exports.default = _default; /***/ }), /***/ "./node_modules/next/dist/lib/p-queue.js": /*!***********************************************!*\ !*** ./node_modules/next/dist/lib/p-queue.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _promise = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/promise */ "./node_modules/@babel/runtime-corejs2/core-js/promise.js")); var _assign = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/object/assign */ "./node_modules/@babel/runtime-corejs2/core-js/object/assign.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); // based on https://github.com/sindresorhus/p-queue (MIT) // modified for browser support var Queue = /*#__PURE__*/ function () { function Queue() { (0, _classCallCheck2.default)(this, Queue); this._queue = []; } (0, _createClass2.default)(Queue, [{ key: "enqueue", value: function enqueue(run) { this._queue.push(run); } }, { key: "dequeue", value: function dequeue() { return this._queue.shift(); } }, { key: "size", get: function get() { return this._queue.length; } }]); return Queue; }(); var PQueue = /*#__PURE__*/ function () { function PQueue(opts) { (0, _classCallCheck2.default)(this, PQueue); opts = (0, _assign.default)({ concurrency: Infinity, queueClass: Queue }, opts); if (opts.concurrency < 1) { throw new TypeError('Expected `concurrency` to be a number from 1 and up'); } this.queue = new opts.queueClass(); // eslint-disable-line new-cap this._pendingCount = 0; this._concurrency = opts.concurrency; this._resolveEmpty = function () {}; } (0, _createClass2.default)(PQueue, [{ key: "_next", value: function _next() { this._pendingCount--; if (this.queue.size > 0) { this.queue.dequeue()(); } else { this._resolveEmpty(); } } }, { key: "add", value: function add(fn, opts) { var _this = this; return new _promise.default(function (resolve, reject) { var run = function run() { _this._pendingCount++; fn().then(function (val) { resolve(val); _this._next(); }, function (err) { reject(err); _this._next(); }); }; if (_this._pendingCount < _this._concurrency) { run(); } else { _this.queue.enqueue(run, opts); } }); } }, { key: "onEmpty", value: function onEmpty() { var _this2 = this; return new _promise.default(function (resolve) { var existingResolve = _this2._resolveEmpty; _this2._resolveEmpty = function () { existingResolve(); resolve(); }; }); } }, { key: "size", get: function get() { return this.queue.size; } }, { key: "pending", get: function get() { return this._pendingCount; } }]); return PQueue; }(); exports.default = PQueue; /***/ }), /***/ "./node_modules/next/dist/lib/router/index.js": /*!****************************************************!*\ !*** ./node_modules/next/dist/lib/router/index.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports._rewriteUrlForNextExport = _rewriteUrlForNextExport; exports.makePublicRouterInstance = makePublicRouterInstance; Object.defineProperty(exports, "withRouter", { enumerable: true, get: function get() { return _withRouter.default; } }); exports.Router = exports.createRouter = exports.default = void 0; var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/objectSpread */ "./node_modules/@babel/runtime-corejs2/helpers/objectSpread.js")); var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/typeof */ "./node_modules/@babel/runtime-corejs2/helpers/typeof.js")); var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/slicedToArray */ "./node_modules/@babel/runtime-corejs2/helpers/slicedToArray.js")); var _construct2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/construct */ "./node_modules/@babel/runtime-corejs2/helpers/construct.js")); var _defineProperty = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/object/define-property */ "./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js")); var _router = _interopRequireDefault(__webpack_require__(/*! ./router */ "./node_modules/next/dist/lib/router/router.js")); var _utils = __webpack_require__(/*! ../utils */ "./node_modules/next/dist/lib/utils.js"); var _withRouter = _interopRequireDefault(__webpack_require__(/*! ./with-router */ "./node_modules/next/dist/lib/router/with-router.js")); /* global window */ var SingletonRouter = { router: null, // holds the actual router instance readyCallbacks: [], ready: function ready(cb) { if (this.router) return cb(); if (typeof window !== 'undefined') { this.readyCallbacks.push(cb); } } }; // Create public properties and methods of the router in the SingletonRouter var urlPropertyFields = ['pathname', 'route', 'query', 'asPath']; var propertyFields = ['components']; var routerEvents = ['routeChangeStart', 'beforeHistoryChange', 'routeChangeComplete', 'routeChangeError', 'hashChangeStart', 'hashChangeComplete']; var coreMethodFields = ['push', 'replace', 'reload', 'back', 'prefetch', 'beforePopState']; // Events is a static property on the router, the router doesn't have to be initialized to use it Object.defineProperty(SingletonRouter, 'events', { get: function get() { return _router.default.events; } }); propertyFields.concat(urlPropertyFields).forEach(function (field) { // Here we need to use Object.defineProperty because, we need to return // the property assigned to the actual router // The value might get changed as we change routes and this is the // proper way to access it (0, _defineProperty.default)(SingletonRouter, field, { get: function get() { throwIfNoRouter(); return SingletonRouter.router[field]; } }); }); coreMethodFields.forEach(function (field) { SingletonRouter[field] = function () { var _SingletonRouter$rout; throwIfNoRouter(); return (_SingletonRouter$rout = SingletonRouter.router)[field].apply(_SingletonRouter$rout, arguments); }; }); routerEvents.forEach(function (event) { SingletonRouter.ready(function () { _router.default.events.on(event, function () { var eventField = "on".concat(event.charAt(0).toUpperCase()).concat(event.substring(1)); if (SingletonRouter[eventField]) { try { SingletonRouter[eventField].apply(SingletonRouter, arguments); } catch (err) { console.error("Error when running the Router event: ".concat(eventField)); console.error("".concat(err.message, "\n").concat(err.stack)); } } }); }); }); var warnAboutRouterOnAppUpdated = (0, _utils.execOnce)(function () { console.warn("Router.onAppUpdated is removed - visit https://err.sh/zeit/next.js/no-on-app-updated-hook for more information."); }); Object.defineProperty(SingletonRouter, 'onAppUpdated', { get: function get() { return null; }, set: function set() { warnAboutRouterOnAppUpdated(); return null; } }); function throwIfNoRouter() { if (!SingletonRouter.router) { var message = 'No router instance found.\n' + 'You should only use "next/router" inside the client side of your app.\n'; throw new Error(message); } } // Export the SingletonRouter and this is the public API. var _default = SingletonRouter; // Reexport the withRoute HOC exports.default = _default; // INTERNAL APIS // ------------- // (do not use following exports inside the app) // Create a router and assign it as the singleton instance. // This is used in client side when we are initilizing the app. // This should **not** use inside the server. var createRouter = function createRouter() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } SingletonRouter.router = (0, _construct2.default)(_router.default, args); SingletonRouter.readyCallbacks.forEach(function (cb) { return cb(); }); SingletonRouter.readyCallbacks = []; return SingletonRouter.router; }; // Export the actual Router class, which is usually used inside the server exports.createRouter = createRouter; var Router = _router.default; exports.Router = Router; function _rewriteUrlForNextExport(url) { var _url$split = url.split('#'), _url$split2 = (0, _slicedToArray2.default)(_url$split, 2), hash = _url$split2[1]; url = url.replace(/#.*/, ''); var _url$split3 = url.split('?'), _url$split4 = (0, _slicedToArray2.default)(_url$split3, 2), path = _url$split4[0], qs = _url$split4[1]; path = path.replace(/\/$/, ''); var newPath = path; // Append a trailing slash if this path does not have an extension if (!/\.[^/]+\/?$/.test(path)) { newPath = "".concat(path, "/"); } if (qs) { newPath = "".concat(newPath, "?").concat(qs); } if (hash) { newPath = "".concat(newPath, "#").concat(hash); } return newPath; } // This function is used to create the `withRouter` router instance function makePublicRouterInstance(router) { var instance = {}; for (var _i = 0; _i < urlPropertyFields.length; _i++) { var property = urlPropertyFields[_i]; if ((0, _typeof2.default)(router[property]) === 'object') { instance[property] = (0, _objectSpread2.default)({}, router[property]); // makes sure query is not stateful continue; } instance[property] = router[property]; } // Events is a static property on the router, the router doesn't have to be initialized to use it instance.events = _router.default.events; propertyFields.forEach(function (field) { // Here we need to use Object.defineProperty because, we need to return // the property assigned to the actual router // The value might get changed as we change routes and this is the // proper way to access it (0, _defineProperty.default)(instance, field, { get: function get() { return router[field]; } }); }); coreMethodFields.forEach(function (field) { instance[field] = function () { return router[field].apply(router, arguments); }; }); return instance; } /***/ }), /***/ "./node_modules/next/dist/lib/router/router.js": /*!*****************************************************!*\ !*** ./node_modules/next/dist/lib/router/router.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/slicedToArray */ "./node_modules/@babel/runtime-corejs2/helpers/slicedToArray.js")); var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/typeof */ "./node_modules/@babel/runtime-corejs2/helpers/typeof.js")); var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/regenerator */ "./node_modules/@babel/runtime-corejs2/regenerator/index.js")); var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/asyncToGenerator */ "./node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js")); var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/objectSpread */ "./node_modules/@babel/runtime-corejs2/helpers/objectSpread.js")); var _set = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/set */ "./node_modules/@babel/runtime-corejs2/core-js/set.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var _url2 = __webpack_require__(/*! url */ "./node_modules/url/url.js"); var _EventEmitter = _interopRequireDefault(__webpack_require__(/*! ../EventEmitter */ "./node_modules/next/dist/lib/EventEmitter.js")); var _shallowEquals = _interopRequireDefault(__webpack_require__(/*! ../shallow-equals */ "./node_modules/next/dist/lib/shallow-equals.js")); var _pQueue = _interopRequireDefault(__webpack_require__(/*! ../p-queue */ "./node_modules/next/dist/lib/p-queue.js")); var _utils = __webpack_require__(/*! ../utils */ "./node_modules/next/dist/lib/utils.js"); var _ = __webpack_require__(/*! ./ */ "./node_modules/next/dist/lib/router/index.js"); /* global __NEXT_DATA__ */ var Router = /*#__PURE__*/ function () { function Router(_pathname, _query, _as2) { var _this = this; var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, initialProps = _ref.initialProps, pageLoader = _ref.pageLoader, App = _ref.App, Component = _ref.Component, ErrorComponent = _ref.ErrorComponent, err = _ref.err; (0, _classCallCheck2.default)(this, Router); (0, _defineProperty2.default)(this, "onPopState", function (e) { if (!e.state) { // We get state as undefined for two reasons. // 1. With older safari (< 8) and older chrome (< 34) // 2. When the URL changed with # // // In the both cases, we don't need to proceed and change the route. // (as it's already changed) // But we can simply replace the state with the new changes. // Actually, for (1) we don't need to nothing. But it's hard to detect that event. // So, doing the following for (1) does no harm. var pathname = _this.pathname, query = _this.query; _this.changeState('replaceState', (0, _url2.format)({ pathname: pathname, query: query }), (0, _utils.getURL)()); return; } // If the downstream application returns falsy, return. // They will then be responsible for handling the event. if (!_this._beforePopState(e.state)) { return; } var _e$state = e.state, url = _e$state.url, as = _e$state.as, options = _e$state.options; if (true) { if (typeof url === 'undefined' || typeof as === 'undefined') { console.warn('`popstate` event triggered but `event.state` did not have `url` or `as` https://err.sh/zeit/next.js/popstate-state-empty'); } } _this.replace(url, as, options); }); // represents the current component key this.route = toRoute(_pathname); // set up the component cache (by route keys) this.components = {}; // We should not keep the cache, if there's an error // Otherwise, this cause issues when when going back and // come again to the errored page. if (Component !== ErrorComponent) { this.components[this.route] = { Component: Component, props: initialProps, err: err }; } this.components['/_app'] = { Component: App // Backwards compat for Router.router.events // TODO: Should be remove the following major version as it was never documented }; this.events = Router.events; this.pageLoader = pageLoader; this.prefetchQueue = new _pQueue.default({ concurrency: 2 }); this.ErrorComponent = ErrorComponent; this.pathname = _pathname; this.query = _query; this.asPath = _as2; this.subscriptions = new _set.default(); this.componentLoadCancel = null; this._beforePopState = function () { return true; }; if (typeof window !== 'undefined') { // in order for `e.state` to work on the `onpopstate` event // we have to register the initial route upon initialization this.changeState('replaceState', (0, _url2.format)({ pathname: _pathname, query: _query }), (0, _utils.getURL)()); window.addEventListener('popstate', this.onPopState); } } (0, _createClass2.default)(Router, [{ key: "update", value: function update(route, Component) { var data = this.components[route]; if (!data) { throw new Error("Cannot update unavailable route: ".concat(route)); } var newData = (0, _objectSpread2.default)({}, data, { Component: Component }); this.components[route] = newData; // pages/_app.js updated if (route === '/_app') { this.notify(this.components[this.route]); return; } if (route === this.route) { this.notify(newData); } } }, { key: "reload", value: function () { var _reload = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee(route) { var pathname, query, url, as, routeInfo, error; return _regenerator.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: delete this.components[route]; this.pageLoader.clearCache(route); if (!(route !== this.route)) { _context.next = 4; break; } return _context.abrupt("return"); case 4: pathname = this.pathname, query = this.query; url = window.location.href; // This makes sure we only use pathname + query + hash, to mirror `asPath` coming from the server. as = window.location.pathname + window.location.search + window.location.hash; Router.events.emit('routeChangeStart', url); _context.next = 10; return this.getRouteInfo(route, pathname, query, as); case 10: routeInfo = _context.sent; error = routeInfo.error; if (!(error && error.cancelled)) { _context.next = 14; break; } return _context.abrupt("return"); case 14: this.notify(routeInfo); if (!error) { _context.next = 18; break; } Router.events.emit('routeChangeError', error, url); throw error; case 18: Router.events.emit('routeChangeComplete', url); case 19: case "end": return _context.stop(); } } }, _callee, this); })); return function reload(_x) { return _reload.apply(this, arguments); }; }() }, { key: "back", value: function back() { window.history.back(); } }, { key: "push", value: function push(url) { var as = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : url; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return this.change('pushState', url, as, options); } }, { key: "replace", value: function replace(url) { var as = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : url; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return this.change('replaceState', url, as, options); } }, { key: "change", value: function () { var _change = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee2(method, _url, _as, options) { var url, as, _parse, asPathname, asQuery, _parse2, pathname, query, route, _options$shallow, shallow, routeInfo, _routeInfo, error, hash; return _regenerator.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // If url and as provided as an object representation, // we'll format them into the string version here. url = (0, _typeof2.default)(_url) === 'object' ? (0, _url2.format)(_url) : _url; as = (0, _typeof2.default)(_as) === 'object' ? (0, _url2.format)(_as) : _as; // Add the ending slash to the paths. So, we can serve the // "<page>/index.html" directly for the SSR page. if (__NEXT_DATA__.nextExport) { as = (0, _._rewriteUrlForNextExport)(as); } this.abortComponentLoad(as); // If the url change is only related to a hash change // We should not proceed. We should only change the state. if (!this.onlyAHashChange(as)) { _context2.next = 10; break; } Router.events.emit('hashChangeStart', as); this.changeState(method, url, as); this.scrollToHash(as); Router.events.emit('hashChangeComplete', as); return _context2.abrupt("return", true); case 10: _parse = (0, _url2.parse)(as, true), asPathname = _parse.pathname, asQuery = _parse.query; _parse2 = (0, _url2.parse)(url, true), pathname = _parse2.pathname, query = _parse2.query; // If asked to change the current URL we should reload the current page // (not location.reload() but reload getInitialProps and other Next.js stuffs) // We also need to set the method = replaceState always // as this should not go into the history (That's how browsers work) if (!this.urlIsNew(asPathname, asQuery)) { method = 'replaceState'; } route = toRoute(pathname); _options$shallow = options.shallow, shallow = _options$shallow === void 0 ? false : _options$shallow; routeInfo = null; Router.events.emit('routeChangeStart', as); // If shallow === false and other conditions met, we reuse the // existing routeInfo for this route. // Because of this, getInitialProps would not run. if (!(shallow && this.isShallowRoutingPossible(route))) { _context2.next = 21; break; } routeInfo = this.components[route]; _context2.next = 24; break; case 21: _context2.next = 23; return this.getRouteInfo(route, pathname, query, as); case 23: routeInfo = _context2.sent; case 24: _routeInfo = routeInfo, error = _routeInfo.error; if (!(error && error.cancelled)) { _context2.next = 27; break; } return _context2.abrupt("return", false); case 27: Router.events.emit('beforeHistoryChange', as); this.changeState(method, url, as, options); hash = window.location.hash.substring(1); this.set(route, pathname, query, as, (0, _objectSpread2.default)({}, routeInfo, { hash: hash })); if (!error) { _context2.next = 34; break; } Router.events.emit('routeChangeError', error, as); throw error; case 34: Router.events.emit('routeChangeComplete', as); return _context2.abrupt("return", true); case 36: case "end": return _context2.stop(); } } }, _callee2, this); })); return function change(_x2, _x3, _x4, _x5) { return _change.apply(this, arguments); }; }() }, { key: "changeState", value: function changeState(method, url, as) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (true) { if (typeof window.history === 'undefined') { console.error("Warning: window.history is not available."); return; } if (typeof window.history[method] === 'undefined') { console.error("Warning: window.history.".concat(method, " is not available")); return; } } if (method !== 'pushState' || (0, _utils.getURL)() !== as) { window.history[method]({ url: url, as: as, options: options }, null, as); } } }, { key: "getRouteInfo", value: function () { var _getRouteInfo = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee3(route, pathname, query, as) { var routeInfo, _routeInfo2, Component, ctx, _Component, _ctx; return _regenerator.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: routeInfo = null; _context3.prev = 1; routeInfo = this.components[route]; if (routeInfo) { _context3.next = 8; break; } _context3.next = 6; return this.fetchComponent(route, as); case 6: _context3.t0 = _context3.sent; routeInfo = { Component: _context3.t0 }; case 8: _routeInfo2 = routeInfo, Component = _routeInfo2.Component; if (!(typeof Component !== 'function')) { _context3.next = 11; break; } throw new Error("The default export is not a React Component in page: \"".concat(pathname, "\"")); case 11: ctx = { pathname: pathname, query: query, asPath: as }; _context3.next = 14; return this.getInitialProps(Component, ctx); case 14: routeInfo.props = _context3.sent; this.components[route] = routeInfo; _context3.next = 40; break; case 18: _context3.prev = 18; _context3.t1 = _context3["catch"](1); if (!(_context3.t1.code === 'PAGE_LOAD_ERROR')) { _context3.next = 24; break; } // If we can't load the page it could be one of following reasons // 1. Page doesn't exists // 2. Page does exist in a different zone // 3. Internal error while loading the page // So, doing a hard reload is the proper way to deal with this. window.location.href = as; // Changing the URL doesn't block executing the current code path. // So, we need to mark it as a cancelled error and stop the routing logic. _context3.t1.cancelled = true; return _context3.abrupt("return", { error: _context3.t1 }); case 24: if (!_context3.t1.cancelled) { _context3.next = 26; break; } return _context3.abrupt("return", { error: _context3.t1 }); case 26: _Component = this.ErrorComponent; routeInfo = { Component: _Component, err: _context3.t1 }; _ctx = { err: _context3.t1, pathname: pathname, query: query }; _context3.prev = 29; _context3.next = 32; return this.getInitialProps(_Component, _ctx); case 32: routeInfo.props = _context3.sent; _context3.next = 39; break; case 35: _context3.prev = 35; _context3.t2 = _context3["catch"](29); console.error('Error in error page `getInitialProps`: ', _context3.t2); routeInfo.props = {}; case 39: routeInfo.error = _context3.t1; case 40: return _context3.abrupt("return", routeInfo); case 41: case "end": return _context3.stop(); } } }, _callee3, this, [[1, 18], [29, 35]]); })); return function getRouteInfo(_x6, _x7, _x8, _x9) { return _getRouteInfo.apply(this, arguments); }; }() }, { key: "set", value: function set(route, pathname, query, as, data) { this.route = route; this.pathname = pathname; this.query = query; this.asPath = as; this.notify(data); } }, { key: "beforePopState", value: function beforePopState(cb) { this._beforePopState = cb; } }, { key: "onlyAHashChange", value: function onlyAHashChange(as) { if (!this.asPath) return false; var _this$asPath$split = this.asPath.split('#'), _this$asPath$split2 = (0, _slicedToArray2.default)(_this$asPath$split, 2), oldUrlNoHash = _this$asPath$split2[0], oldHash = _this$asPath$split2[1]; var _as$split = as.split('#'), _as$split2 = (0, _slicedToArray2.default)(_as$split, 2), newUrlNoHash = _as$split2[0], newHash = _as$split2[1]; // Makes sure we scroll to the provided hash if the url/hash are the same if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) { return true; } // If the urls are change, there's more than a hash change if (oldUrlNoHash !== newUrlNoHash) { return false; } // If the hash has changed, then it's a hash only change. // This check is necessary to handle both the enter and // leave hash === '' cases. The identity case falls through // and is treated as a next reload. return oldHash !== newHash; } }, { key: "scrollToHash", value: function scrollToHash(as) { var _as$split3 = as.split('#'), _as$split4 = (0, _slicedToArray2.default)(_as$split3, 2), hash = _as$split4[1]; // Scroll to top if the hash is just `#` with no value if (hash === '') { window.scrollTo(0, 0); return; } // First we check if the element by id is found var idEl = document.getElementById(hash); if (idEl) { idEl.scrollIntoView(); return; } // If there's no element with the id, we check the `name` property // To mirror browsers var nameEl = document.getElementsByName(hash)[0]; if (nameEl) { nameEl.scrollIntoView(); } } }, { key: "urlIsNew", value: function urlIsNew(pathname, query) { return this.pathname !== pathname || !(0, _shallowEquals.default)(query, this.query); } }, { key: "isShallowRoutingPossible", value: function isShallowRoutingPossible(route) { return (// If there's cached routeInfo for the route. Boolean(this.components[route]) && // If the route is already rendered on the screen. this.route === route ); } }, { key: "prefetch", value: function () { var _prefetch = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee4(url) { var _this2 = this; var _parse3, pathname, route; return _regenerator.default.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (false) {} return _context4.abrupt("return"); case 2: _parse3 = (0, _url2.parse)(url), pathname = _parse3.pathname; route = toRoute(pathname); return _context4.abrupt("return", this.prefetchQueue.add(function () { return _this2.fetchRoute(route); })); case 5: case "end": return _context4.stop(); } } }, _callee4, this); })); return function prefetch(_x10) { return _prefetch.apply(this, arguments); }; }() }, { key: "fetchComponent", value: function () { var _fetchComponent = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee5(route, as) { var cancelled, cancel, Component, error; return _regenerator.default.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: cancelled = false; cancel = this.componentLoadCancel = function () { cancelled = true; }; _context5.next = 4; return this.fetchRoute(route); case 4: Component = _context5.sent; if (!cancelled) { _context5.next = 9; break; } error = new Error("Abort fetching component for route: \"".concat(route, "\"")); error.cancelled = true; throw error; case 9: if (cancel === this.componentLoadCancel) { this.componentLoadCancel = null; } return _context5.abrupt("return", Component); case 11: case "end": return _context5.stop(); } } }, _callee5, this); })); return function fetchComponent(_x11, _x12) { return _fetchComponent.apply(this, arguments); }; }() }, { key: "getInitialProps", value: function () { var _getInitialProps = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee6(Component, ctx) { var cancelled, cancel, App, props, err; return _regenerator.default.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: cancelled = false; cancel = function cancel() { cancelled = true; }; this.componentLoadCancel = cancel; App = this.components['/_app'].Component; _context6.next = 6; return (0, _utils.loadGetInitialProps)(App, { Component: Component, router: this, ctx: ctx }); case 6: props = _context6.sent; if (cancel === this.componentLoadCancel) { this.componentLoadCancel = null; } if (!cancelled) { _context6.next = 12; break; } err = new Error('Loading initial props cancelled'); err.cancelled = true; throw err; case 12: return _context6.abrupt("return", props); case 13: case "end": return _context6.stop(); } } }, _callee6, this); })); return function getInitialProps(_x13, _x14) { return _getInitialProps.apply(this, arguments); }; }() }, { key: "fetchRoute", value: function () { var _fetchRoute = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee7(route) { return _regenerator.default.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: return _context7.abrupt("return", this.pageLoader.loadPage(route)); case 1: case "end": return _context7.stop(); } } }, _callee7, this); })); return function fetchRoute(_x15) { return _fetchRoute.apply(this, arguments); }; }() }, { key: "abortComponentLoad", value: function abortComponentLoad(as) { if (this.componentLoadCancel) { Router.events.emit('routeChangeError', new Error('Route Cancelled'), as); this.componentLoadCancel(); this.componentLoadCancel = null; } } }, { key: "notify", value: function notify(data) { var App = this.components['/_app'].Component; this.subscriptions.forEach(function (fn) { return fn((0, _objectSpread2.default)({}, data, { App: App })); }); } }, { key: "subscribe", value: function subscribe(fn) { var _this3 = this; this.subscriptions.add(fn); return function () { return _this3.subscriptions.delete(fn); }; } }]); return Router; }(); exports.default = Router; (0, _defineProperty2.default)(Router, "events", new _EventEmitter.default()); function toRoute(path) { return path.replace(/\/$/, '') || '/'; } /***/ }), /***/ "./node_modules/next/dist/lib/router/with-router.js": /*!**********************************************************!*\ !*** ./node_modules/next/dist/lib/router/with-router.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireWildcard */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireWildcard.js"); var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = withRouter; var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/objectSpread */ "./node_modules/@babel/runtime-corejs2/helpers/objectSpread.js")); var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js")); var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/getPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js")); var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/inherits */ "./node_modules/@babel/runtime-corejs2/helpers/inherits.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _propTypes = _interopRequireDefault(__webpack_require__(/*! prop-types */ "./node_modules/prop-types/index.js")); var _hoistNonReactStatics = _interopRequireDefault(__webpack_require__(/*! hoist-non-react-statics */ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js")); var _utils = __webpack_require__(/*! ../utils */ "./node_modules/next/dist/lib/utils.js"); function withRouter(ComposedComponent) { var displayName = (0, _utils.getDisplayName)(ComposedComponent); var WithRouteWrapper = /*#__PURE__*/ function (_Component) { (0, _inherits2.default)(WithRouteWrapper, _Component); function WithRouteWrapper() { (0, _classCallCheck2.default)(this, WithRouteWrapper); return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(WithRouteWrapper).apply(this, arguments)); } (0, _createClass2.default)(WithRouteWrapper, [{ key: "render", value: function render() { var props = (0, _objectSpread2.default)({ router: this.context.router }, this.props); return _react.default.createElement(ComposedComponent, props); } }]); return WithRouteWrapper; }(_react.Component); (0, _defineProperty2.default)(WithRouteWrapper, "contextTypes", { router: _propTypes.default.object }); (0, _defineProperty2.default)(WithRouteWrapper, "displayName", "withRouter(".concat(displayName, ")")); return (0, _hoistNonReactStatics.default)(WithRouteWrapper, ComposedComponent); } /***/ }), /***/ "./node_modules/next/dist/lib/shallow-equals.js": /*!******************************************************!*\ !*** ./node_modules/next/dist/lib/shallow-equals.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = shallowEquals; function shallowEquals(a, b) { for (var i in a) { if (b[i] !== a[i]) return false; } for (var _i in b) { if (b[_i] !== a[_i]) return false; } return true; } /***/ }), /***/ "./node_modules/next/dist/lib/side-effect.js": /*!***************************************************!*\ !*** ./node_modules/next/dist/lib/side-effect.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireWildcard */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireWildcard.js"); var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = withSideEffect; var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/classCallCheck */ "./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js")); var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime-corejs2/helpers/possibleConstructorReturn.js")); var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/getPrototypeOf */ "./node_modules/@babel/runtime-corejs2/helpers/getPrototypeOf.js")); var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/createClass */ "./node_modules/@babel/runtime-corejs2/helpers/createClass.js")); var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/inherits */ "./node_modules/@babel/runtime-corejs2/helpers/inherits.js")); var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/assertThisInitialized */ "./node_modules/@babel/runtime-corejs2/helpers/assertThisInitialized.js")); var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/defineProperty */ "./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js")); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/toConsumableArray */ "./node_modules/@babel/runtime-corejs2/helpers/toConsumableArray.js")); var _set = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/core-js/set */ "./node_modules/@babel/runtime-corejs2/core-js/set.js")); var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _utils = __webpack_require__(/*! ./utils */ "./node_modules/next/dist/lib/utils.js"); function withSideEffect(reduceComponentsToState, handleStateChangeOnClient, mapStateOnServer) { if (typeof reduceComponentsToState !== 'function') { throw new Error('Expected reduceComponentsToState to be a function.'); } if (typeof handleStateChangeOnClient !== 'function') { throw new Error('Expected handleStateChangeOnClient to be a function.'); } if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') { throw new Error('Expected mapStateOnServer to either be undefined or a function.'); } return function wrap(WrappedComponent) { if (typeof WrappedComponent !== 'function') { throw new Error('Expected WrappedComponent to be a React component.'); } var mountedInstances = new _set.default(); var state; function emitChange(component) { state = reduceComponentsToState((0, _toConsumableArray2.default)(mountedInstances)); if (SideEffect.canUseDOM) { handleStateChangeOnClient.call(component, state); } else if (mapStateOnServer) { state = mapStateOnServer(state); } } var SideEffect = /*#__PURE__*/ function (_Component) { (0, _inherits2.default)(SideEffect, _Component); (0, _createClass2.default)(SideEffect, null, [{ key: "peek", // Expose canUseDOM so tests can monkeypatch it // Try to use displayName of wrapped component value: function peek() { return state; } }, { key: "rewind", value: function rewind() { if (SideEffect.canUseDOM) { throw new Error('You may only call rewind() on the server. Call peek() to read the current state.'); } var recordedState = state; state = undefined; mountedInstances.clear(); return recordedState; } }]); function SideEffect(props) { var _this; (0, _classCallCheck2.default)(this, SideEffect); _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(SideEffect).call(this, props)); if (!SideEffect.canUseDOM) { mountedInstances.add((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this))); emitChange((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this))); } return _this; } (0, _createClass2.default)(SideEffect, [{ key: "componentDidMount", value: function componentDidMount() { mountedInstances.add(this); emitChange(this); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { emitChange(this); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { mountedInstances.delete(this); emitChange(this); } }, { key: "render", value: function render() { return _react.default.createElement(WrappedComponent, null, this.props.children); } }]); return SideEffect; }(_react.Component); (0, _defineProperty2.default)(SideEffect, "canUseDOM", typeof window !== 'undefined'); (0, _defineProperty2.default)(SideEffect, "contextTypes", WrappedComponent.contextTypes); (0, _defineProperty2.default)(SideEffect, "displayName", "SideEffect(".concat((0, _utils.getDisplayName)(WrappedComponent), ")")); return SideEffect; }; } /***/ }), /***/ "./node_modules/next/dist/lib/utils.js": /*!*********************************************!*\ !*** ./node_modules/next/dist/lib/utils.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(/*! @babel/runtime-corejs2/helpers/interopRequireDefault */ "./node_modules/@babel/runtime-corejs2/helpers/interopRequireDefault.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.execOnce = execOnce; exports.getDisplayName = getDisplayName; exports.isResSent = isResSent; exports.loadGetInitialProps = loadGetInitialProps; exports.getLocationOrigin = getLocationOrigin; exports.getURL = getURL; var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/regenerator */ "./node_modules/@babel/runtime-corejs2/regenerator/index.js")); var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime-corejs2/helpers/asyncToGenerator */ "./node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js")); function execOnce(fn) { var _this = this; var used = false; return function () { if (!used) { used = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } fn.apply(_this, args); } }; } function getDisplayName(Component) { if (typeof Component === 'string') { return Component; } return Component.displayName || Component.name || 'Unknown'; } function isResSent(res) { return res.finished || res.headersSent; } function loadGetInitialProps(_x, _x2) { return _loadGetInitialProps.apply(this, arguments); } function _loadGetInitialProps() { _loadGetInitialProps = (0, _asyncToGenerator2.default)( /*#__PURE__*/ _regenerator.default.mark(function _callee(Component, ctx) { var compName, message, props, _compName, _message; return _regenerator.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (false) {} if (!(Component.prototype && Component.prototype.getInitialProps)) { _context.next = 5; break; } compName = getDisplayName(Component); message = "\"".concat(compName, ".getInitialProps()\" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information."); throw new Error(message); case 5: if (Component.getInitialProps) { _context.next = 7; break; } return _context.abrupt("return", {}); case 7: _context.next = 9; return Component.getInitialProps(ctx); case 9: props = _context.sent; if (!(ctx.res && isResSent(ctx.res))) { _context.next = 12; break; } return _context.abrupt("return", props); case 12: if (props) { _context.next = 16; break; } _compName = getDisplayName(Component); _message = "\"".concat(_compName, ".getInitialProps()\" should resolve to an object. But found \"").concat(props, "\" instead."); throw new Error(_message); case 16: return _context.abrupt("return", props); case 17: case "end": return _context.stop(); } } }, _callee, this); })); return _loadGetInitialProps.apply(this, arguments); } function getLocationOrigin() { var _window$location = window.location, protocol = _window$location.protocol, hostname = _window$location.hostname, port = _window$location.port; return "".concat(protocol, "//").concat(hostname).concat(port ? ':' + port : ''); } function getURL() { var href = window.location.href; var origin = getLocationOrigin(); return href.substring(origin.length); } /***/ }), /***/ "./node_modules/next/head.js": /*!***********************************!*\ !*** ./node_modules/next/head.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./dist/lib/head */ "./node_modules/next/dist/lib/head.js") /***/ }), /***/ "./node_modules/next/link.js": /*!***********************************!*\ !*** ./node_modules/next/link.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./dist/lib/link */ "./node_modules/next/dist/lib/link.js") /***/ }), /***/ "./node_modules/node-libs-browser/node_modules/punycode/punycode.js": /*!**************************************************************************!*\ !*** ./node_modules/node-libs-browser/node_modules/punycode/punycode.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return punycode; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "./node_modules/object-assign/index.js": /*!***************************************************************************************************!*\ !*** delegated ./node_modules/object-assign/index.js from dll-reference dll_b2d9fd95b535cd8bf589 ***! \***************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference dll_b2d9fd95b535cd8bf589 */ "dll-reference dll_b2d9fd95b535cd8bf589"))("./node_modules/object-assign/index.js"); /***/ }), /***/ "./node_modules/object-keys/index.js": /*!*******************************************!*\ !*** ./node_modules/object-keys/index.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(/*! ./isArguments */ "./node_modules/object-keys/isArguments.js"); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /***/ "./node_modules/object-keys/isArguments.js": /*!*************************************************!*\ !*** ./node_modules/object-keys/isArguments.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /***/ "./node_modules/object.assign/implementation.js": /*!******************************************************!*\ !*** ./node_modules/object.assign/implementation.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es6-shim var keys = __webpack_require__(/*! object-keys */ "./node_modules/object-keys/index.js"); var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = __webpack_require__(/*! has-symbols/shams */ "./node_modules/has-symbols/shams.js")(); var toObject = Object; var push = bind.call(Function.call, Array.prototype.push); var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; module.exports = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms, value, key; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); if (getSymbols) { syms = getSymbols(source); for (i = 0; i < syms.length; ++i) { key = syms[i]; if (propIsEnumerable(source, key)) { push(props, key); } } } for (i = 0; i < props.length; ++i) { key = props[i]; value = source[key]; if (propIsEnumerable(source, key)) { objTarget[key] = value; } } } return objTarget; }; /***/ }), /***/ "./node_modules/object.assign/index.js": /*!*********************************************!*\ !*** ./node_modules/object.assign/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defineProperties = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js"); var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object.assign/implementation.js"); var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object.assign/polyfill.js"); var shim = __webpack_require__(/*! ./shim */ "./node_modules/object.assign/shim.js"); var polyfill = getPolyfill(); defineProperties(polyfill, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = polyfill; /***/ }), /***/ "./node_modules/object.assign/polyfill.js": /*!************************************************!*\ !*** ./node_modules/object.assign/polyfill.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object.assign/implementation.js"); var lacksProperEnumerationOrder = function () { if (!Object.assign) { return false; } // v8, specifically in node 4.x, has a bug with incorrect property enumeration order // note: this does not detect the bug unless there's 20 characters var str = 'abcdefghijklmnopqrst'; var letters = str.split(''); var map = {}; for (var i = 0; i < letters.length; ++i) { map[letters[i]] = letters[i]; } var obj = Object.assign({}, map); var actual = ''; for (var k in obj) { actual += k; } return str !== actual; }; var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } return false; }; module.exports = function getPolyfill() { if (!Object.assign) { return implementation; } if (lacksProperEnumerationOrder()) { return implementation; } if (assignHasPendingExceptions()) { return implementation; } return Object.assign; }; /***/ }), /***/ "./node_modules/object.assign/shim.js": /*!********************************************!*\ !*** ./node_modules/object.assign/shim.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js"); var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object.assign/polyfill.js"); module.exports = function shimAssign() { var polyfill = getPolyfill(); define( Object, { assign: polyfill }, { assign: function () { return Object.assign !== polyfill; } } ); return polyfill; }; /***/ }), /***/ "./node_modules/prop-types-exact/build/helpers/isPlainObject.js": /*!**********************************************************************!*\ !*** ./node_modules/prop-types-exact/build/helpers/isPlainObject.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports['default'] = isPlainObject; function isPlainObject(x) { return x && (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && !Array.isArray(x); } module.exports = exports['default']; //# sourceMappingURL=isPlainObject.js.map /***/ }), /***/ "./node_modules/prop-types-exact/build/index.js": /*!******************************************************!*\ !*** ./node_modules/prop-types-exact/build/index.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = forbidExtraProps; var _object = __webpack_require__(/*! object.assign */ "./node_modules/object.assign/index.js"); var _object2 = _interopRequireDefault(_object); var _has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js"); var _has2 = _interopRequireDefault(_has); var _isPlainObject = __webpack_require__(/*! ./helpers/isPlainObject */ "./node_modules/prop-types-exact/build/helpers/isPlainObject.js"); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var zeroWidthSpace = '\u200B'; var specialProperty = 'prop-types-exact: ' + zeroWidthSpace; var semaphore = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? Symbol['for'](specialProperty) : /* istanbul ignore next */specialProperty; function brand(fn) { return (0, _object2['default'])(fn, _defineProperty({}, specialProperty, semaphore)); } function isBranded(value) { return value && value[specialProperty] === semaphore; } function forbidExtraProps(propTypes) { if (!(0, _isPlainObject2['default'])(propTypes)) { throw new TypeError('given propTypes must be an object'); } if ((0, _has2['default'])(propTypes, specialProperty) && !isBranded(propTypes[specialProperty])) { throw new TypeError('Against all odds, you created a propType for a prop that uses both the zero-width space and our custom string - which, sadly, conflicts with `prop-types-exact`'); } return (0, _object2['default'])({}, propTypes, _defineProperty({}, specialProperty, brand(function () { function forbidUnknownProps(props, _, componentName) { var unknownProps = Object.keys(props).filter(function (prop) { return !(0, _has2['default'])(propTypes, prop); }); if (unknownProps.length > 0) { return new TypeError(String(componentName) + ': unknown props found: ' + String(unknownProps.join(', '))); } return null; } return forbidUnknownProps; }()))); } module.exports = exports['default']; //# sourceMappingURL=index.js.map /***/ }), /***/ "./node_modules/prop-types/checkPropTypes.js": /*!*********************************************************************************************************!*\ !*** delegated ./node_modules/prop-types/checkPropTypes.js from dll-reference dll_b2d9fd95b535cd8bf589 ***! \*********************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference dll_b2d9fd95b535cd8bf589 */ "dll-reference dll_b2d9fd95b535cd8bf589"))("./node_modules/prop-types/checkPropTypes.js"); /***/ }), /***/ "./node_modules/prop-types/factoryWithTypeCheckers.js": /*!************************************************************!*\ !*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js"); var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); var checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ "./node_modules/prop-types/checkPropTypes.js"); var printWarning = function() {}; if (true) { printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if ("development" !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { true ? printWarning('Invalid argument supplied to oneOf, expected an instance of array.') : undefined; return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined; return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /***/ "./node_modules/prop-types/index.js": /*!******************************************!*\ !*** ./node_modules/prop-types/index.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ "./node_modules/prop-types/factoryWithTypeCheckers.js")(isValidElement, throwOnDirectAccess); } else {} /***/ }), /***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js": /*!*******************************************************************************************************************!*\ !*** delegated ./node_modules/prop-types/lib/ReactPropTypesSecret.js from dll-reference dll_b2d9fd95b535cd8bf589 ***! \*******************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference dll_b2d9fd95b535cd8bf589 */ "dll-reference dll_b2d9fd95b535cd8bf589"))("./node_modules/prop-types/lib/ReactPropTypesSecret.js"); /***/ }), /***/ "./node_modules/querystring-es3/decode.js": /*!************************************************!*\ !*** ./node_modules/querystring-es3/decode.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ "./node_modules/querystring-es3/encode.js": /*!************************************************!*\ !*** ./node_modules/querystring-es3/encode.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }), /***/ "./node_modules/querystring-es3/index.js": /*!***********************************************!*\ !*** ./node_modules/querystring-es3/index.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.decode = exports.parse = __webpack_require__(/*! ./decode */ "./node_modules/querystring-es3/decode.js"); exports.encode = exports.stringify = __webpack_require__(/*! ./encode */ "./node_modules/querystring-es3/encode.js"); /***/ }), /***/ "./node_modules/react/index.js": /*!*******************************************************************************************!*\ !*** delegated ./node_modules/react/index.js from dll-reference dll_b2d9fd95b535cd8bf589 ***! \*******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference dll_b2d9fd95b535cd8bf589 */ "dll-reference dll_b2d9fd95b535cd8bf589"))("./node_modules/react/index.js"); /***/ }), /***/ "./node_modules/regenerator-runtime/runtime-module.js": /*!************************************************************!*\ !*** ./node_modules/regenerator-runtime/runtime-module.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This method of obtaining a reference to the global object needs to be // kept identical to the way it is obtained in runtime.js var g = (function() { return this || (typeof self === "object" && self); })() || Function("return this")(); // Use `getOwnPropertyNames` because not all browsers support calling // `hasOwnProperty` on the global `self` object in a worker. See #183. var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; // Save the old regeneratorRuntime in case it needs to be restored later. var oldRuntime = hadRuntime && g.regeneratorRuntime; // Force reevalutation of runtime.js. g.regeneratorRuntime = undefined; module.exports = __webpack_require__(/*! ./runtime */ "./node_modules/regenerator-runtime/runtime.js"); if (hadRuntime) { // Restore the original runtime. g.regeneratorRuntime = oldRuntime; } else { // Remove the global property added by runtime.js. try { delete g.regeneratorRuntime; } catch(e) { g.regeneratorRuntime = undefined; } } /***/ }), /***/ "./node_modules/regenerator-runtime/runtime.js": /*!*****************************************************!*\ !*** ./node_modules/regenerator-runtime/runtime.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ !(function(global) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. runtime.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return Promise.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { if (delegate.iterator.return) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; })( // In sloppy mode, unbound `this` refers to the global object, fallback to // Function constructor if we're in global strict mode. That is sadly a form // of indirect eval which violates Content Security Policy. (function() { return this || (typeof self === "object" && self); })() || Function("return this")() ); /***/ }), /***/ "./node_modules/url/url.js": /*!*********************************!*\ !*** ./node_modules/url/url.js ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = __webpack_require__(/*! punycode */ "./node_modules/node-libs-browser/node_modules/punycode/punycode.js"); var util = __webpack_require__(/*! ./util */ "./node_modules/url/util.js"); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = __webpack_require__(/*! querystring */ "./node_modules/querystring-es3/index.js"); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; /***/ }), /***/ "./node_modules/url/util.js": /*!**********************************!*\ !*** ./node_modules/url/util.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; /***/ }), /***/ "./node_modules/webpack/buildin/global.js": /*!******************************************************************************************************!*\ !*** delegated ./node_modules/webpack/buildin/global.js from dll-reference dll_b2d9fd95b535cd8bf589 ***! \******************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference dll_b2d9fd95b535cd8bf589 */ "dll-reference dll_b2d9fd95b535cd8bf589"))("./node_modules/webpack/buildin/global.js"); /***/ }), /***/ "./node_modules/webpack/buildin/harmony-module.js": /*!*******************************************!*\ !*** (webpack)/buildin/harmony-module.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(originalModule) { if (!originalModule.webpackPolyfill) { var module = Object.create(originalModule); // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); Object.defineProperty(module, "exports", { enumerable: true }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "./node_modules/webpack/buildin/module.js": /*!***********************************!*\ !*** (webpack)/buildin/module.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(module) { if (!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "./pages/index.js": /*!************************!*\ !*** ./pages/index.js ***! \************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./config.js"); /* harmony import */ var next_head__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! next/head */ "./node_modules/next/head.js"); /* harmony import */ var next_head__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_head__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! next/link */ "./node_modules/next/link.js"); /* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_link__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _components_Footer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/Footer */ "./components/Footer.js"); var _jsxFileName = "/Users/inlife/Projects/inlife.github.io/pages/index.js"; /* harmony default export */ __webpack_exports__["default"] = (function () { return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 8 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(next_head__WEBPACK_IMPORTED_MODULE_2___default.a, { __source: { fileName: _jsxFileName, lineNumber: 9 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("title", { __source: { fileName: _jsxFileName, lineNumber: 10 }, __self: this }, _config__WEBPACK_IMPORTED_MODULE_1__["default"].name)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "header", __source: { fileName: _jsxFileName, lineNumber: 13 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 14 }, __self: this }, "hey!")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "content animated fadeIn", __source: { fileName: _jsxFileName, lineNumber: 17 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "top-bar", __source: { fileName: _jsxFileName, lineNumber: 18 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", { __source: { fileName: _jsxFileName, lineNumber: 19 }, __self: this }, "I'm ", react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("strong", { __source: { fileName: _jsxFileName, lineNumber: 19 }, __self: this }, _config__WEBPACK_IMPORTED_MODULE_1__["default"].name)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", { __source: { fileName: _jsxFileName, lineNumber: 20 }, __self: this }, _config__WEBPACK_IMPORTED_MODULE_1__["default"].role, " ", react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("strong", { __source: { fileName: _jsxFileName, lineNumber: 20 }, __self: this }, "w/"), " >", _config__WEBPACK_IMPORTED_MODULE_1__["default"].yearsOfExp, " years of experience")), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "mid-bar", __source: { fileName: _jsxFileName, lineNumber: 23 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "hashtags", __source: { fileName: _jsxFileName, lineNumber: 24 }, __self: this }, "#backend, #frontend, #mobile, #gamedev"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "links", __source: { fileName: _jsxFileName, lineNumber: 25 }, __self: this }, "my ", react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(next_link__WEBPACK_IMPORTED_MODULE_3___default.a, { prefetch: true, href: "/projects", __source: { fileName: _jsxFileName, lineNumber: 26 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { __source: { fileName: _jsxFileName, lineNumber: 26 }, __self: this }, "projects")), " | my ", react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: _config__WEBPACK_IMPORTED_MODULE_1__["default"].site + 'static/vladyslav_hrytsenko_2020.pdf', __source: { fileName: _jsxFileName, lineNumber: 27 }, __self: this }, "c.v."))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "link-bar", __source: { fileName: _jsxFileName, lineNumber: 31 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "mailto:vladgritsenko+site@gmail.com?subject=Hey!", __source: { fileName: _jsxFileName, lineNumber: 32 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-envelope", __source: { fileName: _jsxFileName, lineNumber: 32 }, __self: this })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://github.com/inlife", __source: { fileName: _jsxFileName, lineNumber: 33 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-github", __source: { fileName: _jsxFileName, lineNumber: 33 }, __self: this })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://facebook.com/inlife360", __source: { fileName: _jsxFileName, lineNumber: 34 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-facebook-official", __source: { fileName: _jsxFileName, lineNumber: 34 }, __self: this })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://twitter.com/inlife360", __source: { fileName: _jsxFileName, lineNumber: 35 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-twitter", __source: { fileName: _jsxFileName, lineNumber: 35 }, __self: this })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://angel.co/inlife360", __source: { fileName: _jsxFileName, lineNumber: 36 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "smaller", __source: { fileName: _jsxFileName, lineNumber: 36 }, __self: this }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-angellist", __source: { fileName: _jsxFileName, lineNumber: 36 }, __self: this }))))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_Footer__WEBPACK_IMPORTED_MODULE_4__["default"], { __source: { fileName: _jsxFileName, lineNumber: 40 }, __self: this })); }); (function (Component, route) { if(!Component) return if (false) {} module.hot.accept() Component.__route = route if (module.hot.status() === 'idle') return var components = next.router.components for (var r in components) { if (!components.hasOwnProperty(r)) continue if (components[r].Component.__route === route) { next.router.update(r, Component) } } })(typeof __webpack_exports__ !== 'undefined' ? __webpack_exports__.default : (module.exports.default || module.exports), "/") /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module))) /***/ }), /***/ 7: /*!******************************!*\ !*** multi ./pages/index.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __NEXT_REGISTER_PAGE('/', function() { module.exports = __webpack_require__(/*! ./pages/index.js */"./pages/index.js"); return { page: module.exports.default }}); /***/ }), /***/ "dll-reference dll_b2d9fd95b535cd8bf589": /*!*******************************************!*\ !*** external "dll_b2d9fd95b535cd8bf589" ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = dll_b2d9fd95b535cd8bf589; /***/ }) },[[7,"static/runtime/webpack.js"]]]));; //# sourceMappingURL=index.js.map
#!/usr/bin/env node 'use strict'; const buildBranch = require('./index.js'); const branch = process.argv[2]; const dir = process.argv[3]; const domain = process.argv[4]; const noVerify = process.argv[5]; buildBranch({ branch: branch || 'gh-pages', folder: dir || 'www', domain: domain || '', noVerify: !!noVerify, }, function buildBranchCLICb(err) { if(err) { throw err; } console.log('Published!'); // eslint-disable-line });
/*! * Simple jQuery Load HTML file, TXT file without iframe * * Copyright (c) 2016 Louis Ho * Under the MIT license. * * @version 1.0.0 */ (function($){ /* .loadHTML() is used to import the external html file into your current html elements */ jQuery.fn.loadHTML = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).html(data); }, error: function(e) { console.log(e.message); } }); } /* .appendHTML() is used to import the external html file into your current html elements */ jQuery.fn.appendHTML = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).append(data); }, error: function(e) { console.log(e.message); } }); } /* .prependHTML() is used to import the external html file into your current html elements */ jQuery.fn.prependHTML = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).prepend(data); }, error: function(e) { console.log(e.message); } }); } /* .loadTEXT() is used to import the external txt file into your current html elements */ jQuery.fn.loadTEXT = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).text(data); }, error: function(e) { console.log(e.message); } }); } /* .appendTEXT() is used to import the external txt file into your current html elements */ jQuery.fn.appendTEXT = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).append(document.createTextNode(data)); }, error: function(e) { console.log(e.message); } }); } /* .prependTEXT() is used to import the external txt file into your current html elements */ jQuery.fn.prependTEXT = function (url) { var thisElement = this; $.ajax({ type: 'GET', url: url, dataType: 'text', success: function(data) { $(thisElement).prepend(document.createTextNode(data)); }, error: function(e) { console.log(e.message); } }); } })(jQuery);
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ module.exports = {FILE_NAME: "./tests/test_cal.jade", template: function (s, d) { var __FILE__ = "./tests/test_cal.jade"; var n_1 = d.tag(s, function () { return n_0; }, function (s) { var n_2 = d.tag(s, function () { return n_1; }, function (s) { var n_3 = d.tag(s, function () { return n_2; }, function (s) { var n_4 = d.tag(s, function () { return n_3; }, function (s) { return []; }, null, d.util.merge_attrs([{"class": "arrow"}, {"class": "left"}]), [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.prevMonth(); } }], deps: ["cal", "s.cal.prevMonth"]}], []); var n_5 = d.tag(s, function () { return n_3; }, function (s) { var n_6 = d.tag(s, function () { return n_5; }, function (s) { var n_7 = d.text(s, function () { return n_6; }, function (s, c) { with (c || {}) { return s.cal.current.format("MMMM"); } }, ["cal", "s.cal.current", "s.cal.current.format"]); return [n_7]; }, null, d.util.merge_attrs([{"class": "month"}]), [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.cycleMode("months", "month"); } }], deps: ["cal", "s.cal.cycleMode"]}], []); var n_8 = d.tag(s, function () { return n_5; }, function (s) { var n_9 = d.text(s, function () { return n_8; }, function (s, c) { with (c || {}) { return s.cal.current.format("YYYY"); } }, ["cal", "s.cal.current", "s.cal.current.format"]); return [n_9]; }, null, d.util.merge_attrs([{"class": "year"}]), [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.cycleMode("years", "month"); } }], deps: ["cal", "s.cal.cycleMode"]}], []); return [n_6, n_8]; }, null, d.util.merge_attrs([{"class": "title"}]), [], []); var n_10 = d.tag(s, function () { return n_3; }, function (s) { return []; }, null, d.util.merge_attrs([{"class": "arrow"}, {"class": "right"}]), [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.nextMonth(); } }], deps: ["cal", "s.cal.nextMonth"]}], []); return [n_4, n_5, n_10]; }, null, d.util.merge_attrs([{"class": "header"}]), [], []); var n_11 = d.tag(s, function () { return n_2; }, function (s) { var n_12 = d.casewhen(s, function () { return n_11; }, [function (s) { var n_13 = d.tag(s, function () { return n_12; }, function (s) { var n_14 = d.forin(s, function () { return n_13; }, function (s) { var n_15 = d.tag(s, function () { return n_14; }, function (s) { var n_16 = d.tag(s, function () { return n_15; }, function (s) { var n_17 = d.text(s, function () { return n_16; }, function (s, c) { with (c || {}) { return s.month.format("MMMM"); } }, ["month", "s.month.format"]); return [n_17]; }, "span", null, [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.setCurrentMonth(s.month); } }], deps: ["cal", "s.cal.setCurrentMonth", "month"]}], []); return [n_16]; }, null, d.util.merge_attrs([{"class": "month-title"}]), [], []); return [n_15]; }, function (s, c) { with (c || {}) { return s.cal.months; } }, "month", "undefined", true, ["cal", "s.cal.months"]); return [n_14]; }, null, d.util.merge_attrs([{"class": "months"}]), [], []); return [n_13]; }, function (s) { var n_18 = d.tag(s, function () { return n_12; }, function (s) { var n_19 = d.tag(s, function () { return n_18; }, function (s) { var n_20 = d.forin(s, function () { return n_19; }, function (s) { var n_21 = d.tag(s, function () { return n_20; }, function (s) { var n_22 = d.text(s, function () { return n_21; }, function (s, c) { with (c || {}) { return s.week.format("dd"); } }, ["week", "s.week.format"]); return [n_22]; }, null, d.util.merge_attrs([{"class": "week-title"}]), [], []); return [n_21]; }, function (s, c) { with (c || {}) { return s.cal.weeks; } }, "week", "undefined", true, ["cal", "s.cal.weeks"]); return [n_20]; }, null, d.util.merge_attrs([{"class": "week-titles"}]), [], []); var n_23 = d.forin(s, function () { return n_18; }, function (s) { var n_24 = d.tag(s, function () { return n_23; }, function (s) { var n_25 = d.forin(s, function () { return n_24; }, function (s) { var n_26 = d.tag(s, function () { return n_25; }, function (s) { var n_27 = d.tag(s, function () { return n_26; }, function (s) { var n_28 = d.text(s, function () { return n_27; }, function (s, c) { with (c || {}) { return s.day.format("D"); } }, ["day", "s.day.format"]); return [n_28]; }, "span", function (s, c) { with (c || {}) { return d.util.merge_attrs([{"class": {"selected": s.cal.isSelected(s.day), "now": s.cal.isCurrent(s.day), "current": s.cal.isSameMonth(s.day)}}]); } }, [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.select(s.day); } }], deps: ["cal", "s.cal.select", "day"]}], ["cal", "s.cal.isSelected", "day", "cal", "s.cal.isCurrent", "day", "cal", "s.cal.isSameMonth", "day"]); return [n_27]; }, null, d.util.merge_attrs([{"class": "day"}]), [], []); return [n_26]; }, function (s, c) { with (c || {}) { return s.weekdays; } }, "day", "undefined", true, ["weekdays"]); return [n_25]; }, null, d.util.merge_attrs([{"class": "week"}]), [], []); return [n_24]; }, function (s, c) { with (c || {}) { return s.cal.calendar; } }, "weekdays", "undefined", true, ["cal", "s.cal.calendar"]); return [n_19, n_23]; }, null, d.util.merge_attrs([{"class": "month"}]), [], []); return [n_18]; }, function (s) { var n_29 = d.tag(s, function () { return n_12; }, function (s) { var n_30 = d.forin(s, function () { return n_29; }, function (s) { var n_31 = d.tag(s, function () { return n_30; }, function (s) { var n_32 = d.tag(s, function () { return n_31; }, function (s) { var n_33 = d.text(s, function () { return n_32; }, function (s, c) { with (c || {}) { return s.year.format("YYYY"); } }, ["year", "s.year.format"]); return [n_33]; }, "span", null, [{id: "on", args: ["click", function (s, c) { with (c || {}) { return s.cal.setCurrentYear(s.year); } }], deps: ["cal", "s.cal.setCurrentYear", "year"]}], []); return [n_32]; }, null, d.util.merge_attrs([{"class": "year-title"}]), [], []); return [n_31]; }, function (s, c) { with (c || {}) { return s.cal.years; } }, "year", "undefined", true, ["cal", "s.cal.years"]); return [n_30]; }, null, d.util.merge_attrs([{"class": "years"}]), [], []); return [n_29]; }], [{c: 0, e: "months"}, {c: 1, e: "month"}, {c: 2, e: "years"}], function (s, c) { with (c || {}) { return s.cal.mode; } }, null, ["cal", "s.cal.mode"]); return [n_12]; }, null, d.util.merge_attrs([{"class": "body"}]), [], []); return [n_3, n_11]; }, null, d.util.merge_attrs([{"class": "jd-calendar-container"}]), [], []); return [n_2]; }, null, d.util.merge_attrs([{"class": "jd-calendar"}]), [], []); ; return [n_1]; }};
/* Dependency management */ requirejs.config({ baseUrl: 'public/scripts/lib', paths: { app: '../' }, shim: {} }); // Start the main app logic. requirejs(['jquery', 'app/commons/UITools'], function ($, UITools) { UITools.navSelect("itemAbout"); // Hidden by default UITools.hideStatusBar(); });
import React from 'react' import UpgradesTable from 'upgrades/upgrades_table' export default class UpgradesPage extends React.Component { constructor(props) { super(props) var self = this; this.state = { hqLevel: 1 } db.get(`select * from user_buildings ub join building_levels bl on bl.id = ub.building_level_id where name = "Headquarters"`, (err, hq) => { self.setState({hqLevel: hq.level}) this.reloadUpgrades(); }); } reloadUpgrades(hqLevel) { if(!hqLevel) hqLevel = this.state.hqLevel db.all("select * from upgrades where required_hq <= " + hqLevel, (err, upgrades) => { this.setState({upgrades: upgrades}) }); } hqLevelChange (evt) { var newHqLevel = evt.target.value; this.reloadUpgrades(newHqLevel); this.setState({hqLevel: newHqLevel}); } render() { if(!this.state.upgrades) return null return <div> <h1>Upgrades</h1> <label>HQ Level {this.state.hqLevel}</label> <input type="range" min="1" max="20" value={this.state.hqLevel} onChange={this.hqLevelChange.bind(this)} /> <UpgradesTable upgrades={this.state.upgrades} reloadUpgrades={this.reloadUpgrades.bind(this)}/> </div>; } }
const { expect } = require('chai'); const { setupDriver } = require('../../utils/setup-driver'); const webdriver = require('selenium-webdriver'); describe('Items routes', () => { let driver = null; const appUrl = 'http://localhost:3004'; beforeEach(() => { driver = setupDriver('chrome'); }); afterEach(() => { return driver.quit(); }); it('expect h3 with text "Search for a property for Sell"', (done) => { driver.get(appUrl) .then(() => { return driver.findElement( webdriver.By.css('h3') ); }) .then((el) => { return el.getText(); }) .then((text) => { expect(text).to.contain('Search for a property for Sell'); done(); }); }); });
// Karma configuration // Generated on Fri Jan 01 2016 23:59:53 GMT+0100 (Romance Standard Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai'], // list of files / patterns to load in the browser files: [ 'node_modules/angular/angular.js', 'node_modules/angular-route/angular-route.js', 'node_modules/angular-mocks/angular-mocks.js', 'src/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }); };
module.exports = { prefix: 'fal', iconName: 'calendar-plus', icon: [448, 512, [], "f271", "M320 332v8c0 6.6-5.4 12-12 12h-68v68c0 6.6-5.4 12-12 12h-8c-6.6 0-12-5.4-12-12v-68h-68c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h68v-68c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v68h68c6.6 0 12 5.4 12 12zm128-220v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v52h192V12c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-416 0v48h384v-48c0-8.8-7.2-16-16-16H48c-8.8 0-16 7.2-16 16zm384 352V192H32v272c0 8.8 7.2 16 16 16h352c8.8 0 16-7.2 16-16z"] };
define('ember-bootstrap/components/bs-modal-dialog', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var computed = _ember['default'].computed; /** Internal component for modal's markup and event handling. Should not be used directly. @class ModalDialog @namespace Components @extends Ember.Component @private */ exports['default'] = _ember['default'].Component.extend({ classNames: ['modal'], classNameBindings: ['fade', 'in'], attributeBindings: ['tabindex'], ariaRole: 'dialog', tabindex: '-1', /** * The title of the modal, visible in the modal header. Is ignored if `header` is false. * * @property title * @type string * @public */ title: null, /** * Display a close button (x icon) in the corner of the modal header. * * @property closeButton * @type boolean * @default true * @public */ closeButton: true, /** * Set to false to disable fade animations. * * @property fade * @type boolean * @default true * @public */ fade: true, /** * Used to apply Bootstrap's "in" class * * @property in * @type boolean * @default false * @private */ 'in': false, /** * Closes the modal when escape key is pressed. * * @property keyboard * @type boolean * @default true * @public */ keyboard: true, /** * Generate a modal header component automatically. Set to false to disable. In this case you would want to include an * instance of [Components.ModalHeader](Components.ModalHeader.html) in the components block template * * @property header * @type boolean * @default true * @public */ header: true, /** * Generate a modal body component automatically. Set to false to disable. In this case you would want to include an * instance of [Components.ModalBody](Components.ModalBody.html) in the components block template. * * Always set this to false if `header` and/or `footer` is false! * * @property body * @type boolean * @default true * @public */ body: true, /** * Generate a modal footer component automatically. Set to false to disable. In this case you would want to include an * instance of [Components.ModalFooter](Components.ModalFooter.html) in the components block template * * @property footer * @type boolean * @default true * @public */ footer: true, /** * Property for size styling, set to null (default), 'lg' or 'sm' * * Also see the [Bootstrap docs](http://getbootstrap.com/javascript/#modals-sizes) * * @property size * @type String * @public */ size: null, /** * If true clicking on the backdrop will close the modal. * * @property backdropClose * @type boolean * @default true * @public */ backdropClose: true, /** * Name of the size class * * @property sizeClass * @type string * @private */ sizeClass: computed('size', function () { var size = this.get('size'); return _ember['default'].isBlank(size) ? null : 'modal-' + size; }), keyDown: function keyDown(e) { var code = e.keyCode || e.which; if (code === 27 && this.get('keyboard')) { this.sendAction('close'); } }, click: function click(e) { if (e.target !== e.currentTarget || !this.get('backdropClose')) { return; } this.sendAction('close'); } }); });
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/519dbfafc4d8e692218df3b264a2e373 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/519dbfafc4d8e692218df3b264a2e373 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono-dark', preset: 'standard', ignore: [ '.bender', 'bender.js', 'bender-err.log', 'bender-out.log', 'dev', '.DS_Store', '.editorconfig', '.gitattributes', '.gitignore', 'gruntfile.js', '.idea', '.jscsrc', '.jshintignore', '.jshintrc', 'less', '.mailmap', 'node_modules', 'package.json', 'README.md', 'tests' ], plugins : { 'a11yhelp' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'codesnippet' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'en' : 1 } };
// COPYRIGHT © 2017 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: contracts@esri.com // // See http://js.arcgis.com/4.4/esri/copyright.txt for details. define(["require","exports","../../core/tsSupport/declareExtendsHelper","../../core/tsSupport/decorateHelper","../../core/accessorSupport/decorators","../../core/JSONSupport","../../core/kebabDictionary"],function(e,r,t,o,p,n,c){var i=c({codedValue:"coded-value"}),u=function(e){function r(r){var t=e.call(this,r)||this;return t.name=null,t.type=null,t}return t(r,e),r.prototype.writeType=function(e,r){r.type=i.toJSON(e)},r}(p.declared(n));return o([p.property({json:{write:!0}})],u.prototype,"name",void 0),o([p.property({json:{read:i.fromJSON,write:!0}})],u.prototype,"type",void 0),o([p.writer("type")],u.prototype,"writeType",null),u=o([p.subclass("esri.layers.support.Domain")],u)});
/** * Helper functions */ 'use strict'; /** * Common options */ function options(req, opts) { if (!req.query) req.query = {}; if (typeof opts.depth === 'number') { req.query.depth = opts.depth; } if (typeof opts.tree === 'string') { req.query.tree = opts.tree; } return opts; } /** * Raw path param */ function RawParam(value) { this.encode = false; this.value = value || ''; } RawParam.prototype.toString = function() { return this.value; }; /** * Path for folder plugin */ function FolderPath(value) { if (!(this instanceof FolderPath)) { return new FolderPath(value); } if (Array.isArray(value)) { this.value = value; } else { this.value = (value || '').split('/').filter(Boolean); } } FolderPath.SEP = '/job/'; FolderPath.prototype.isEmpty = function() { return !this.value.length; }; FolderPath.prototype.name = function() { return this.value[this.value.length - 1] || ''; }; FolderPath.prototype.path = function() { if (this.isEmpty()) return new RawParam(); return new RawParam(FolderPath.SEP + this.value.map(encodeURIComponent).join(FolderPath.SEP)); }; FolderPath.prototype.parent = function() { return new FolderPath(this.value.slice(0, Math.max(0, this.value.length - 1))); }; FolderPath.prototype.dir = function() { return this.parent().path(); }; /** * Module exports */ exports.options = options; exports.FolderPath = FolderPath;
'use strict'; angular.module('shopAdmin').controller('settingsEmailListController', ['$scope', '$location', '$timeout', 'settingsService', function($scope, $location, $timeout, settingsService) { $scope.settings = {}; $scope.email = {}; $scope.getEmailSettings = function() { settingsService.getEmailSettings() .$promise .then(function(settings) { $scope.settings = settings; }); }; $scope.getEmailSettings(); var resetDefaultEmail = function(callback) { var emailCount = 0; angular.forEach($scope.settings.emails, function(email) { email.isDefault = false; emailCount+=1; }); if($scope.settings.emails.length === emailCount) { callback(); } }; $scope.markAsDefaultEmail = function(emailIndex) { resetDefaultEmail(function() { $scope.settings.emails[emailIndex].isDefault = true; settingsService.editEmailSettings($scope.settings) .$promise .then(function(response) { $scope.updateSuccessMsg = response.msg; $timeout(function(){ $scope.updateSuccessMsg = ''; },2000); }); }); }; $scope.testEmailSend = function() { settingsService.testEmailSend($scope.email) .$promise .then(function(resposnse) { $scope.sendSuccess = resposnse.msg; $timeout(function() { $scope.sendSuccess = ''; },2000); },function(error) { $scope.sendFailed = error.data.msg; }); }; } ]);
version https://git-lfs.github.com/spec/v1 oid sha256:c5f5480dabb1b45a9e65d1dd86a827fe49be4159dbb1a157aa296bc910871edc size 1914
var _ = require('underscore'); var express = require('express'); var db = require('../helpers/db'); var isBadRequest = require('../helpers/request-checker'); var router = express.Router(); var createTagQuery = function(id, tags) { if (tags.length === 0) { return ""; } var query = 'INSERT INTO tags ("place_id", "characteristic_id") VALUES '; for (var tag in tags) { query += ('(' + id + ', ' + tags[tag] + ')'); if (tags[tag] === _.last(tags)) { query += ';'; } else { query += ', '; } } return query; }; router.get('/', function(req, res) { var query = "SELECT place_id, places.name, countries.name AS country, description, places.photo_id, latitude, longitude, link, enabled FROM places LEFT JOIN countries ON countries.country_id = places.country_id ORDER BY place_id ASC"; db.query(query) .then(function(result) { res.status(200).send(result.rows); }) .catch(function(error) { res.status(500).send(error); }); }); router.post('/', function(req, res) { var values = [ req.body.country_id, req.body.name, req.body.description, req.body.photo_id, req.body.latitude, req.body.longitude, req.body.link, req.body.enabled, req.body.tags ]; if (isBadRequest(values)) { res.status(400).send("Bad Request"); return; } var query = 'INSERT INTO places ("country_id", "name", "description", "photo_id", "latitude", "longitude", "link", "enabled") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING place_id'; db.query(query, _.initial(values)) .then(function(result) { var row = result.rows[0]; var tags = _.last(values); var query = createTagQuery(row.place_id, tags); db.query(query) .then(function(result) { res.status(201).send(row); }) .catch(function(error) { res.status(500).send(error); }); }) .catch(function(error) { res.status(500).send(error); }); }); router.use('/:id', function(req, res, next) { var id = Number(req.params.id); if (_.isNumber(id)) { next(); } else { res.status(400).send("Value should be a number"); } }); router.get('/:id', function(req, res) { var query = "SELECT * FROM places WHERE place_id = $1"; var values = [req.params.id]; db.query(query, values) .then(function(result) { var row = result.rows[0]; if (_.isEmpty(row)) { res.status(404).end(); } else { var tagQuery = "SELECT characteristic_id FROM tags WHERE place_id = $1"; db.query(tagQuery, values) .then(function(result) { var tags = []; _.each(result.rows, function(tag) { tags.push(tag.characteristic_id); }); row.tags = tags; res.status(200).send(row); }) .catch(function(error) { res.status(500).send(error); }); } }) .catch(function(error) { res.status(500).send(error); }); }); router.put('/:id', function(req, res) { var values = [ req.body.name, req.body.description, req.body.photo_id, req.body.latitude, req.body.longitude, req.body.link, req.body.enabled ]; if (isBadRequest(values)) { res.status(400).send("Bad Request"); return; } var id = req.params.id; var tags = req.body.tags; var shouldUpdateTags = !(_.isUndefined(tags)); var tagPromise = new Promise(function(resolve, reject) { if (!shouldUpdateTags) { resolve("Not updating tags"); } else { var tagQuery = 'DELETE FROM tags WHERE tags.place_id = $1'; var tagValues = [id]; var errorCallback = function(error) { res.status(500).send(error); reject(error); }; db.query(tagQuery, tagValues) .then(function(result) { tagQuery = createTagQuery(id, tags); if (tagQuery === "") { resolve("Done updating tags"); return; } db.query(tagQuery) .then(function(result) { resolve("Done updating tags"); }) .catch(errorCallback); }) .catch(errorCallback); } }); tagPromise.then(function(result) { var query = "UPDATE places SET name = $1, description = $2, photo_id = $3, latitude = $4, longitude = $5, link = $6, enabled = $7 WHERE place_id = " + id; db.query(query, values) .then(function(result) { res.status(200).end(); }) .catch(function(error) { res.status(500).send(error); }); }); }); router.delete('/:id',function(req, res) { var query = "BEGIN; DELETE FROM tags WHERE place_id = $1; DELETE FROM places WHERE place_id = $1; COMMIT;"; query = query.split('$1').join(req.params.id); db.query(query) .then(function(result) { res.status(204).end(); }) .catch(function(error) { console.log(error); res.status(500).send(error); }); }); module.exports = router;
var assert = require('assert'); var Key = require('../').Key; var bytesToHex = require('../').convert.bytesToHex; var hexToBytes = require('../').convert.hexToBytes; var base58 = require('../').base58; // get public key from private key test('from private base58', function() { var priv = '18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725'; var pub = '0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6'; var key = Key(hexToBytes(priv)); assert.equal(bytesToHex(key.getPub()), pub); assert.equal(key.compressed, false); var priv = '5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh'; var pub = '044f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa385b6b1b8ead809ca67454d9683fcf2ba03456d6fe2c4abe2b07f0fbdbb2f1c1'; var addr = '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a'; var key = Key(priv); assert.equal(key.compressed, false); assert.equal(bytesToHex(key.getPub()), pub); assert.equal(key.getBitcoinAddress().toString(), addr); var priv = 'KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp'; var pub = '034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa' var addr = '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9'; var key = Key(priv); assert.equal(key.compressed, true); assert.equal(bytesToHex(key.getPub()), pub); assert.equal(key.getBitcoinAddress().toString(), addr); assert.notEqual(key.getBitcoinAddress('testnet').toString(), addr); });
import * as fetchUtils from '../util/fetchUtils'; import serverFetchQueries from './fetchQueries'; describe('serverFetchQueries', () => { // export const serverFetchQueries = request => () => queries => // apiProxy$(request, queries) // .toPromise() // .then(parseQueryResponse(queries)); it('calls apiProxy$ with request and queries, passes ', () => { const request = { proxyApi: jest.fn(() => { return Promise.resolve('response'); }), trackActivity: jest.fn(), state: {}, server: { settings: { app: { api: {} } } }, }; const queries = []; const expectedParsedResponse = 'foo'; spyOn(fetchUtils, 'parseQueryResponse').and.callFake(() => () => expectedParsedResponse ); return serverFetchQueries(request)()(queries).then(parsedResponse => { expect(request.proxyApi).toHaveBeenCalledWith(queries, undefined); expect(parsedResponse).toEqual(expectedParsedResponse); }); }); });
/** * @file Interface for entire ui-handling. This prototype is used in stages to * access ui-based logic and to create ui-entities. * * @author Human Interactive */ "use strict"; var eventManager = require( "../messaging/EventManager" ); var TOPIC = require( "../messaging/Topic" ); var system = require( "../core/System" ); var developmentPanel = require( "./DevelopmentPanel" ); var performanceMonitor = require( "./PerformanceMonitor" ); var informationPanel = require( "./InformationPanel" ); var interactionLabel = require( "./InteractionLabel" ); var loadingScreen = require( "./LoadingScreen" ); var menu = require( "./Menu" ); var textScreen = require( "./TextScreen" ); var modalDialog = require( "./ModalDialog" ); var chat = require( "./Chat" ); var self; /** * Creates the user interface manager. * * @constructor */ function UserInterfaceManager() { self = this; } /** * Initializes the user interface manager. */ UserInterfaceManager.prototype.init = function() { // eventing this._initEventListener(); // subscriptions this._initSubscriptions(); // the setup of controls must always be done AFTER the setup of event // listener and subscriptions informationPanel.init(); interactionLabel.init(); loadingScreen.init(); menu.init(); textScreen.init(); modalDialog.init(); chat.init(); // add development controls if ( system.isDevModeActive === true ) { performanceMonitor.init(); developmentPanel.init(); } }; /** * Updates the manager. */ UserInterfaceManager.prototype.update = function() { if ( system.isDevModeActive === true ) { performanceMonitor.update(); } }; /** * Sets the text of the information panel. * * @param {string} textKey - The text-content of the information panel. */ UserInterfaceManager.prototype.setInformationPanelText = function( textKey ) { informationPanel.setText( textKey ); }; /** * Shows the text screen. * * @param {object} textObject - The conversation of the text screen. * @param {function} completeCallback - This function is executed, when all * texts are shown and the ui-element is going to hide. */ UserInterfaceManager.prototype.showTextScreen = function( textKeys, completeCallback ) { textScreen.show( textKeys, completeCallback ); }; /** * Hides the text screen. */ UserInterfaceManager.prototype.hideTextScreen = function() { textScreen.hide(); }; /** * Shows the modal dialog. * * @param {object} textKeys - The texts to display. */ UserInterfaceManager.prototype.showModalDialog = function( textKeys ) { modalDialog.show( textKeys ); }; /** * Hides the modal dialog. */ UserInterfaceManager.prototype.hideModalDialog = function() { modalDialog.hide(); }; /** * Handles the press of the space-key. */ UserInterfaceManager.prototype.handleUiInteraction = function() { if ( textScreen.isActive === true ) { textScreen.complete(); } else if ( loadingScreen.isActive === true && loadingScreen.isReady === true ) { eventManager.publish( TOPIC.STAGE.START, undefined ); loadingScreen.hide(); } }; /** * Initializes event listeners for DOM events. */ UserInterfaceManager.prototype._initEventListener = function() { global.window.addEventListener( "contextmenu", this._onContextMenu ); global.window.addEventListener( "keydown", this._onKeyDown ); global.window.addEventListener( "resize", this._onResize ); }; /** * Initializes subscriptions */ UserInterfaceManager.prototype._initSubscriptions = function() { eventManager.subscribe( TOPIC.UI.MENU.SHOW, this._onShowMenu ); eventManager.subscribe( TOPIC.UI.MENU.HIDE, this._onHideMenu ); eventManager.subscribe( TOPIC.UI.INTERACTION_LABEL.SHOW, this._onShowInteractionLabel ); eventManager.subscribe( TOPIC.UI.INTERACTION_LABEL.HIDE, this._onHideInteractionLabel ); eventManager.subscribe( TOPIC.UI.LOADING_SCREEN.SHOW, this._onShowLoadingScreen ); eventManager.subscribe( TOPIC.UI.LOADING_SCREEN.HIDE, this._onHideLoadingScreen ); eventManager.subscribe( TOPIC.UI.PERFORMANCE.TOGGLE, this._onPerformanceMonitor ); }; /** * This method handles the context menu event. * * @param {object} event - The event object. */ UserInterfaceManager.prototype._onContextMenu = function( event ) { // disable contextmenu event.preventDefault(); }; /** * This method handles the keydown event. * * @param {object} event - Default event object. */ UserInterfaceManager.prototype._onKeyDown = function( event ) { switch ( event.keyCode ) { // enter case 13: event.preventDefault(); if ( textScreen.isActive === false && modalDialog.isActive === false && developmentPanel.isActive === false && menu.isActive === false && loadingScreen.isActive === false ) { chat.toggle(); } break; // space case 32: if ( chat.isActive === false ) { // prevent scrolling event.preventDefault(); // because pressing the space key can cause different actions, // the logic for this key handling is placed in a separate method self.handleUiInteraction(); } break; // m case 77: if ( system.isDevModeActive === true && ( textScreen.isActive === false && modalDialog.isActive === false && chat.isActive === false && menu.isActive === false && loadingScreen.isActive === false ) ) { developmentPanel.toggle(); } break; } }; /** * This method handles the resize event. * * @param {object} event - The event object. */ UserInterfaceManager.prototype._onResize = function( event ) { eventManager.publish( TOPIC.APPLICATION.RESIZE, undefined ); }; /** * This method handles the "show" topic for the menu. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onShowMenu = function( message, data ) { menu.show(); }; /** * This method handles the "hide" topic for the menu. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onHideMenu = function( message, data ) { menu.hide(); }; /** * This method handles the "show" topic for the interaction label. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onShowInteractionLabel = function( message, data ) { interactionLabel.show( data.textKey ); }; /** * This method handles the "hide" topic for the interaction label. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onHideInteractionLabel = function( message, data ) { interactionLabel.hide(); }; /** * This method handles the "show" topic for the loading screen. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onShowLoadingScreen = function( message, data ) { loadingScreen.show( data.callback ); }; /** * This method handles the "hide" topic for the loading screen. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onHideLoadingScreen = function( message, data ) { loadingScreen.hide(); }; /** * This method handles the "toggle" topic for the performance monitor. * * @param {string} message - The message topic of the subscription. * @param {object} data - The data of the message. */ UserInterfaceManager.prototype._onPerformanceMonitor = function( message, data ) { performanceMonitor.toggle(); }; module.exports = new UserInterfaceManager();
function translateScore(guessAndScore) { // Translate a guessAndScore from internal Perseus format to the // result format used everywhere else. // // TODO(eater): Use the existance of these unit tests to // convert eveything to The One True Format. guess = guessAndScore[0]; score = guessAndScore[1]; if (score.type === "points") { return { empty: false, correct: score.earned >= score.total, message: score.message, guess: guess }; } else if (score.type === "invalid") { return { empty: true, correct: false, message: score.message, guess: guess }; } } function testAnswer(component, input, result, description) { $("#qunit-fixture input").val(input); checkAnswer(component, result, description + " [" + input + "]"); } function testMultipleAnswer(component, inputs, result, description) { _.chain($("#qunit-fixture input")).zip(inputs).each(function(args) { var el = args[0], text = args[1]; if (typeof text === "string") { $(el).val(text); } else { $(el).prop("checked", text); } }); checkAnswer(component, result, description + " [" + inputs.join(", ") + "]"); } function checkAnswer(component, result, description) { var answer = translateScore(component.guessAndScore()); if (result === "right") { strictEqual(answer.empty, false, description + " - not empty"); strictEqual(answer.message, null, description + " - no message"); strictEqual(answer.correct, true, description + " - correct"); } else if (result === "right-message") { strictEqual(answer.empty, false, description + " - not empty"); notStrictEqual(answer.message, null, description + " - message"); strictEqual(answer.correct, true, description + " - correct"); } else if (result === "wrong") { strictEqual(answer.empty, false, description + " - not empty"); strictEqual(answer.message, null, description + " - no message"); strictEqual(answer.correct, false, description + " - not correct"); } else if (result === "wrong-message") { strictEqual(answer.empty, false, description + " - not empty"); notStrictEqual(answer.message, null, description + " - message"); strictEqual(answer.correct, false, description + " - not correct"); } else if (result === "empty") { strictEqual(answer.empty, true, description + " - empty"); strictEqual(answer.message, null, description + " - no message"); strictEqual(answer.correct, false, description + " - not correct"); } else if (result === "empty-message") { strictEqual(answer.empty, true, description + " - empty"); notStrictEqual(answer.message, null, description + " - message"); strictEqual(answer.correct, false, description + " - not correct"); } } asyncTest("widget input-number", 27, function() { var component = React.renderComponent(Perseus.Renderer({ content: "[[☃ input-number 1]]", widgets: { "input-number 1": { options: { value: "-42", simplify: "required", size: "normal", inexact: false, maxError: 0.1, answerType: "number" }, type: "input-number" } } }), $("#qunit-fixture")[0]); testAnswer(component, "", "empty", "empty answer is empty"); testAnswer(component, "123", "wrong", "wrong answer is wrong"); testAnswer(component, "2/4", "wrong", "wrong answer is wrong"); testAnswer(component, "-42", "right", "right answer is right"); testAnswer(component, "-84/2", "empty-message", "non-simplified right answer gives message"); testAnswer(component, " \u2212 42 ", "right", "weirdly formatted right answer is right"); testAnswer(component, "- 4 2", "wrong", "crazily formatted answer is wrong"); testAnswer(component, "-41.9999999", "wrong", "close decimal is wrong"); testAnswer(component, "-,42", "wrong", "sort of tricky wrong answer is wrong"); start(); }); asyncTest("widget input-number multiple", 33, function() { var component = React.renderComponent(Perseus.Renderer({ "content": "[[☃ input-number 1]]\n[[☃ input-number 2]]", "widgets": { "input-number 1": { "options": { "value": "7", "simplify": "required", "size": "normal", "inexact": false, "maxError": 0.1, "answerType": "number" }, "type": "input-number" }, "input-number 2": { "options": { "value": "1.5", "simplify": "required", "size": "normal", "inexact": false, "maxError": 0.1, "answerType": "number" }, "type": "input-number" } } }), $("#qunit-fixture")[0]); testMultipleAnswer(component, ["7", "3/2"], "right", "right answer is right"); testMultipleAnswer(component, ["7", "1.5"], "right", "right answer is right"); testMultipleAnswer(component, ["3/2", "7"], "wrong", "wrong answer is wrong"); testMultipleAnswer(component, ["7", ""], "empty", "incomplete answer gives empty"); testMultipleAnswer(component, ["", "3/2"], "empty", "incomplete answer gives empty"); testMultipleAnswer(component, ["", ""], "empty", "empty answer is empty"); testMultipleAnswer(component, ["7", "6/4"], "empty-message", "unsimplified right answer provides a message"); testMultipleAnswer(component, ["14/2", "6/4"], "empty-message", "unsimplified right gives message"); testMultipleAnswer(component, ["14/2", "3/2"], "empty-message", "unsimplified right gives message"); testMultipleAnswer(component, ["7", "6/4"], "empty-message", "unsimplified right gives message"); // testMultipleAnswer(component, ["14/2", "7"], "wrong", "unsimplified right and wrong is wrong"); // testMultipleAnswer(component, ["3", "6/4"], "wrong", "unsimplified right and wrong is wrong"); testMultipleAnswer(component, ["4/2", "4/2"], "wrong", "unsimplified wrong is wrong"); // testMultipleAnswer(component, ["14/2", ""], "empty", "unsimplified incomplete answer is empty"); start(); }); asyncTest("widget input-number multiple simplify-enforced", 21, function() { var component = React.renderComponent(Perseus.Renderer({ "content": "[[☃ input-number 1]]\n[[☃ input-number 2]]", "widgets": { "input-number 1": { "options": { "value": "7", "simplify": "enforced", "size": "normal", "inexact": false, "maxError": 0.1, "answerType": "number" }, "type": "input-number" }, "input-number 2": { "options": { "value": "1.5", "simplify": "enforced", "size": "normal", "inexact": false, "maxError": 0.1, "answerType": "number" }, "type": "input-number" } } }), $("#qunit-fixture")[0]); testMultipleAnswer(component, ["7", "3/2"], "right", "right answer is right"); testMultipleAnswer(component, ["7", "1.5"], "right", "right answer is right"); testMultipleAnswer(component, ["3/2", "7"], "wrong", "wrong answer is wrong"); testMultipleAnswer(component, ["7", ""], "empty", "incomplete answer is empty"); testMultipleAnswer(component, ["", "3/2"], "empty", "incomplete answer is empty"); testMultipleAnswer(component, ["", ""], "empty", "empty answer is empty"); // testMultipleAnswer(component, ["7", "6/4"], "wrong", "unsimplified is wrong"); // testMultipleAnswer(component, ["14/2", "6/4"], "wrong", "unsimplified is wrong"); // testMultipleAnswer(component, ["14/2", "3/2"], "wrong", "unsimplified is wrong"); // testMultipleAnswer(component, ["7", "6/4"], "wrong", "unsimplified is wrong"); testMultipleAnswer(component, ["4/2", "4/2"], "wrong", "unsimplified wrong is wrong"); start(); });
(function( $ ) { module( "core - jQuery extensions" ); TestHelpers.testJshint( "core" ); asyncTest( "focus - original functionality", function() { expect( 1 ); $( "#inputTabindex0" ) .one( "focus", function() { ok( true, "event triggered" ); start(); }) .focus(); }); asyncTest( "focus", function() { expect( 2 ); $( "#inputTabindex0" ) .one( "focus", function() { ok( true, "event triggered" ); }) .focus( 500, function() { ok( true, "callback triggered" ); start(); }); }); test( "zIndex", function() { expect( 7 ); var el = $( "#zIndexAutoWithParent" ), parent = el.parent(); equal( el.zIndex(), 100, "zIndex traverses up to find value" ); equal( parent.zIndex(200 ), parent, "zIndex setter is chainable" ); equal( el.zIndex(), 200, "zIndex setter changed zIndex" ); el = $( "#zIndexAutoWithParentViaCSS" ); equal( el.zIndex(), 0, "zIndex traverses up to find CSS value, not found because not positioned" ); el = $( "#zIndexAutoWithParentViaCSSPositioned" ); equal( el.zIndex(), 100, "zIndex traverses up to find CSS value" ); el.parent().zIndex( 200 ); equal( el.zIndex(), 200, "zIndex setter changed zIndex, overriding CSS" ); equal( $( "#zIndexAutoNoParent" ).zIndex(), 0, "zIndex never explicitly set in hierarchy" ); }); test( "innerWidth - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.innerWidth(), 122, "getter passthru" ); el.hide(); equal( el.innerWidth(), 122, "getter passthru when hidden" ); }); test( "innerWidth - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.innerWidth( 120 ); equal( el.width(), 98, "width set properly" ); el.hide(); el.innerWidth( 100 ); equal( el.width(), 78, "width set properly when hidden" ); }); test( "innerHeight - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.innerHeight(), 70, "getter passthru" ); el.hide(); equal( el.innerHeight(), 70, "getter passthru when hidden" ); }); test( "innerHeight - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.innerHeight( 60 ); equal( el.height(), 40, "height set properly" ); el.hide(); el.innerHeight( 50 ); equal( el.height(), 30, "height set properly when hidden" ); }); test( "outerWidth - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.outerWidth(), 140, "getter passthru" ); el.hide(); equal( el.outerWidth(), 140, "getter passthru when hidden" ); }); test( "outerWidth - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.outerWidth( 130 ); equal( el.width(), 90, "width set properly" ); el.hide(); el.outerWidth( 120 ); equal( el.width(), 80, "width set properly when hidden" ); }); test( "outerWidth(true) - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.outerWidth(true), 154, "getter passthru w/ margin" ); el.hide(); equal( el.outerWidth(true), 154, "getter passthru w/ margin when hidden" ); }); test( "outerWidth(true) - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.outerWidth( 130, true ); equal( el.width(), 76, "width set properly" ); el.hide(); el.outerWidth( 120, true ); equal( el.width(), 66, "width set properly when hidden" ); }); test( "outerHeight - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.outerHeight(), 86, "getter passthru" ); el.hide(); equal( el.outerHeight(), 86, "getter passthru when hidden" ); }); test( "outerHeight - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.outerHeight( 80 ); equal( el.height(), 44, "height set properly" ); el.hide(); el.outerHeight( 70 ); equal( el.height(), 34, "height set properly when hidden" ); }); test( "outerHeight(true) - getter", function() { expect( 2 ); var el = $( "#dimensions" ); equal( el.outerHeight(true), 98, "getter passthru w/ margin" ); el.hide(); equal( el.outerHeight(true), 98, "getter passthru w/ margin when hidden" ); }); test( "outerHeight(true) - setter", function() { expect( 2 ); var el = $( "#dimensions" ); el.outerHeight( 90, true ); equal( el.height(), 42, "height set properly" ); el.hide(); el.outerHeight( 80, true ); equal( el.height(), 32, "height set properly when hidden" ); }); test( "uniqueId / removeUniqueId", function() { expect( 3 ); var el = $( "img" ).eq( 0 ); // support: jQuery <1.6.2 // support: IE <8 // We should use strictEqual( id, undefined ) when dropping jQuery 1.6.1 support (or IE6/7) ok( !el.attr( "id" ), "element has no initial id" ); el.uniqueId(); ok( /ui-id-\d+$/.test( el.attr( "id" ) ), "element has generated id" ); el.removeUniqueId(); // support: jQuery <1.6.2 // support: IE <8 // see above ok( !el.attr( "id" ), "unique id has been removed from element" ); }); })( jQuery );
var http = require('http'); var app = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }); var port = process.env.PORT || 10080; app.listen(port, function() { console.log("Listening on " + port); });
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // function to ease scrolling on anchors function easeScrolling() { $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body') .animate({scrollTop: targetOffset}, 1000); return false; } } } )} // jQuery to collapse the navbar on scroll function collapseNavbar() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } } $(window).scroll(collapseNavbar); $(document).ready(collapseNavbar); $(document).ready(easeScrolling); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { if ($(this).attr('class') != 'dropdown-toggle active' && $(this).attr('class') != 'dropdown-toggle') { $('.navbar-toggle:visible').click(); } }); // Google Maps Scripts var map = null; // When the window has finished loading create our google map below google.maps.event.addDomListener(window, 'load', init); google.maps.event.addDomListener(window, 'resize', function() { map.setCenter(new google.maps.LatLng(40.6700, -73.9400)); }); function init() { // Basic options for a simple Google Map // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions var mapOptions = { // How zoomed in you want the map to start at (always required) zoom: 15, // The latitude and longitude to center the map (always required) center: new google.maps.LatLng(40.6700, -73.9400), // New York // Disables the default Google Maps UI components disableDefaultUI: true, scrollwheel: false, draggable: false, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [{ "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }] }; // Get the HTML DOM element that will contain your map // We are using a div with id="map" seen below in the <body> var mapElement = document.getElementById('map'); // Create the Google Map using out element and options defined above map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(40.6700, -73.9400); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); }
const authResponse = require('../../middleware/auth-response'); const { WishList } = require('../../database/models/wish-list'); const { handleError, sanitizeRequestBody } = require('./shared'); async function updateWishList(req, res, next) { const wishListId = req.params.wishListId; const userId = req.user._id; const attributes = sanitizeRequestBody(req.body); try { const wishList = await WishList.confirmUserOwnership( wishListId, userId ); wishList.updateSync(attributes); await wishList.save(); authResponse({ data: { }, message: 'Wish list updated.' })(req, res, next); } catch (err) { handleError(err, next); } } module.exports = { updateWishList };
/* SAUERKRAUT V1 script.js */ $(document).ready(function(){ /*var t = 0; var b = $('#sidebar').height()+$('#footer').height()+$('#sidebar ul>li').length*20; $('.widget').each(function(){ b -= $(this).height()+20; $.lockfixed(this, {offset: {top: t, bottom: b}}) t += $(this).height()+20; });*/ //$.lockfixed('#sidebar .rightmenu', {offset: {top: 100, bottom: 100}}) $("#flip").click(function(){ $("#panel").slideToggle("slow"); }); $('#sidebar').on("mouseenter", function(){ /*mouseenter*/ $(this).addClass('top'); }); $('#sidebar').on("mouseleave", function(){ /*mouseleave*/ $(this).removeClass('top'); }); $(document).ready(function() { $(".fancybox").fancybox({ openEffect : 'none', closeEffect : 'none', padding : 5 }); }); $(".post_content").fitVids(); $('.gallery').each(function(){ $(this).find('.more').click(function(event){ $(this).parent().find('.gallery-icon a').trigger("click"); }); }); }); /* SCRIPT POUR FANCYBOX -> à insérer dans le champ prévu pour les scripts personnalisés //jQuery(thumbnails).addClass("fancybox").attr("rel","fancybox").getTitle(); jQuery(".gallery").each(function(){ var galleryCat = "fancybox-"+jQuery(this).attr("id"); jQuery("a",this).addClass("fancybox").attr("rel",galleryCat).getTitle(); }); */
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Subject_1 = require("rxjs/Subject"); exports.AUTH_URL = new core_1.OpaqueToken('app.auth_url'); var AuthService = (function () { function AuthService(http, authUrl) { this.http = http; this.authUrl = authUrl; this.token = localStorage.getItem('authToken'); this.username = 'admin'; this.password = '1234'; } AuthService.prototype.getToken = function () { var _this = this; if (!this.token) { var headers = new http_1.Headers(); headers.append("Content-Type", "x-www-form-urlencoded"); headers.append("accept", "application/json"); var authForm = "grant_type=password&username=" + this.username + "&password=" + this.password; var subject_1 = new Subject_1.Subject(); this.http.post(this.authUrl, authForm, { headers: headers }).subscribe(function (res) { return _this.processResponse(res, subject_1); }); return subject_1; } var subject = new Subject_1.Subject(); setTimeout(function () { return subject.next(_this.token); }, 1); return subject; // return Subject.create(() => this.token); }; AuthService.prototype.processResponse = function (res, subject) { var token = res.json(); this.token = token.access_token; this.saveToken(); subject.next(this.token); subject.complete(); }; AuthService.prototype.saveToken = function () { localStorage.setItem('authToken', this.token); }; return AuthService; }()); AuthService = __decorate([ core_1.Injectable(), __param(1, core_1.Inject(exports.AUTH_URL)), __metadata("design:paramtypes", [http_1.Http, String]) ], AuthService); exports.AuthService = AuthService; //# sourceMappingURL=AuthService.js.map
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = require('babel-runtime/regenerator'); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator'); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultEventFailureGracePeriod = 100; exports.default = function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(element, expectedDuration, type, eventFailureGracePeriod) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return new Promise(function (resolve) { var transitionend = getTransitionEndEvent(type); var gracePeriod = eventFailureGracePeriod !== undefined ? eventFailureGracePeriod : defaultEventFailureGracePeriod; var done = false; var forceEnd = false; element.addEventListener(transitionend, onTransitionEnd); setTimeout(function () { if (!done) { // forcing onTransitionEnd callback... forceEnd = true; onTransitionEnd(); } else { resolve(); } }, expectedDuration + gracePeriod); function onTransitionEnd(e) { if (forceEnd || e.target === element) { done = true; element.removeEventListener(transitionend, onTransitionEnd); resolve(); } } }); case 2: case 'end': return _context.stop(); } } }, _callee, undefined); })); return function (_x, _x2, _x3, _x4) { return _ref.apply(this, arguments); }; }(); function getTransitionEndEvent(type) { var types = void 0; if (type && ('transition' === type || 'trans' === type)) { types = { 'OTransition': 'oTransitionEnd', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'transition': 'transitionend' }; } else { // animation is default types = { 'OAnimation': 'oAnimationEnd', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'animationend', 'animation': 'animationend' }; } var elem = document.createElement('fake'); return Object.keys(types).reduce(function (prev, trans) { return undefined !== elem.style[trans] ? types[trans] : prev; }, ''); } module.exports = exports['default'];
/** * Constants */ KEYS_ESC = 27; KEYS_ENTER = 13; DATE_DISPLAY_FORMAT = '%m/%d/%Y'; TIME_DISPLAY_FORMAT = '%l:%M %P'; TIME_TO_EXPIRE = 1800; /** * Format a unix timestamp * * @param int timestamp unix timestamp * @param string format strftime format, only support a subset. seef formatUnix */ function formatUnix(timestamp, format){ if(typeof format == 'undefined'){ var format = '%Y-%m-%d %H:%M:%S'; } var date = fromUnix(timestamp); var hours = date.hours; var hours_12 = hours % 12; if(hours_12 == 0){ hours_12 = 12; } var tokens = format.match(/\%[a-z]/ig); for(var i = 0; i < tokens.length; i++){ var token = tokens[i]; var replace = null; switch(token){ case '%Y': replace = date.year; break; // case '%m': replace = date.month; break; case '%m': replace = strpad(date.month, 2, '0'); break; case '%B': replace = monthLabel(date.month); break; case '%d': replace = strpad(date.day, 2, '0'); break; case '%e': replace = date.day; break; case '%H': replace = strpad(hours, 2, '0'); break; case '%k': replace = hours; break; case '%I': replace = strpad(hours_12, 2, '0'); break; case '%l': replace = hours_12; break; case '%M': replace = strpad(date.minutes, 2, '0'); break; case '%S': replace = strpad(date.seconds, 2, '0'); break; case '%P': replace = date.pm ? 'PM' : 'AM'; break; case '%p': replace = date.pm ? 'pm' : 'am'; break; } if(replace){ format = format.replace(token, replace); } } return format; } function fromUnix(timestamp){ var date = new Date(timestamp * 1000); var hours = date.getHours(); var ret = { year: date.getFullYear(), month: date.getMonth() + 1, // zero based to one based day: date.getDate(), hours: hours, minutes: date.getMinutes(), seconds: date.getSeconds(), pm: hours >= 12 }; return ret; } function monthLabel(num){ var ret; switch(num){ case 1: ret = 'January'; break; case 2: ret = 'February'; break; case 3: ret = 'March'; break; case 4: ret = 'April'; break; case 5: ret = 'May'; break; case 6: ret = 'June'; break; case 7: ret = 'July'; break; case 8: ret = 'August'; break; case 9: ret = 'September'; break; case 10: ret = 'October'; break; case 11: ret = 'November'; break; case 12: ret = 'December'; break; } return ret; } function now(delta){ if(typeof delta == 'undefined'){ var delta = 0; } return Math.floor(((new Date()).getTime() + delta)/ 1000); } function rand(a, b){ if(typeof b == 'undefined'){ var min = 0; var max = a; } else { var min = a; var max = b; } return Math.floor(Math.random() * (max - min) + min); } function leftExtend(left, right){ if(typeof left != 'object' || typeof right != 'object'){ return left; } var new_obj = {}; $.each(left, function(k, v){ new_obj[k] = typeof right[k] == 'undefined' ? left[k] : right[k]; }); return new_obj; } /** * Similar to str_pad * * @param string str * @param int len target length * @param string pad string to pad with. default ' ' * @param string left_or_right values 'left' or 'right'. default 'left' */ function strpad(str, len, pad, left_or_right){ str = String(str); if(typeof pad == 'undefined'){ var pad = ' '; } if(typeof left_or_right == 'undefined'){ var left_or_right = 'left'; } while(str.length < len){ switch(left_or_right){ case 'left': str = pad + str; break; case 'right': str = str + pad; break; } } return str; } /** * Remove an element from an array by index */ Array.prototype.removeIdx = function(idx){ if(idx == 0){ return this.slice(1, this.length); } else if(idx == this.length - 1){ return this.slice(0, this.length - 1); } else { if(idx < 0){ idx = this.length - (Math.abs(idx) % this.length); } var right = this.slice(idx + 1, this.length); var left = this.slice(0, idx); left.push.apply(left, right); return left; } }; /** * Remove an element from an array by value */ Array.prototype.remove = function(value) { var ret = this; var idx = this.indexOf(value); if(idx >= 0){ ret = this.removeIdx(idx); } return ret; };