code
stringlengths
2
1.05M
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastefromword', 'pt-br', { confirmCleanup: 'O texto que você deseja colar parece ter sido copiado do Word. Você gostaria de remover a formatação antes de colar?', error: 'Não foi possível limpar os dados colados devido a um erro interno', title: 'Colar do Word', toolbar: 'Colar do Word' });
module.exports={title:"Bulma",slug:"bulma",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Bulma icon</title><path d="M11.25 0l-6 6 -1.5 10.5 7.5 7.5 9 -6 -6 -6 4.5 -4.5 -7.5 -7.5Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/jgthms/bulma/",hex:"00D1B2"};
var assert = require('assert') var UINT32 = require('..').UINT32 describe('and method', function () { describe('0&1', function () { it('should return 0', function (done) { var u = UINT32(0).and( UINT32(1) ) assert.equal( u.toNumber(), 0 ) done() }) }) describe('1&2', function () { it('should return 0', function (done) { var u = UINT32(1).and( UINT32(2) ) assert.equal( u.toNumber(), 0 ) done() }) }) describe('1&2^16', function () { it('should return 0', function (done) { var n = Math.pow(2, 16) var u = UINT32(1).and( UINT32(n) ) assert.equal( u.toNumber(), 0 ) done() }) }) describe('2^16&1', function () { it('should return 0', function (done) { var n = Math.pow(2, 16) var u = UINT32(n).and( UINT32(1) ) assert.equal( u.toNumber(), 0 ) done() }) }) describe('2^16&2^16', function () { it('should return n', function (done) { var n = Math.pow(2, 16) var u = UINT32(n).and( UINT32(n) ) assert.equal( u.toNumber(), n ) done() }) }) })
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _rest = require('./internal/rest'); var _rest2 = _interopRequireDefault(_rest); var _initialParams = require('./internal/initialParams'); var _initialParams2 = _interopRequireDefault(_initialParams); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Returns a function that when called, calls-back with the values provided. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to * [`auto`]{@link module:ControlFlow.auto}. * * @name constant * @static * @memberOf module:Utils * @method * @category Util * @param {...*} arguments... - Any number of arguments to automatically invoke * callback with. * @returns {AsyncFunction} Returns a function that when invoked, automatically * invokes the callback with the previous given arguments. * @example * * async.waterfall([ * async.constant(42), * function (value, next) { * // value === 42 * }, * //... * ], callback); * * async.waterfall([ * async.constant(filename, "utf8"), * fs.readFile, * function (fileData, next) { * //... * } * //... * ], callback); * * async.auto({ * hostname: async.constant("https://server.net/"), * port: findFreePort, * launchServer: ["hostname", "port", function (options, cb) { * startServer(options, cb); * }], * //... * }, callback); */ exports.default = (0, _rest2.default)(function (values) { var args = [null].concat(values); return (0, _initialParams2.default)(function (ignoredArgs, callback) { return callback.apply(this, args); }); }); module.exports = exports['default'];
/* * Copyright (c) 2013-2014 Chukong Technologies 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. */ /** * @type {Object} * @name jsb.AssetsManager * jsb.AssetsManager is the native AssetsManager for your game resources or scripts. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.AssetsManager = cc.AssetsManager; delete cc.AssetsManager; /** * @type {Object} * @name jsb.EventListenerAssetsManager * jsb.EventListenerAssetsManager is the native event listener for AssetsManager. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager; delete cc.EventListenerAssetsManager; /** * @type {Object} * @name jsb.EventAssetsManager * jsb.EventAssetsManager is the native event for AssetsManager. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.EventAssetsManager = cc.EventAssetsManager; delete cc.EventAssetsManager; // move from jsb_cocos2d //start------------------------------ cc.ControlButton.extend = cc.Class.extend; cc.ControlColourPicker.extend = cc.Class.extend; cc.ControlPotentiometer.extend = cc.Class.extend; cc.ControlSlider.extend = cc.Class.extend; cc.ControlStepper.extend = cc.Class.extend; cc.ControlSwitch.extend = cc.Class.extend; //end------------------------------ // // cocos2d constants // // This helper file should be required after jsb_cocos2d.js // var cc = cc || {}; cc.SCROLLVIEW_DIRECTION_NONE = -1; cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0; cc.SCROLLVIEW_DIRECTION_VERTICAL = 1; cc.SCROLLVIEW_DIRECTION_BOTH = 2; cc.TABLEVIEW_FILL_TOPDOWN = 0; cc.TABLEVIEW_FILL_BOTTOMUP = 1; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_DEFAULT = 0; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_DONE = 1; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_SEND = 2; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_SEARCH = 3; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_GO = 4; /** * The EditBox::InputMode defines the type of text that the user is allowed * to enter. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_ANY = 0; /** * The user is allowed to enter an e-mail address. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_EMAILADDR = 1; /** * The user is allowed to enter an integer value. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_NUMERIC = 2; /** * The user is allowed to enter a phone number. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3; /** * The user is allowed to enter a URL. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_URL = 4; /** * The user is allowed to enter a real number value. * This extends kEditBoxInputModeNumeric by allowing a decimal point. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_DECIMAL = 5; /** * The user is allowed to enter any text, except for line breaks. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_SINGLELINE = 6; /** * Indicates that the text entered is confidential data that should be * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_PASSWORD = 0; /** * Indicates that the text entered is sensitive data that the * implementation must never store into a dictionary or table for use * in predictive, auto-completing, or other accelerated input schemes. * A credit card number is an example of sensitive data. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1; /** * This flag is a hint to the implementation that during text editing, * the initial letter of each word should be capitalized. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2; /** * This flag is a hint to the implementation that during text editing, * the initial letter of each sentence should be capitalized. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3; /** * Capitalize all characters automatically. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4; cc.CONTROL_EVENT_TOTAL_NUMBER = 9; cc.CONTROL_EVENT_TOUCH_DOWN = 1 << 0; // A touch-down event in the control. cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE = 1 << 1; // An event where a finger is dragged inside the bounds of the control. cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE = 1 << 2; // An event where a finger is dragged just outside the bounds of the control. cc.CONTROL_EVENT_TOUCH_DRAG_ENTER = 1 << 3; // An event where a finger is dragged into the bounds of the control. cc.CONTROL_EVENT_TOUCH_DRAG_EXIT = 1 << 4; // An event where a finger is dragged from within a control to outside its bounds. cc.CONTROL_EVENT_TOUCH_UP_INSIDE = 1 << 5; // A touch-up event in the control where the finger is inside the bounds of the control. cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE = 1 << 6; // A touch-up event in the control where the finger is outside the bounds of the control. cc.CONTROL_EVENT_TOUCH_CANCEL = 1 << 7; // A system event canceling the current touches for the control. cc.CONTROL_EVENT_VALUECHANGED = 1 << 8; // A touch dragging or otherwise manipulating a control; causing it to emit a series of different values. cc.CONTROL_STATE_NORMAL = 1 << 0; // The normal; or default state of a control梩hat is; enabled but neither selected nor highlighted. cc.CONTROL_STATE_HIGHLIGHTED = 1 << 1; // Highlighted state of a control. A control enters this state when a touch down; drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. cc.CONTROL_STATE_DISABLED = 1 << 2; // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. cc.CONTROL_STATE_SELECTED = 1 << 3; // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. cc.CONTROL_STATE_INITIAL = 1 << 3; cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001; //CCControlButton.js cc.CONTROL_STEPPER_PARTMINUS = 0; //CCControlStepper.js cc.CONTROL_STEPPER_PARTPLUS = 1; cc.CONTROL_STEPPER_PARTNONE = 2; cc.CONTROL_STEPPER_LABELCOLOR_ENABLED = cc.color(55, 55, 55); cc.CONTROL_STEPPER_LABELCOLOR_DISABLED = cc.color(147, 147, 147); cc.CONTROL_STEPPER_LABELFONT = "CourierNewPSMT"; cc.AUTOREPEAT_DELTATIME = 0.15; cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12; jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0; jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1; jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2; jsb.EventAssetsManager.NEW_VERSION_FOUND = 3; jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4; jsb.EventAssetsManager.UPDATE_PROGRESSION = 5; jsb.EventAssetsManager.ASSET_UPDATED = 6; jsb.EventAssetsManager.ERROR_UPDATING = 7; jsb.EventAssetsManager.UPDATE_FINISHED = 8; jsb.EventAssetsManager.UPDATE_FAILED = 9; jsb.EventAssetsManager.ERROR_DECOMPRESS = 10; cc.ScrollView.extend = cc.Class.extend; cc.TableView.extend = cc.Class.extend; cc.TableViewCell.extend = cc.Class.extend;
CKEDITOR.plugins.setLang("autoembed","en-au",{embeddingInProgress:"Trying to embed pasted URL...",embeddingFailed:"This URL could not be automatically embedded."});
// ramda.js // https://github.com/CrossEye/ramda // (c) 2013-2014 Scott Sauyet and Michael Hurley // Ramda may be freely distributed under the MIT license. // Ramda // ----- // A practical functional library for Javascript programmers. Ramda is a collection of tools to make it easier to // use Javascript as a functional programming language. (The name is just a silly play on `lambda`.) // Basic Setup // ----------- // Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser, // with or without an AMD-style loader. // // [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js (function(factory) { if (typeof exports === 'object') { module.exports = factory(this); } else if (typeof define === 'function' && define.amd) { define(factory); } else { this.R = this.ramda = factory(this); } }(function() { 'use strict'; // This object is what is actually returned, with all the exposed functions attached as properties. /** * A practical functional library for Javascript programmers. * * @namespace R */ // jscs:disable disallowQuotedKeysInObjects var R = {'version': '0.5.0'}; // jscs:enable disallowQuotedKeysInObjects // Internal Functions and Properties // --------------------------------- /** * An optimized, private array `slice` implementation. * * @private * @category Internal * @param {Arguments|Array} args The array or arguments object to consider. * @param {number} [from=0] The array index to slice from, inclusive. * @param {number} [to=args.length] The array index to slice to, exclusive. * @return {Array} A new, sliced array. * @example * * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] * * var firstThreeArgs = function(a, b, c, d) { * return _slice(arguments, 0, 3); * }; * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3] */ function _slice(args, from, to) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return _slice(args, 0, args.length); case 2: return _slice(args, from, args.length); default: var length = to - from, list = new Array(length), idx = -1; while (++idx < length) { list[idx] = args[from + idx]; } return list; } } /** * Private `concat` function to merge two array-like objects. * * @private * @category Internal * @param {Array|Arguments} [set1=[]] An array-like object. * @param {Array|Arguments} [set2=[]] An array-like object. * @return {Array} A new, merged array. * @example * * concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] */ var concat = function _concat(set1, set2) { set1 = set1 || []; set2 = set2 || []; var length1 = set1.length, length2 = set2.length, result = new Array(length1 + length2); for (var idx = 0; idx < length1; idx++) { result[idx] = set1[idx]; } for (idx = 0; idx < length2; idx++) { result[idx + length1] = set2[idx]; } return result; }; // Private reference to toString function. var toString = Object.prototype.toString; /** * Tests whether or not an object is an array. * * @private * @category Internal * @param {*} val The object to test. * @return {boolean} `true` if `val` is an array, `false` otherwise. * @example * * isArray([]); //=> true * isArray(true); //=> false * isArray({}); //=> false */ var isArray = Array.isArray || function _isArray(val) { return val && val.length >= 0 && toString.call(val) === '[object Array]'; }; /** * Tests whether or not an object is similar to an array. * * @func * @category Type * @category List * @param {*} val The object to test. * @return {boolean} `true` if `val` has a numeric length property; `false` otherwise. * @example * * R.isArrayLike([]); //=> true * R.isArrayLike(true); //=> false * R.isArrayLike({}); //=> false * R.isArrayLike({length: 10}); //=> true */ R.isArrayLike = function isArrayLike(x) { return isArray(x) || ( !!x && typeof x === 'object' && !(x instanceof String) && ( !!(x.nodeType === 1 && x.length) || x.length >= 0 ) ); }; var NO_ARGS_EXCEPTION = new TypeError('Function called with no arguments'); /** * Optimized internal two-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} curried function * @example * * var addTwo = function(a, b) { * return a + b; * }; * * var curriedAddTwo = curry2(addTwo); */ function curry2(fn) { return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(b) { return fn(a, b); }; default: return fn(a, b); } }; } /** * Optimized internal three-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} curried function * @example * * var addThree = function(a, b, c) { * return a + b + c; * }; * * var curriedAddThree = curry3(addThree); */ function curry3(fn) { return function(a, b, c) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return curry2(function(b, c) { return fn(a, b, c); }); case 2: return function(c) { return fn(a, b, c); }; default: return fn(a, b, c); } }; } if (typeof Object.defineProperty === 'function') { try { Object.defineProperty(R, '_', {writable: false, value: void 0}); } catch (e) {} } var _ = R._; void _;// This intentionally left `undefined`. /** * Converts a function into something like an infix operation, meaning that * when called with a single argument, that argument is applied to the * second position, sort of a curry-right. This allows for more natural * processing of functions which are really binary operators. * * @memberOf R * @category Functions * @param {function} fn The operation to adjust * @return {function} A new function that acts somewhat like an infix operator. * @example * * var div = R.op(function (a, b) { * return a / b; * }); * * div(6, 3); //=> 2 * div(6, _)(3); //=> 2 // note: `_` here is just an `undefined` value. You could use `void 0` instead * div(3)(6); //=> 2 */ var op = R.op = function op(fn) { var length = fn.length; if (length < 2) {throw new Error('Expected binary function.');} var left = curry(fn), right = curry(R.flip(fn)); return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return right(a); case 2: return (b === R._) ? left(a) : left.apply(null, arguments); default: return left.apply(null, arguments); } }; }; /** * Creates a new version of `fn` with given arity that, when invoked, * will return either: * - A new function ready to accept one or more of `fn`'s remaining arguments, if all of * `fn`'s expected arguments have not yet been provided * - `fn`'s result if all of its expected arguments have been provided * * This function is useful in place of `curry`, when the arity of the * function to curry cannot be determined from its signature, e.g. if it's * a variadic function. * * @func * @memberOf R * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {number} fnArity The arity for the returned function. * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curry * @example * * var addFourNumbers = function() { * return R.sum([].slice.call(arguments, 0, 4)); * }; * * var curriedAddFourNumbers = R.curryN(4, addFourNumbers); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4);//=> 10 */ var curryN = R.curryN = function curryN(length, fn) { return (function recurry(args) { return arity(Math.max(length - (args && args.length || 0), 0), function() { if (arguments.length === 0) { throw NO_ARGS_EXCEPTION; } var newArgs = concat(args, arguments); if (newArgs.length >= length) { return fn.apply(this, newArgs); } else { return recurry(newArgs); } }); }([])); }; /** * Creates a new version of `fn` that, when invoked, will return either: * - A new function ready to accept one or more of `fn`'s remaining arguments, if all of * `fn`'s expected arguments have not yet been provided * - `fn`'s result if all of its expected arguments have been provided * * @func * @memberOf R * @category Function * @sig (* -> a) -> (* -> a) * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curryN * @example * * var addFourNumbers = function(a, b, c, d) { * return a + b + c + d; * }; * * var curriedAddFourNumbers = R.curry(addFourNumbers); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4);//=> 10 */ var curry = R.curry = function curry(fn) { return curryN(fn.length, fn); }; /** * Private function that determines whether or not a provided object has a given method. * Does not ignore methods stored on the object's prototype chain. Used for dynamically * dispatching Ramda methods to non-Array objects. * * @private * @category Internal * @param {string} methodName The name of the method to check for. * @param {Object} obj The object to test. * @return {boolean} `true` has a given method, `false` otherwise. * @example * * var person = { name: 'John' }; * person.shout = function() { alert(this.name); }; * * hasMethod('shout', person); //=> true * hasMethod('foo', person); //=> false */ var hasMethod = function _hasMethod(methodName, obj) { return obj && !isArray(obj) && typeof obj[methodName] === 'function'; }; /** * Similar to hasMethod, this checks whether a function has a [methodname] * function. If it isn't an array it will execute that function otherwise it will * default to the ramda implementation. * * @private * @category Internal * @param {Function} fn ramda implemtation * @param {String} methodname property to check for a custom implementation * @return {Object} whatever the return value of the method is */ function checkForMethod(methodname, fn) { return function(a, b, c) { var length = arguments.length; var obj = arguments[length - 1], callBound = obj && !isArray(obj) && typeof obj[methodname] === 'function'; switch (arguments.length) { case 0: return fn(); case 1: return callBound ? obj[methodname]() : fn(a); case 2: return callBound ? obj[methodname](a) : fn(a, b); case 3: return callBound ? obj[methodname](a, b) : fn(a, b, c); } }; } /** * Wraps a function of any arity (including nullary) in a function that accepts exactly `n` * parameters. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {number} n The desired arity of the new function. * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity `n`. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.nAry(1, takesTwoArgs); * takesOneArg.length; //=> 1 * // Only `n` arguments are passed to the wrapped function * takesOneArg(1, 2); //=> [1, undefined] */ var nAry = R.nAry = function(n, fn) { switch (n) { case 0: return function() {return fn.call(this);}; case 1: return function(a0) {return fn.call(this, a0);}; case 2: return function(a0, a1) {return fn.call(this, a0, a1);}; case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);}; case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);}; case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);}; case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);}; case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);}; case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);}; case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);}; case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);}; default: return fn; // TODO: or throw? } }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 * parameter. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig (* -> b) -> (a -> b) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 1. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.unary(takesTwoArgs); * takesOneArg.length; //=> 1 * // Only 1 argument is passed to the wrapped function * takesOneArg(1, 2); //=> [1, undefined] */ R.unary = function _unary(fn) { return nAry(1, fn); }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 * parameters. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig (* -> c) -> (a, b -> c) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 2. * @example * * var takesThreeArgs = function(a, b, c) { * return [a, b, c]; * }; * takesThreeArgs.length; //=> 3 * takesThreeArgs(1, 2, 3); //=> [1, 2, 3] * * var takesTwoArgs = R.binary(takesThreeArgs); * takesTwoArgs.length; //=> 2 * // Only 2 arguments are passed to the wrapped function * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] */ var binary = R.binary = function _binary(fn) { return nAry(2, fn); }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly `n` * parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function, * functions produced by `arity` will pass all provided arguments to the wrapped function. * * @func * @memberOf R * @sig (Number, (* -> *)) -> (* -> *) * @category Function * @param {number} n The desired arity of the returned function. * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is * guaranteed to be of arity `n`. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.arity(1, takesTwoArgs); * takesOneArg.length; //=> 1 * // All arguments are passed through to the wrapped function * takesOneArg(1, 2); //=> [1, 2] */ var arity = R.arity = function(n, fn) { switch (n) { case 0: return function() {return fn.apply(this, arguments);}; case 1: return function(a0) {void a0; return fn.apply(this, arguments);}; case 2: return function(a0, a1) {void a1; return fn.apply(this, arguments);}; case 3: return function(a0, a1, a2) {void a2; return fn.apply(this, arguments);}; case 4: return function(a0, a1, a2, a3) {void a3; return fn.apply(this, arguments);}; case 5: return function(a0, a1, a2, a3, a4) {void a4; return fn.apply(this, arguments);}; case 6: return function(a0, a1, a2, a3, a4, a5) {void a5; return fn.apply(this, arguments);}; case 7: return function(a0, a1, a2, a3, a4, a5, a6) {void a6; return fn.apply(this, arguments);}; case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {void a7; return fn.apply(this, arguments);}; case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {void a8; return fn.apply(this, arguments);}; case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {void a9; return fn.apply(this, arguments);}; default: return fn; // TODO: or throw? } }; /** * Turns a named method of an object (or object prototype) into a function that can be * called directly. Passing the optional `len` parameter restricts the returned function to * the initial `len` parameters of the method. * * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` * when `len` is not specified), and the final parameter is the target object. * * @func * @memberOf R * @category Function * @sig (String, Object, Number) -> (* -> *) * @param {string} name The name of the method to wrap. * @param {Object} obj The object to search for the `name` method. * @param [len] The desired arity of the wrapped method. * @return {Function} A new function or `undefined` if the specified method is not found. * @example * * var charAt = R.invoker('charAt', String.prototype); * charAt(6, 'abcdefghijklm'); //=> 'g' * * var join = R.invoker('join', Array.prototype); * var firstChar = charAt(0); * join('', R.map(firstChar, ['light', 'ampliifed', 'stimulated', 'emission', 'radiation'])); * //=> 'laser' */ var invoker = R.invoker = function _invoker(name, obj, len) { var method = obj[name]; var length = len === void 0 ? method.length : len; return method && curryN(length + 1, function() { if (arguments.length) { var target = Array.prototype.pop.call(arguments); var targetMethod = target[name]; if (targetMethod == method) { return targetMethod.apply(target, arguments); } } }); }; /** * Accepts a function `fn` and any number of transformer functions and returns a new * function. When the new function is invoked, it calls the function `fn` with parameters * consisting of the result of calling each supplied handler on successive arguments to the * new function. For example: * * ```javascript * var useWithExample = R.useWith(someFn, transformerFn1, transformerFn2); * * // This invocation: * useWithExample('x', 'y'); * // Is functionally equivalent to: * someFn(transformerFn1('x'), transformerFn2('y')) * ``` * * If more arguments are passed to the returned function than transformer functions, those * arguments are passed directly to `fn` as additional parameters. If you expect additional * arguments that don't need to be transformed, although you can ignore them, it's best to * pass an identity function so that the new function reports the correct arity. * * @func * @memberOf R * @category Function * @sig ((* -> *), (* -> *)...) -> (* -> *) * @param {Function} fn The function to wrap. * @param {...Function} transformers A variable number of transformer functions * @return {Function} The wrapped function. * @example * * var double = function(y) { return y * 2; }; * var square = function(x) { return x * x; }; * var add = function(a, b) { return a + b; }; * // Adds any number of arguments together * var addAll = function() { * return R.reduce(add, 0, arguments); * }; * * // Basic example * var addDoubleAndSquare = R.useWith(addAll, double, square); * * //≅ addAll(double(10), square(5)); * addDoubleAndSquare(10, 5); //=> 45 * * // Example of passing more arguments than transformers * //≅ addAll(double(10), square(5), 100); * addDoubleAndSquare(10, 5, 100); //=> 145 * * // But if you're expecting additional arguments that don't need transformation, it's best * // to pass transformer functions so the resulting function has the correct arity * var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity); * //≅ addAll(double(10), square(5), R.identity(100)); * addDoubleAndSquare(10, 5, 100); //=> 145 */ var useWith = R.useWith = function _useWith(fn /*, transformers */) { var transformers = _slice(arguments, 1); var tlen = transformers.length; return curry(arity(tlen, function() { var args = [], idx = -1; while (++idx < tlen) { args.push(transformers[idx](arguments[idx])); } return fn.apply(this, args.concat(_slice(arguments, tlen))); })); }; /** * Iterate over an input `list`, calling a provided function `fn` for each element in the * list. * * `fn` receives one argument: *(value)*. * * Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.forEach` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description * * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original * array. In some libraries this function is named `each`. * * @func * @memberOf R * @category List * @sig (a -> *) -> [a] -> [a] * @param {Function} fn The function to invoke. Receives one argument, `value`. * @param {Array} list The list to iterate over. * @return {Array} The original list. * @example * * var printXPlusFive = function(x) { console.log(x + 5); }; * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] * //-> 6 * //-> 7 * //-> 8 */ function forEach(fn, list) { var idx = -1, len = list.length; while (++idx < len) { fn(list[idx]); } // i can't bear not to return *something* return list; } R.forEach = curry2(forEach); /** * Like `forEach`, but but passes additional parameters to the predicate function. * * `fn` receives three arguments: *(value, index, list)*. * * Note: `R.forEach.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.forEach` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description * * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original * array. In some libraries this function is named `each`. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> ) -> [a] -> [a] * @param {Function} fn The function to invoke. Receives three arguments: * (`value`, `index`, `list`). * @param {Array} list The list to iterate over. * @return {Array} The original list. * @alias forEach.idx * @example * * // Note that having access to the original `list` allows for * // mutation. While you *can* do this, it's very un-functional behavior: * var plusFive = function(num, idx, list) { list[idx] = num + 5 }; * R.forEach.idx(plusFive, [1, 2, 3]); //=> [6, 7, 8] */ R.forEach.idx = curry2(function forEachIdx(fn, list) { var idx = -1, len = list.length; while (++idx < len) { fn(list[idx], idx, list); } // i can't bear not to return *something* return list; }); /** * Creates a shallow copy of an array. * * @func * @memberOf R * @category Array * @sig [a] -> [a] * @param {Array} list The list to clone. * @return {Array} A new copy of the original list. * @example * * var numbers = [1, 2, 3]; * var numbersClone = R.clone(numbers); //=> [1, 2, 3] * numbers === numbersClone; //=> false * * // Note that this is a shallow clone--it does not clone complex values: * var objects = [{}, {}, {}]; * var objectsClone = R.clone(objects); * objects[0] === objectsClone[0]; //=> true */ var clone = R.clone = function _clone(list) { return _slice(list); }; // Core Functions // -------------- // /** * Reports whether an array is empty. * * @func * @memberOf R * @category Array * @sig [a] -> Boolean * @param {Array} list The array to consider. * @return {boolean} `true` if the `list` argument has a length of 0 or * if `list` is a falsy value (e.g. undefined). * @example * * R.isEmpty([1, 2, 3]); //=> false * R.isEmpty([]); //=> true * R.isEmpty(); //=> true * R.isEmpty(null); //=> true */ function isEmpty(list) { return !list || !list.length; } R.isEmpty = isEmpty; /** * Returns a new list with the given element at the front, followed by the contents of the * list. * * @func * @memberOf R * @category Array * @sig a -> [a] -> [a] * @param {*} el The item to add to the head of the output list. * @param {Array} list The array to add to the tail of the output list. * @return {Array} A new array. * @example * * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] */ R.prepend = curry2(function prepend(el, list) { return concat([el], list); }); /** * @func * @memberOf R * @category Array * @see R.prepend */ R.cons = R.prepend; /** * Returns the first element in a list. * In some libraries this function is named `first`. * * @func * @memberOf R * @category Array * @sig [a] -> a * @param {Array} [list=[]] The array to consider. * @return {*} The first element of the list, or `undefined` if the list is empty. * @example * * R.head(['fi', 'fo', 'fum']); //=> 'fi' */ R.head = function head(list) { list = list || []; return list[0]; }; /** * @func * @memberOf R * @category Array * @see R.head */ R.car = R.head; /** * Returns the last element from a list. * * @func * @memberOf R * @category Array * @sig [a] -> a * @param {Array} [list=[]] The array to consider. * @return {*} The last element of the list, or `undefined` if the list is empty. * @example * * R.last(['fi', 'fo', 'fum']); //=> 'fum' */ R.last = function _last(list) { list = list || []; return list[list.length - 1]; }; /** * Returns all but the first element of a list. If the list provided has the `tail` method, * it will instead return `list.tail()`. * * @func * @memberOf R * @category Array * @sig [a] -> [a] * @param {Array} [list=[]] The array to consider. * @return {Array} A new array containing all but the first element of the input list, or an * empty list if the input list is a falsy value (e.g. `undefined`). * @example * * R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] */ R.tail = checkForMethod('tail', function(list) { list = list || []; return (list.length > 1) ? _slice(list, 1) : []; }); /** * @func * @memberOf R * @category Array * @see R.tail */ R.cdr = R.tail; /** * Returns a new list containing the contents of the given list, followed by the given * element. * * @func * @memberOf R * @category Array * @sig a -> [a] -> [a] * @param {*} el The element to add to the end of the new list. * @param {Array} list The list whose contents will be added to the beginning of the output * list. * @return {Array} A new list containing the contents of the old list followed by `el`. * @example * * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] * R.append('tests', []); //=> ['tests'] * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] */ var append = R.append = curry2(function _append(el, list) { return concat(list, [el]); }); /** * @func * @memberOf R * @category Array * @see R.append */ R.push = R.append; /** * Returns a new list consisting of the elements of the first list followed by the elements * of the second. * * @func * @memberOf R * @category Array * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list to merge. * @param {Array} list2 The second set to merge. * @return {Array} A new array consisting of the contents of `list1` followed by the * contents of `list2`. If, instead of an {Array} for `list1`, you pass an * object with a `concat` method on it, `concat` will call `list1.concat` * and it the value of `list2`. * @example * * R.concat([], []); //=> [] * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] * R.concat('ABC', 'DEF'); // 'ABCDEF' */ R.concat = curry2(function(set1, set2) { if (isArray(set2)) { return concat(set1, set2); } else if (R.is(String, set1)) { return set1.concat(set2); } else if (hasMethod('concat', set2)) { return set2.concat(set1); } else { throw new TypeError("can't concat " + typeof set2); } }); /** * A function that does nothing but return the parameter supplied to it. Good as a default * or placeholder function. * * @func * @memberOf R * @category Core * @sig a -> a * @param {*} x The value to return. * @return {*} The input value, `x`. * @example * * R.identity(1); //=> 1 * * var obj = {}; * R.identity(obj) === obj; //=> true */ var identity = R.identity = function _I(x) { return x; }; /** * @func * @memberOf R * @category Core * @see R.identity */ R.I = R.identity; /** * Calls an input function `n` times, returning an array containing the results of those * function calls. * * `fn` is passed one argument: The current value of `n`, which begins at `0` and is * gradually incremented to `n - 1`. * * @func * @memberOf R * @category List * @sig (i -> a) -> i -> [a] * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`. * @param {number} n A value between `0` and `n - 1`. Increments after each function call. * @return {Array} An array containing the return values of all calls to `fn`. * @example * * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] */ R.times = curry2(function _times(fn, n) { var list = new Array(n); var idx = -1; while (++idx < n) { list[idx] = fn(idx); } return list; }); /** * Returns a fixed list of size `n` containing a specified identical value. * * @func * @memberOf R * @category Array * @sig a -> n -> [a] * @param {*} value The value to repeat. * @param {number} n The desired size of the output list. * @return {Array} A new array containing `n` `value`s. * @example * * R.repeatN('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] * * var obj = {}; * var repeatedObjs = R.repeatN(obj, 5); //=> [{}, {}, {}, {}, {}] * repeatedObjs[0] === repeatedObjs[1]; //=> true */ R.repeatN = curry2(function _repeatN(value, n) { return R.times(R.always(value), n); }); // Function functions :-) // ---------------------- // // These functions make new functions out of old ones. // -------- /** * Basic, right-associative composition function. Accepts two functions and returns the * composite function; this composite function represents the operation `var h = f(g(x))`, * where `f` is the first argument, `g` is the second argument, and `x` is whatever * argument(s) are passed to `h`. * * This function's main use is to build the more general `compose` function, which accepts * any number of functions. * * @private * @category Function * @param {Function} f A function. * @param {Function} g A function. * @return {Function} A new function that is the equivalent of `f(g(x))`. * @example * * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDouble = internalCompose(double, square); * * squareThenDouble(5); //≅ double(square(5)) => 50 */ function internalCompose(f, g) { return function() { return f.call(this, g.apply(this, arguments)); }; } /** * Creates a new function that runs each of the functions supplied as parameters in turn, * passing the return value of each function invocation to the next function invocation, * beginning with whatever arguments were passed to the initial invocation. * * Note that `compose` is a right-associative function, which means the functions provided * will be invoked in order from right to left. In the example `var h = compose(f, g)`, * the function `h` is equivalent to `f( g(x) )`, where `x` represents the arguments * originally passed to `h`. * * @func * @memberOf R * @category Function * @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z) * @param {...Function} functions A variable number of functions. * @return {Function} A new function which represents the result of calling each of the * input `functions`, passing the result of each function call to the next, from * right to left. * @example * * var triple = function(x) { return x * 3; }; * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDoubleThenTriple = R.compose(triple, double, square); * * //≅ triple(double(square(5))) * squareThenDoubleThenTriple(5); //=> 150 */ var compose = R.compose = function _compose() { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return arguments[0]; default: var idx = arguments.length - 1, fn = arguments[idx], length = fn.length; while (idx--) { fn = internalCompose(arguments[idx], fn); } return arity(length, fn); } }; /** * Creates a new function that runs each of the functions supplied as parameters in turn, * passing the return value of each function invocation to the next function invocation, * beginning with whatever arguments were passed to the initial invocation. * * `pipe` is the mirror version of `compose`. `pipe` is left-associative, which means that * each of the functions provided is executed in order from left to right. * * In some libraries this function is named `sequence`. * @func * @memberOf R * @category Function * @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z) * @param {...Function} functions A variable number of functions. * @return {Function} A new function which represents the result of calling each of the * input `functions`, passing the result of each function call to the next, from * right to left. * @example * * var triple = function(x) { return x * 3; }; * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDoubleThenTriple = R.pipe(square, double, triple); * * //≅ triple(double(square(5))) * squareThenDoubleThenTriple(5); //=> 150 */ R.pipe = function _pipe() { return compose.apply(this, _slice(arguments).reverse()); }; /** * Returns a new function much like the supplied one, except that the first two arguments' * order is reversed. * * @func * @memberOf R * @category Function * @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z) * @param {Function} fn The function to invoke with its first two parameters reversed. * @return {*} The result of invoking `fn` with its first two parameters' order reversed. * @example * * var mergeThree = function(a, b, c) { * return ([]).concat(a, b, c); * }; * * mergeThree(1, 2, 3); //=> [1, 2, 3] * * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] */ var flip = R.flip = function _flip(fn) { return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(b) { return fn.apply(this, [b, a].concat(_slice(arguments, 1))); }; default: return fn.apply(this, concat([b, a], _slice(arguments, 2))); } }; }; /** * Accepts as its arguments a function and any number of values and returns a function that, * when invoked, calls the original function with all of the values prepended to the * original function's arguments list. In some libraries this function is named `applyLeft`. * * @func * @memberOf R * @category Function * @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n) * @param {Function} fn The function to invoke. * @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked. * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` * with `args` prepended to `fn`'s arguments list. * @example * * var multiply = function(a, b) { return a * b; }; * var double = R.lPartial(multiply, 2); * double(2); //=> 4 * * var greet = function(salutation, title, firstName, lastName) { * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; * }; * var sayHello = R.lPartial(greet, 'Hello'); * var sayHelloToMs = R.lPartial(sayHello, 'Ms.'); * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' */ R.lPartial = function _lPartial(fn /*, args */) { var args = _slice(arguments, 1); return arity(Math.max(fn.length - args.length, 0), function() { return fn.apply(this, concat(args, arguments)); }); }; /** * Accepts as its arguments a function and any number of values and returns a function that, * when invoked, calls the original function with all of the values appended to the original * function's arguments list. * * Note that `rPartial` is the opposite of `lPartial`: `rPartial` fills `fn`'s arguments * from the right to the left. In some libraries this function is named `applyRight`. * * @func * @memberOf R * @category Function * @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i) * @param {Function} fn The function to invoke. * @param {...*} [args] Arguments to append to `fn` when the returned function is invoked. * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with * `args` appended to `fn`'s arguments list. * @example * * var greet = function(salutation, title, firstName, lastName) { * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; * }; * var greetMsJaneJones = R.rPartial(greet, 'Ms.', 'Jane', 'Jones'); * * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' */ R.rPartial = function _rPartial(fn) { var args = _slice(arguments, 1); return arity(Math.max(fn.length - args.length, 0), function() { return fn.apply(this, concat(arguments, args)); }); }; /** * Creates a new function that, when invoked, caches the result of calling `fn` for a given * argument set and returns the result. Subsequent calls to the memoized `fn` with the same * argument set will not result in an additional call to `fn`; instead, the cached result * for that set of arguments will be returned. * * Note that this version of `memoize` effectively handles only string and number * parameters. Also note that it does not work on variadic functions. * * @func * @memberOf R * @category Function * @sig (a... -> b) -> (a... -> b) * @param {Function} fn The function to be wrapped by `memoize`. * @return {Function} Returns a memoized version of `fn`. * @example * * var numberOfCalls = 0; * var trackedAdd = function(a, b) { * numberOfCalls += 1; * return a + b; * }; * var memoTrackedAdd = R.memoize(trackedAdd); * * memoTrackedAdd(1, 2); //=> 3 * numberOfCalls; //=> 1 * memoTrackedAdd(1, 2); //=> 3 * numberOfCalls; //=> 1 * memoTrackedAdd(2, 3); //=> 5 * numberOfCalls; //=> 2 * * // Note that argument order matters * memoTrackedAdd(2, 1); //=> 3 * numberOfCalls; //=> 3 */ R.memoize = function _memoize(fn) { if (!fn.length) { return once(fn); } var cache = {}; return function() { if (!arguments.length) {return;} var position = foldl(function(cache, arg) { return cache[arg] || (cache[arg] = {}); }, cache, _slice(arguments, 0, arguments.length - 1)); var arg = arguments[arguments.length - 1]; return (position[arg] || (position[arg] = fn.apply(this, arguments))); }; }; /** * Accepts a function `fn` and returns a function that guards invocation of `fn` such that * `fn` can only ever be called once, no matter how many times the returned function is * invoked. * * @func * @memberOf R * @category Function * @sig (a... -> b) -> (a... -> b) * @param {Function} fn The function to wrap in a call-only-once wrapper. * @return {Function} The wrapped function. * @example * * var addOneOnce = R.once(function(x){ return x + 1; }); * addOneOnce(10); //=> 11 * addOneOnce(addOneOnce(50)); //=> 11 */ var once = R.once = function _once(fn) { var called = false, result; return function() { if (called) { return result; } called = true; result = fn.apply(this, arguments); return result; }; }; /** * Wrap a function inside another to allow you to make adjustments to the parameters, or do * other processing either before the internal function is called or with its results. * * @func * @memberOf R * @category Function * ((* -> *) -> ((* -> *), a...) -> (*, a... -> *) * @param {Function} fn The function to wrap. * @param {Function} wrapper The wrapper function. * @return {Function} The wrapped function. * @example * * var slashify = R.wrap(R.flip(add)('/'), function(f, x) { * return R.match(/\/$/, x) ? x : f(x); * }); * * slashify('a'); //=> 'a/' * slashify('a/'); //=> 'a/' */ R.wrap = function _wrap(fn, wrapper) { return function() { return wrapper.apply(this, concat([fn], arguments)); }; }; /** * Wraps a constructor function inside a curried function that can be called with the same * arguments and returns the same type. The arity of the function returned is specified * to allow using variadic constructor functions. * * NOTE: Does not work with some built-in objects such as Date. * * @func * @memberOf R * @category Function * @sig Number -> (* -> {*}) -> (* -> {*}) * @param {number} n The arity of the constructor function. * @param {Function} Fn The constructor function to wrap. * @return {Function} A wrapped, curried constructor function. * @example * * // Variadic constructor function * var Widget = function() { * this.children = Array.prototype.slice.call(arguments); * // ... * }; * Widget.prototype = { * // ... * }; * var allConfigs = { * // ... * }; * R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets */ var constructN = R.constructN = curry2(function _constructN(n, Fn) { var f = function() { var Temp = function() {}, inst, ret; Temp.prototype = Fn.prototype; inst = new Temp(); ret = Fn.apply(inst, arguments); return Object(ret) === ret ? ret : inst; }; return n > 1 ? curry(nAry(n, f)) : f; }); /** * Wraps a constructor function inside a curried function that can be called with the same * arguments and returns the same type. * * NOTE: Does not work with some built-in objects such as Date. * * @func * @memberOf R * @category Function * @sig (* -> {*}) -> (* -> {*}) * @param {Function} Fn The constructor function to wrap. * @return {Function} A wrapped, curried constructor function. * @example * * // Constructor function * var Widget = function(config) { * // ... * }; * Widget.prototype = { * // ... * }; * var allConfigs = { * // ... * }; * R.map(R.construct(Widget), allConfigs); // a list of Widgets */ R.construct = function _construct(Fn) { return constructN(Fn.length, Fn); }; /** * Accepts three functions and returns a new function. When invoked, this new function will * invoke the first function, `after`, passing as its arguments the results of invoking the * second and third functions with whatever arguments are passed to the new function. * * For example, a function produced by `converge` is equivalent to: * * ```javascript * var h = R.converge(e, f, g); * h(1, 2); //≅ e( f(1, 2), g(1, 2) ) * ``` * * @func * @memberOf R * @category Function * @sig ((a, b -> c) -> (((* -> a), (* -> b), ...) -> c) * @param {Function} after A function. `after` will be invoked with the return values of * `fn1` and `fn2` as its arguments. * @param {Function} fn1 A function. It will be invoked with the arguments passed to the * returned function. Afterward, its resulting value will be passed to `after` as * its first argument. * @param {Function} fn2 A function. It will be invoked with the arguments passed to the * returned function. Afterward, its resulting value will be passed to `after` as * its second argument. * @return {Function} A new function. * @example * * var add = function(a, b) { return a + b; }; * var multiply = function(a, b) { return a * b; }; * var subtract = function(a, b) { return a - b; }; * * //≅ multiply( add(1, 2), subtract(1, 2) ); * R.converge(multiply, add, subtract)(1, 2); //=> -3 */ R.converge = function(after) { var fns = _slice(arguments, 1); return function() { var args = arguments; return after.apply(this, map(function(fn) { return fn.apply(this, args); }, fns)); }; }; // List Functions // -------------- // // These functions operate on logical lists, here plain arrays. Almost all of these are curried, and the list // parameter comes last, so you can create a new function by supplying the preceding arguments, leaving the // list parameter off. For instance: // // // skip third parameter // var checkAllPredicates = reduce(andFn, alwaysTrue); // // ... given suitable definitions of odd, lt20, gt5 // var test = checkAllPredicates([odd, lt20, gt5]); // // test(7) => true, test(9) => true, test(10) => false, // // test(3) => false, test(21) => false, // -------- /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. * * The iterator function receives two values: *(acc, value)* * * Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.reduce` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives two values, the accumulator and the * current element from the array. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @example * * var numbers = [1, 2, 3]; * var add = function(a, b) { * return a + b; * }; * * R.reduce(add, 10, numbers); //=> 16 */ R.reduce = curry3(function _reduce(fn, acc, list) { var idx = -1, len = list.length; while (++idx < len) { acc = fn(acc, list[idx]); } return acc; }); /** * @func * @memberOf R * @category List * @see R.reduce */ var foldl = R.foldl = R.reduce; /** * Like `reduce`, but passes additional parameters to the predicate function. * * The iterator function receives four values: *(acc, value, index, list)* * * Note: `R.reduce.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.reduce` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b,i,[b] -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives four values: the accumulator, the * current element from `list`, that element's index, and the entire `list` itself. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @alias reduce.idx * @example * * var letters = ['a', 'b', 'c']; * var objectify = function(accObject, elem, idx, list) { * accObject[elem] = idx; * return accObject; * }; * * R.reduce.idx(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } */ R.reduce.idx = curry3(function _reduceIdx(fn, acc, list) { var idx = -1, len = list.length; while (++idx < len) { acc = fn(acc, list[idx], idx, list); } return acc; }); /** * @func * @memberOf R * @category List * @alias foldl.idx * @see R.reduce.idx */ R.foldl.idx = R.reduce.idx; /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. * * Similar to `reduce`, except moves through the input list from the right to the left. * * The iterator function receives two values: *(acc, value)* * * Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.reduce` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives two values, the accumulator and the * current element from the array. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @example * * var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; * var flattenPairs = function(acc, pair) { * return acc.concat(pair); * }; * * R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] */ R.reduceRight = curry3(checkForMethod('reduceRight', function _reduceRight(fn, acc, list) { var idx = list.length; while (idx--) { acc = fn(acc, list[idx]); } return acc; })); /** * @func * @memberOf R * @category List * @see R.reduceRight */ R.foldr = R.reduceRight; /** * Like `reduceRight`, but passes additional parameters to the predicate function. Moves through * the input list from the right to the left. * * The iterator function receives four values: *(acc, value, index, list)*. * * Note: `R.reduceRight.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.reduce` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b,i,[b] -> a -> [b] -> a * @param {Function} fn The iterator function. Receives four values: the accumulator, the * current element from `list`, that element's index, and the entire `list` itself. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @alias reduceRight.idx * @example * * var letters = ['a', 'b', 'c']; * var objectify = function(accObject, elem, idx, list) { * accObject[elem] = idx; * return accObject; * }; * * R.reduceRight.idx(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 } */ R.reduceRight.idx = curry3(function _reduceRightIdx(fn, acc, list) { var idx = list.length; while (idx--) { acc = fn(acc, list[idx], idx, list); } return acc; }); /** * @func * @memberOf R * @category List * @alias foldr.idx * @see R.reduceRight.idx */ R.foldr.idx = R.reduceRight.idx; /** * Builds a list from a seed value. Accepts an iterator function, which returns either false * to stop iteration or an array of length 2 containing the value to add to the resulting * list and the seed to be used in the next call to the iterator function. * * The iterator function receives one argument: *(seed)*. * * @func * @memberOf R * @category List * @sig (a -> [b]) -> * -> [b] * @param {Function} fn The iterator function. receives one argument, `seed`, and returns * either false to quit iteration or an array of length two to proceed. The element * at index 0 of this array will be added to the resulting array, and the element * at index 1 will be passed to the next call to `fn`. * @param {*} seed The seed value. * @return {Array} The final list. * @example * * var f = function(n) { return n > 50 ? false : [-n, n + 10] }; * R.unfoldr(f, 10); //=> [-10, -20, -30, -40, -50] */ R.unfoldr = curry2(function _unfoldr(fn, seed) { var pair = fn(seed); var result = []; while (pair && pair.length) { result.push(pair[0]); pair = fn(pair[1]); } return result; }); /** * Returns a new list, constructed by applying the supplied function to every element of the * supplied list. * * Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the * native `Array.prototype.map` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description * * @func * @memberOf R * @category List * @sig (a -> b) -> [a] -> [b] * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @example * * var double = function(x) { * return x * 2; * }; * * R.map(double, [1, 2, 3]); //=> [2, 4, 6] */ function map(fn, list) { var idx = -1, len = list.length, result = new Array(len); while (++idx < len) { result[idx] = fn(list[idx]); } return result; } R.map = curry2(checkForMethod('map', map)); /** * Like `map`, but but passes additional parameters to the mapping function. * `fn` receives three arguments: *(value, index, list)*. * * Note: `R.map.idx` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.map` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description * * @func * @memberOf R * @category List * @sig (a,i,[b] -> b) -> [a] -> [b] * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @alias map.idx * @example * * var squareEnds = function(elt, idx, list) { * if (idx === 0 || idx === list.length - 1) { * return elt * elt; * } * return elt; * }; * * R.map.idx(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] */ R.map.idx = curry2(function _mapIdx(fn, list) { var idx = -1, len = list.length, result = new Array(len); while (++idx < len) { result[idx] = fn(list[idx], idx, list); } return result; }); /** * Map, but for objects. Creates an object with the same keys as `obj` and values * generated by running each property of `obj` through `fn`. `fn` is passed one argument: * *(value)*. * * @func * @memberOf R * @category List * @sig (v -> v) -> {k: v} -> {k: v} * @param {Function} fn A function called for each property in `obj`. Its return value will * become a new property on the return object. * @param {Object} obj The object to iterate over. * @return {Object} A new object with the same keys as `obj` and values that are the result * of running each property through `fn`. * @example * * var values = { x: 1, y: 2, z: 3 }; * var double = function(num) { * return num * 2; * }; * * R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 } */ // TODO: consider mapObj.key in parallel with mapObj.idx. Also consider folding together with `map` implementation. R.mapObj = curry2(function _mapObject(fn, obj) { return foldl(function(acc, key) { acc[key] = fn(obj[key]); return acc; }, {}, keys(obj)); }); /** * Like `mapObj`, but but passes additional arguments to the predicate function. The * predicate function is passed three arguments: *(value, key, obj)*. * * @func * @memberOf R * @category List * @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v} * @param {Function} fn A function called for each property in `obj`. Its return value will * become a new property on the return object. * @param {Object} obj The object to iterate over. * @return {Object} A new object with the same keys as `obj` and values that are the result * of running each property through `fn`. * @alias mapObj.idx * @example * * var values = { x: 1, y: 2, z: 3 }; * var prependKeyAndDouble = function(num, key, obj) { * return key + (num * 2); * }; * * R.mapObj.idx(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } */ R.mapObj.idx = curry2(function mapObjectIdx(fn, obj) { return foldl(function(acc, key) { acc[key] = fn(obj[key], key, obj); return acc; }, {}, keys(obj)); }); /** * ap applies a list of functions to a list of values. * * @func * @memberOf R * @category Function * @sig [f] -> [a] -> [f a] * @param {Array} fns An array of functions * @param {Array} vs An array of values * @return the value of applying each the function `fns` to each value in `vs` * @example * * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] */ R.ap = curry2(function _ap(fns, vs) { return hasMethod('ap', fns) ? fns.ap(vs) : foldl(function(acc, fn) { return concat(acc, map(fn, vs)); }, [], fns); }); /** * * `of` wraps any object in an Array. This implementation is compatible with the * Fantasy-land Applicative spec, and will work with types that implement that spec. * Note this `of` is different from the ES6 `of`; See * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of * * @func * @memberOf R * @category Function * @sig a -> [a] * @param {*} x any value * @return [x] * @example * * R.of(1); //=> [1] * R.of([2]); //=> [[2]] * R.of({}); //=> [{}] */ R.of = function _of(x, container) { return (hasMethod('of', container)) ? container.of(x) : [x]; }; /** * `empty` wraps any object in an array. This implementation is compatible with the * Fantasy-land Monoid spec, and will work with types that implement that spec. * * @func * @memberOf R * @category Function * @sig * -> [] * @return {Array} an empty array * @example * * R.empty([1,2,3,4,5]); //=> [] */ R.empty = function _empty(x) { return (hasMethod('empty', x)) ? x.empty() : []; }; /** * `chain` maps a function over a list and concatenates the results. * This implementation is compatible with the * Fantasy-land Chain spec, and will work with types that implement that spec. * `chain` is also known as `flatMap` in some libraries * * @func * @memberOf R * @category List * @sig (a -> [b]) -> [a] -> [b] * @param {Function} fn * @param {Array} list * @return {Array} * @example * * var duplicate = function(n) { * return [n, n]; * }; * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] * */ R.chain = curry2(checkForMethod('chain', function _chain(f, list) { return unnest(map(f, list)); })); /** * Returns the number of elements in the array by returning `list.length`. * * @func * @memberOf R * @category List * @sig [a] -> Number * @param {Array} list The array to inspect. * @return {number} The size of the array. * @example * * R.size([]); //=> 0 * R.size([1, 2, 3]); //=> 3 */ R.size = function _size(list) { return list.length; }; /** * @func * @memberOf R * @category List * @see R.size */ R.length = R.size; /** * Returns a new list containing only those items that match a given predicate function. * The predicate function is passed one argument: *(value)*. * * Note that `R.filter` does not skip deleted or unassigned indices, unlike the native * `Array.prototype.filter` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @example * * var isEven = function(n) { * return n % 2 === 0; * }; * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] */ var filter = function _filter(fn, list) { var idx = -1, len = list.length, result = []; while (++idx < len) { if (fn(list[idx])) { result.push(list[idx]); } } return result; }; R.filter = curry2(checkForMethod('filter', filter)); /** * Like `filter`, but passes additional parameters to the predicate function. The predicate * function is passed three arguments: *(value, index, list)*. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @alias filter.idx * @example * * var lastTwo = function(val, idx, list) { * return list.length - idx <= 2; * }; * R.filter.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] */ function filterIdx(fn, list) { var idx = -1, len = list.length, result = []; while (++idx < len) { if (fn(list[idx], idx, list)) { result.push(list[idx]); } } return result; } R.filter.idx = curry2(filterIdx); /** * Similar to `filter`, except that it keeps only values for which the given predicate * function returns falsy. The predicate function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @example * * var isOdd = function(n) { * return n % 2 === 1; * }; * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] */ var reject = function _reject(fn, list) { return filter(not(fn), list); }; R.reject = curry2(reject); /** * Like `reject`, but passes additional parameters to the predicate function. The predicate * function is passed three arguments: *(value, index, list)*. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @alias reject.idx * @example * * var lastTwo = function(val, idx, list) { * return list.length - idx <= 2; * }; * * R.reject.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] */ R.reject.idx = curry2(function _rejectIdx(fn, list) { return filterIdx(not(fn), list); }); /** * Returns a new list containing the first `n` elements of a given list, passing each value * to the supplied predicate function, and terminating when the predicate function returns * `false`. Excludes the element that caused the predicate function to fail. The predicate * function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} A new array. * @example * * var isNotFour = function(x) { * return !(x === 4); * }; * * R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] */ R.takeWhile = curry2(checkForMethod('takeWhile', function(fn, list) { var idx = -1, len = list.length; while (++idx < len && fn(list[idx])) {} return _slice(list, 0, idx); })); /** * Returns a new list containing the first `n` elements of the given list. If * `n > * list.length`, returns a list of `list.length` elements. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} n The number of elements to return. * @param {Array} list The array to query. * @return {Array} A new array containing the first elements of `list`. */ R.take = curry2(checkForMethod('take', function(n, list) { return _slice(list, 0, Math.min(n, list.length)); })); /** * Returns a new list containing the last `n` elements of a given list, passing each value * to the supplied predicate function, beginning when the predicate function returns * `true`. Excludes the element that caused the predicate function to fail. The predicate * function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} A new array. * @example * * var isTwo = function(x) { * return x === 2; * }; * * R.skipUntil(isTwo, [1, 2, 3, 4]); //=> [2, 3, 4] */ R.skipUntil = curry2(function _skipUntil(fn, list) { var idx = -1, len = list.length; while (++idx < len && !fn(list[idx])) {} return _slice(list, idx); }); /** * Returns a new list containing all but the first `n` elements of the given `list`. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} n The number of elements of `list` to skip. * @param {Array} list The array to consider. * @return {Array} The last `n` elements of `list`. * @example * * R.skip(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] */ R.skip = curry2(checkForMethod('skip', function _skip(n, list) { if (n < list.length) { return _slice(list, n); } else { return []; } })); /** * Returns the first element of the list which matches the predicate, or `undefined` if no * element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> a | undefined * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {Object} The element found, or `undefined`. * @example * * var xs = [{a: 1}, {a: 2}, {a: 3}]; * R.find(R.propEq('a', 2))(xs); //=> {a: 2} * R.find(R.propEq('a', 4))(xs); //=> undefined */ R.find = curry2(function find(fn, list) { var idx = -1; var len = list.length; while (++idx < len) { if (fn(list[idx])) { return list[idx]; } } }); /** * Returns the index of the first element of the list which matches the predicate, or `-1` * if no element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Number * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {number} The index of the element found, or `-1`. * @example * * var xs = [{a: 1}, {a: 2}, {a: 3}]; * R.findIndex(R.propEq('a', 2))(xs); //=> 1 * R.findIndex(R.propEq('a', 4))(xs); //=> -1 */ R.findIndex = curry2(function _findIndex(fn, list) { var idx = -1; var len = list.length; while (++idx < len) { if (fn(list[idx])) { return idx; } } return -1; }); /** * Returns the last element of the list which matches the predicate, or `undefined` if no * element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> a | undefined * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {Object} The element found, or `undefined`. * @example * * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} * R.findLast(R.propEq('a', 4))(xs); //=> undefined */ R.findLast = curry2(function _findLast(fn, list) { var idx = list.length; while (idx--) { if (fn(list[idx])) { return list[idx]; } } }); /** * Returns the index of the last element of the list which matches the predicate, or * `-1` if no element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Number * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {number} The index of the element found, or `-1`. * @example * * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 */ R.findLastIndex = curry2(function _findLastIndex(fn, list) { var idx = list.length; while (idx--) { if (fn(list[idx])) { return idx; } } return -1; }); /** * Returns `true` if all elements of the list match the predicate, `false` if there are any * that don't. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {boolean} `true` if the predicate is satisfied by every element, `false` * otherwise * @example * * var lessThan2 = R.flip(R.lt)(2); * var lessThan3 = R.flip(R.lt)(3); * var xs = R.range(1, 3); * xs; //=> [1, 2] * R.every(lessThan2)(xs); //=> false * R.every(lessThan3)(xs); //=> true */ function every(fn, list) { var idx = -1; while (++idx < list.length) { if (!fn(list[idx])) { return false; } } return true; } R.every = curry2(every); /** * Returns `true` if at least one of elements of the list match the predicate, `false` * otherwise. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {boolean} `true` if the predicate is satisfied by at least one element, `false` * otherwise * @example * * var lessThan0 = R.flip(R.lt)(0); * var lessThan2 = R.flip(R.lt)(2); * var xs = R.range(1, 3); * xs; //=> [1, 2] * R.some(lessThan0)(xs); //=> false * R.some(lessThan2)(xs); //=> true */ function some(fn, list) { var idx = -1; while (++idx < list.length) { if (fn(list[idx])) { return true; } } return false; } R.some = curry2(some); /** * Internal implementation of `indexOf`. * Returns the position of the first occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @private * @category Internal * @param {Array} The array to search * @param {*} item the item to find in the Array * @param {Number} from (optional) the index to start searching the Array * @return {Number} the index of the found item, or -1 * */ var indexOf = function _indexOf(list, item, from) { var idx = 0, length = list.length; if (typeof from == 'number') { idx = from < 0 ? Math.max(0, length + from) : from; } for (; idx < length; idx++) { if (list[idx] === item) { return idx; } } return -1; }; /** * Internal implementation of `lastIndexOf`. * Returns the position of the last occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @private * @category Internal * @param {Array} The array to search * @param {*} item the item to find in the Array * @param {Number} from (optional) the index to start searching the Array * @return {Number} the index of the found item, or -1 * */ var lastIndexOf = function _lastIndexOf(list, item, from) { var idx = list.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) { if (list[idx] === item) { return idx; } } return -1; }; /** * Returns the position of the first occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @func * @memberOf R * @category List * @sig a -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.indexOf(3, [1,2,3,4]); //=> 2 * R.indexOf(10, [1,2,3,4]); //=> -1 */ R.indexOf = curry2(function _indexOf(target, list) { return indexOf(list, target); }); /** * Returns the position of the first occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. However, * `indexOf.from` will only search the tail of the array, starting from the * `fromIdx` parameter. * * @func * @memberOf R * @category List * @sig a -> Number -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @param {Number} fromIdx the index to start searching from * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.indexOf.from(3, 2, [-1,0,1,2,3,4]); //=> 4 * R.indexOf.from(10, 2, [1,2,3,4]); //=> -1 */ R.indexOf.from = curry3(function indexOfFrom(target, fromIdx, list) { return indexOf(list, target, fromIdx); }); /** * Returns the position of the last occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. * * @func * @memberOf R * @category List * @sig a -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 * R.lastIndexOf(10, [1,2,3,4]); //=> -1 */ R.lastIndexOf = curry2(function _lastIndexOf(target, list) { return lastIndexOf(list, target); }); /** * Returns the position of the last occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. However, * `lastIndexOf.from` will only search the tail of the array, starting from the * `fromIdx` parameter. * * @func * @memberOf R * @category List * @sig a -> Number -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @param {Number} fromIdx the index to start searching from * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.lastIndexOf.from(3, 2, [-1,3,3,0,1,2,3,4]); //=> 2 * R.lastIndexOf.from(10, 2, [1,2,3,4]); //=> -1 */ R.lastIndexOf.from = curry3(function lastIndexOfFrom(target, fromIdx, list) { return lastIndexOf(list, target, fromIdx); }); /** * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. * * @func * @memberOf R * @category List * @sig a -> [a] -> Boolean * @param {Object} a The item to compare against. * @param {Array} list The array to consider. * @return {boolean} `true` if the item is in the list, `false` otherwise. * @example * * R.contains(3)([1, 2, 3]); //=> true * R.contains(4)([1, 2, 3]); //=> false * R.contains({})([{}, {}]); //=> false * var obj = {}; * R.contains(obj)([{}, obj, {}]); //=> true */ function contains(a, list) { return indexOf(list, a) > -1; } R.contains = curry2(contains); /** * Returns `true` if the `x` is found in the `list`, using `pred` as an * equality predicate for `x`. * * @func * @memberOf R * @category List * @sig (x, a -> Boolean) -> x -> [a] -> Boolean * @param {Function} pred :: x -> x -> Bool * @param {*} x the item to find * @param {Array} list the list to iterate over * @return {Boolean} `true` if `x` is in `list`, else `false` * @example * * var xs = [{x: 12}, {x: 11}, {x: 10}]; * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false */ function containsWith(pred, x, list) { var idx = -1, len = list.length; while (++idx < len) { if (pred(x, list[idx])) { return true; } } return false; } R.containsWith = curry3(containsWith); /** * Returns a new list containing only one copy of each element in the original list. * Equality is strict here, meaning reference equality for objects and non-coercing equality * for primitives. * * @func * @memberOf R * @category List * @sig [a] -> [a] * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * R.uniq([1, 1, 2, 1]); //=> [1, 2] * R.uniq([{}, {}]); //=> [{}, {}] * R.uniq([1, '1']); //=> [1, '1'] */ var uniq = R.uniq = function uniq(list) { var idx = -1, len = list.length; var result = [], item; while (++idx < len) { item = list[idx]; if (!contains(item, result)) { result.push(item); } } return result; }; /** * Returns `true` if all elements are unique, otherwise `false`. * Uniqueness is determined using strict equality (`===`). * * @func * @memberOf R * @category List * @sig [a] -> Boolean * @param {Array} list The array to consider. * @return {boolean} `true` if all elements are unique, else `false`. * @example * * R.isSet(['1', 1]); //=> true * R.isSet([1, 1]); //=> false * R.isSet([{}, {}]); //=> true */ R.isSet = function _isSet(list) { var len = list.length; var idx = -1; while (++idx < len) { if (indexOf(list, list[idx], idx + 1) >= 0) { return false; } } return true; }; /** * Returns a new list containing only one copy of each element in the original list, based * upon the value returned by applying the supplied predicate to two list elements. Prefers * the first item if two items compare equal based on the predicate. * * @func * @memberOf R * @category List * @sig (x, a -> Boolean) -> [a] -> [a] * @param {Function} pred :: x -> x -> Bool * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * var strEq = function(a, b) { return ('' + a) === ('' + b) }; * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] * R.uniqWith(strEq)([{}, {}]); //=> [{}] * R.uniqWith(strEq)([1, '1', 1]); //=> [1] * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] */ var uniqWith = R.uniqWith = curry2(function _uniqWith(pred, list) { var idx = -1, len = list.length; var result = [], item; while (++idx < len) { item = list[idx]; if (!containsWith(pred, item, result)) { result.push(item); } } return result; }); /** * Returns a new list by plucking the same named property off all objects in the list supplied. * * @func * @memberOf R * @category List * @sig String -> {*} -> [*] * @param {string|number} key The key name to pluck off of each object. * @param {Array} list The array to consider. * @return {Array} The list of values for the given key. * @example * * R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] * R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] */ var pluck = R.pluck = curry2(function _pluck(p, list) { return map(prop(p), list); }); /** * `makeFlat` is a helper function that returns a one-level or fully recursive function * based on the flag passed in. * * @private */ // TODO: document, even for internals... var makeFlat = function _makeFlat(recursive) { return function __flatt(list) { var value, result = [], idx = -1, j, ilen = list.length, jlen; while (++idx < ilen) { if (R.isArrayLike(list[idx])) { value = (recursive) ? __flatt(list[idx]) : list[idx]; j = -1; jlen = value.length; while (++j < jlen) { result.push(value[j]); } } else { result.push(list[idx]); } } return result; }; }; /** * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting * them in a new array, depth-first. * * @func * @memberOf R * @category List * @sig [a] -> [b] * @param {Array} list The array to consider. * @return {Array} The flattened list. * @example * * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */ R.flatten = makeFlat(true); /** * Returns a new list by pulling every item at the first level of nesting out, and putting * them in a new array. * * @func * @memberOf R * @category List * @sig [a] -> [b] * @param {Array} list The array to consider. * @return {Array} The flattened list. * @example * * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] */ var unnest = R.unnest = makeFlat(false); /** * Creates a new list out of the two supplied by applying the function to * each equally-positioned pair in the lists. The returned list is * truncated to the length of the shorter of the two input lists. * * @function * @memberOf R * @category List * @sig (a,b -> c) -> a -> b -> [c] * @param {Function} fn The function used to combine the two elements into one value. * @param {Array} list1 The first array to consider. * @param {Array} list2 The second array to consider. * @return {Array} The list made by combining same-indexed elements of `list1` and `list2` * using `fn`. * @example * * var f = function(x, y) { * // ... * }; * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] */ R.zipWith = curry3(function _zipWith(fn, a, b) { var rv = [], idx = -1, len = Math.min(a.length, b.length); while (++idx < len) { rv[idx] = fn(a[idx], b[idx]); } return rv; }); /** * Creates a new list out of the two supplied by pairing up * equally-positioned items from both lists. The returned list is * truncated to the length of the shorter of the two input lists. * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. * * @func * @memberOf R * @category List * @sig a -> b -> [[a,b]] * @param {Array} list1 The first array to consider. * @param {Array} list2 The second array to consider. * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`. * @example * * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] */ R.zip = curry2(function _zip(a, b) { var rv = []; var idx = -1; var len = Math.min(a.length, b.length); while (++idx < len) { rv[idx] = [a[idx], b[idx]]; } return rv; }); /** * Creates a new object out of a list of keys and a list of values. * * @func * @memberOf R * @category List * @sig k -> v -> {k: v} * @param {Array} keys The array that will be properties on the output object. * @param {Array} values The list of values on the output object. * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`. * @example * * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} */ R.zipObj = curry2(function _zipObj(keys, values) { var idx = -1, len = keys.length, out = {}; while (++idx < len) { out[keys[idx]] = values[idx]; } return out; }); /** * Creates a new object out of a list key-value pairs. * * @func * @memberOf R * @category List * @sig [[k,v]] -> {k: v} * @param {Array} An array of two-element arrays that will be the keys and values of the ouput object. * @return {Object} The object made by pairing up `keys` and `values`. * @example * * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} */ R.fromPairs = function _fromPairs(pairs) { var idx = -1, len = pairs.length, out = {}; while (++idx < len) { if (isArray(pairs[idx]) && pairs[idx].length) { out[pairs[idx][0]] = pairs[idx][1]; } } return out; }; /** * Creates a new list out of the two supplied by applying the function * to each possible pair in the lists. * * @see R.xprod * @func * @memberOf R * @category List * @sig (a,b -> c) -> a -> b -> [c] * @param {Function} fn The function to join pairs with. * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The list made by combining each possible pair from * `as` and `bs` using `fn`. * @example * * var f = function(x, y) { * // ... * }; * R.xprodWith(f, [1, 2], ['a', 'b']); * // [f(1, 'a'), f(1, 'b'), f(2, 'a'), f(2, 'b')]; */ R.xprodWith = curry3(function _xprodWith(fn, a, b) { if (isEmpty(a) || isEmpty(b)) { return []; } // Better to push them all or to do `new Array(ilen * jlen)` and // calculate indices? var idx = -1, ilen = a.length, j, jlen = b.length, result = []; while (++idx < ilen) { j = -1; while (++j < jlen) { result.push(fn(a[idx], b[j])); } } return result; }); /** * Creates a new list out of the two supplied by creating each possible * pair from the lists. * * @func * @memberOf R * @category List * @sig a -> b -> [[a,b]] * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The list made by combining each possible pair from * `as` and `bs` into pairs (`[a, b]`). * @example * * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] */ R.xprod = curry2(function _xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...) if (isEmpty(a) || isEmpty(b)) { return []; } var idx = -1; var ilen = a.length; var j; var jlen = b.length; // Better to push them all or to do `new Array(ilen * jlen)` and calculate indices? var result = []; while (++idx < ilen) { j = -1; while (++j < jlen) { result.push([a[idx], b[j]]); } } return result; }); /** * Returns a new list with the same elements as the original list, just * in the reverse order. * * @func * @memberOf R * @category List * @sig [a] -> [a] * @param {Array} list The list to reverse. * @return {Array} A copy of the list in reverse order. * @example * * R.reverse([1, 2, 3]); //=> [3, 2, 1] * R.reverse([1, 2]); //=> [2, 1] * R.reverse([1]); //=> [1] * R.reverse([]); //=> [] */ R.reverse = function _reverse(list) { return clone(list || []).reverse(); }; /** * Returns a list of numbers from `from` (inclusive) to `to` * (exclusive). * * @func * @memberOf R * @category List * @sig Number -> Number -> [Number] * @param {number} from The first number in the list. * @param {number} to One more than the last number in the list. * @return {Array} The list of numbers in tthe set `[a, b)`. * @example * * R.range(1, 5); //=> [1, 2, 3, 4] * R.range(50, 53); //=> [50, 51, 52] */ R.range = curry2(function _range(from, to) { if (from >= to) { return []; } var idx = 0, result = new Array(Math.floor(to) - Math.ceil(from)); for (; from < to; idx++, from++) { result[idx] = from; } return result; }); /** * Returns a string made by inserting the `separator` between each * element and concatenating all the elements into a single string. * * @func * @memberOf R * @category List * @sig String -> [a] -> String * @param {string|number} separator The string used to separate the elements. * @param {Array} xs The elements to join into a string. * @return {string} The string made by concatenating `xs` with `separator`. * @example * * var spacer = R.join(' '); * spacer(['a', 2, 3.4]); //=> 'a 2 3.4' * R.join('|', [1, 2, 3]); //=> '1|2|3' */ R.join = invoker('join', Array.prototype); /** * Returns the elements from `xs` starting at `a` and ending at `b - 1`. * * @func * @memberOf R * @category List * @sig Number -> Number -> [a] -> [a] * @param {number} a The starting index. * @param {number} b One more than the ending index. * @param {Array} xs The list to take elements from. * @return {Array} The items from `a` to `b - 1` from `xs`. * @example * * var xs = R.range(0, 10); * R.slice(2, 5)(xs); //=> [2, 3, 4] */ R.slice = invoker('slice', Array.prototype); /** * Returns the elements from `xs` starting at `a` going to the end of `xs`. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} a The starting index. * @param {Array} xs The list to take elements from. * @return {Array} The items from `a` to the end of `xs`. * @example * * var xs = R.range(0, 10); * R.slice.from(2)(xs); //=> [2, 3, 4, 5, 6, 7, 8, 9] * * var ys = R.range(4, 8); * var tail = R.slice.from(1); * tail(ys); //=> [5, 6, 7] */ R.slice.from = curry2(function(a, xs) { return xs.slice(a, xs.length); }); /** * Removes the sub-list of `list` starting at index `start` and containing * `count` elements. _Note that this is not destructive_: it returns a * copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> Number -> [a] -> [a] * @param {Number} start The position to start removing elements * @param {Number} count The number of elements to remove * @param {Array} list The list to remove from * @return {Array} a new Array with `count` elements from `start` removed * @example * * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] */ R.remove = curry3(function _remove(start, count, list) { return concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count))); }); /** * Inserts the supplied element into the list, at index `index`. _Note * that this is not destructive_: it returns a copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> a -> [a] -> [a] * @param {Number} index The position to insert the element * @param {*} elt The element to insert into the Array * @param {Array} list The list to insert into * @return {Array} a new Array with `elt` inserted at `index` * @example * * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] */ R.insert = curry3(function _insert(idx, elt, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; return concat(append(elt, _slice(list, 0, idx)), _slice(list, idx)); }); /** * Inserts the sub-list into the list, at index `index`. _Note that this * is not destructive_: it returns a copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] -> [a] * @param {Number} index The position to insert the sublist * @param {Array} elts The sub-list to insert into the Array * @param {Array} list The list to insert the sub-list into * @return {Array} a new Array with `elts` inserted starting at `index` * @example * * R.insert.all(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] */ R.insert.all = curry3(function _insertAll(idx, elts, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; return concat(concat(_slice(list, 0, idx), elts), _slice(list, idx)); }); /** * Makes a comparator function out of a function that reports whether the first element is less than the second. * * @func * @memberOf R * @category Function * @sig (a, b -> Boolean) -> (a, b -> Number) * @param {Function} pred A predicate function of arity two. * @return {Function} a Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0` * @example * * var cmp = R.comparator(function(a, b) { * return a.age < b.age; * }); * var people = [ * // ... * ]; * R.sort(cmp, people); */ var comparator = R.comparator = function _comparator(pred) { return function(a, b) { return pred(a, b) ? -1 : pred(b, a) ? 1 : 0; }; }; /** * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero * if they are equal. Please note that this is a **copy** of the list. It does not modify the original. * * @func * @memberOf R * @category List * @sig (a,a -> Number) -> [a] -> [a] * @param {Function} comparator A sorting function :: a -> b -> Int * @param {Array} list The list to sort * @return {Array} a new array with its elements sorted by the comparator function. * @example * * var diff = function(a, b) { return a - b; }; * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] */ R.sort = curry2(function sort(comparator, list) { return clone(list).sort(comparator); }); /** * Splits a list into sublists stored in an object, based on the result of calling a String-returning function * on each element, and grouping the results according to values returned. * * @func * @memberOf R * @category List * @sig (a -> s) -> [a] -> {s: a} * @param {Function} fn Function :: a -> String * @param {Array} list The array to group * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements * that produced that key when passed to `fn`. * @example * * var byGrade = R.groupBy(function(student) { * var score = student.score; * return (score < 65) ? 'F' : (score < 70) ? 'D' : * (score < 80) ? 'C' : (score < 90) ? 'B' : 'A'; * }); * var students = [{name: 'Abby', score: 84}, * {name: 'Eddy', score: 58}, * // ... * {name: 'Jack', score: 69}]; * byGrade(students); * // { * // 'A': [{name: 'Dianne', score: 99}], * // 'B': [{name: 'Abby', score: 84}] * // // ..., * // 'F': [{name: 'Eddy', score: 58}] * // } */ R.groupBy = curry2(function _groupBy(fn, list) { return foldl(function(acc, elt) { var key = fn(elt); acc[key] = append(elt, acc[key] || (acc[key] = [])); return acc; }, {}, list); }); /** * Takes a predicate and a list and returns the pair of lists of * elements which do and do not satisfy the predicate, respectively. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [[a],[a]] * @param {Function} pred Function :: a -> Boolean * @param {Array} list The array to partition * @return {Array} A nested array, containing first an array of elements that satisfied the predicate, * and second an array of elements that did not satisfy. * @example * * R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); * //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] */ R.partition = curry2(function _partition(pred, list) { return foldl(function(acc, elt) { acc[pred(elt) ? 0 : 1].push(elt); return acc; }, [[], []], list); }); // Object Functions // ---------------- // // These functions operate on plain Javascript object, adding simple functions to test properties on these // objects. Many of these are of most use in conjunction with the list functions, operating on lists of // objects. // -------- /** * Runs the given function with the supplied object, then returns the object. * * @func * @memberOf R * @category Function * @sig a -> (a -> *) -> a * @param {*} x * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away. * @return {*} x * @example * * var sayX = function(x) { console.log('x is ' + x); }; * R.tap(100, sayX); //=> 100 * //-> 'x is 100') */ R.tap = curry2(function _tap(x, fn) { if (typeof fn === 'function') { fn(x); } return x; }); /** * Tests if two items are equal. Equality is strict here, meaning reference equality for objects and * non-coercing equality for primitives. * * @func * @memberOf R * @category Relation * @sig a -> b -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * var o = {}; * R.eq(o, o); //=> true * R.eq(o, {}); //=> false * R.eq(1, 1); //=> true * R.eq(1, '1'); //=> false */ R.eq = curry2(function _eq(a, b) { return a === b; }); /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. * * @func * @memberOf R * @category Object * @sig s -> {s: a} -> a * @param {String} p The property name * @param {Object} obj The object to query * @return {*} The value at obj.p * @example * * R.prop('x', {x: 100}); //=> 100 * R.prop('x', {}); //=> undefined * * var fifth = R.prop(4); // indexed from 0, remember * fifth(['Bashful', 'Doc', 'Dopey', 'Grumpy', 'Happy', 'Sleepy', 'Sneezy']); * //=> 'Happy' */ var prop = R.prop = function prop(p, obj) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function _prop(obj) { return obj[p]; }; } return obj[p]; }; /** * @func * @memberOf R * @category Object * @see R.prop */ R.get = R.prop; /** * Returns the value at the specified property. * The only difference from `prop` is the parameter order. * * @func * @memberOf R * @see R.prop * @category Object * @sig {s: a} -> s -> a * @param {Object} obj The object to query * @param {String} prop The property name * @return {*} The value at obj.p * @example * * R.props({x: 100}, 'x'); //=> 100 */ R.props = flip(R.prop); /** * An internal reference to `Object.prototype.hasOwnProperty` * @private */ var hasOwnProperty = Object.prototype.hasOwnProperty; /** * If the given object has an own property with the specified name, * returns the value of that property. * Otherwise returns the provided default value. * * @func * @memberOf R * @category Object * @sig s -> v -> {s: x} -> x | v * @param {String} p The name of the property to return. * @param {*} val The default value. * @returns {*} The value of given property or default value. * @example * * var alice = { * name: 'ALICE', * age: 101 * }; * var favorite = R.prop('favoriteLibrary'); * var favoriteWithDefault = R.propOrDefault('favoriteLibrary', 'Ramda'); * * favorite(alice); //=> undefined * favoriteWithDefault(alice); //=> 'Ramda' */ R.propOrDefault = curry3(function _propOrDefault(p, val, obj) { return hasOwnProperty.call(obj, p) ? obj[p] : val; }); /** * Calls the specified function on the supplied object. Any additional arguments * after `fn` and `obj` are passed in to `fn`. If no additional arguments are passed to `func`, * `fn` is invoked with no arguments. * * @func * @memberOf R * @category Object * @sig k -> {k : v} -> v(*) * @param {String} fn The name of the property mapped to the function to invoke * @param {Object} obj The object * @return {*} The value of invoking `obj.fn` * @example * * R.func('add', R, 1, 2); //=> 3 * * var obj = { f: function() { return 'f called'; } }; * R.func('f', obj); //=> 'f called' */ R.func = function _func(funcName, obj) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(obj) { return obj[funcName].apply(obj, _slice(arguments, 1)); }; default: return obj[funcName].apply(obj, _slice(arguments, 2)); } }; /** * Returns a function that always returns the given value. * * @func * @memberOf R * @category Function * @sig a -> (* -> a) * @param {*} val The value to wrap in a function * @return {Function} A Function :: * -> val * @example * * var t = R.always('Tee'); * t(); //=> 'Tee' */ var always = R.always = function _always(val) { return function() { return val; }; }; /** * Internal reference to Object.keys * * @private * @param {Object} * @return {Array} */ var nativeKeys = Object.keys; /** * Returns a list containing the names of all the enumerable own * properties of the supplied object. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ var keys = R.keys = (function() { // cover IE < 9 keys issues var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString'); var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; return function _keys(obj) { if (!R.is(Object, obj)) { return []; } if (nativeKeys) { return nativeKeys(Object(obj)); } var prop, ks = [], nIdx; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { ks.push(prop); } } if (hasEnumBug) { nIdx = nonEnumerableProps.length; while (nIdx--) { prop = nonEnumerableProps[nIdx]; if (hasOwnProperty.call(obj, prop) && !R.contains(prop, ks)) { ks.push(prop); } } } return ks; }; }()); /** * Returns a list containing the names of all the * properties of the supplied object, including prototype properties. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.keysIn(f); //=> ['x', 'y'] */ R.keysIn = function _keysIn(obj) { var prop, ks = []; for (prop in obj) { ks.push(prop); } return ks; }; /** * @private * @param {Function} fn The strategy for extracting keys from an object * @return {Function} A function that takes an object and returns an array of * key-value arrays. */ var pairWith = function(fn) { return function(obj) { return R.map(function(key) { return [key, obj[key]]; }, fn(obj)); }; }; /** * Converts an object into an array of key, value arrays. * Only the object's own properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [[k,v]] * @param {Object} obj The object to extract from * @return {Array} An array of key, value arrays from the object's own properties * @example * * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] */ R.toPairs = pairWith(R.keys); /** * Converts an object into an array of key, value arrays. * The object's own properties and prototype properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [[k,v]] * @param {Object} obj The object to extract from * @return {Array} An array of key, value arrays from the object's own * and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.toPairsIn(f); //=> [['x','X'], ['y','Y']] */ R.toPairsIn = pairWith(R.keysIn); /** * Returns a list of all the enumerable own properties of the supplied object. * Note that the order of the output array is not guaranteed across * different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [v] * @param {Object} obj The object to extract values from * @return {Array} An array of the values of the object's own properties * @example * * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] */ R.values = function _values(obj) { var props = keys(obj), length = props.length, vals = new Array(length); for (var idx = 0; idx < length; idx++) { vals[idx] = obj[props[idx]]; } return vals; }; /** * Returns a list of all the properties, including prototype properties, * of the supplied object. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [v] * @param {Object} obj The object to extract values from * @return {Array} An array of the values of the object's own and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.valuesIn(f); //=> ['X', 'Y'] */ R.valuesIn = function _valuesIn(obj) { var prop, vs = []; for (prop in obj) { vs.push(obj[prop]); } return vs; }; /** * Internal helper function for making a partial copy of an object * * @private * */ // TODO: document, even for internals... function pickWith(test, obj) { var copy = {}, props = keys(obj), prop, val; for (var idx = 0, len = props.length; idx < len; idx++) { prop = props[idx]; val = obj[prop]; if (test(val, prop, obj)) { copy[prop] = val; } } return copy; } /** * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the * property is ignored. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to copy onto a new object * @param {Object} obj The object to copy from * @return {Object} A new object with only properties from `names` on it. * @example * * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} */ R.pick = curry2(function pick(names, obj) { return pickWith(function(val, key) { return contains(key, names); }, obj); }); /** * Returns a partial copy of an object omitting the keys specified. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to omit from the new object * @param {Object} obj The object to copy from * @return {Object} A new object with properties from `names` not on it. * @example * * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} */ R.omit = curry2(function omit(names, obj) { return pickWith(function(val, key) { return !contains(key, names); }, obj); }); /** * Returns a partial copy of an object containing only the keys that * satisfy the supplied predicate. * * @func * @memberOf R * @category Object * @sig (v, k -> Boolean) -> {k: v} -> {k: v} * @param {Function} pred A predicate to determine whether or not a key * should be included on the output object. * @param {Object} obj The object to copy from * @return {Object} A new object with only properties that satisfy `pred` * on it. * @see R.pick * @example * * var isUpperCase = function(val, key) { return key.toUpperCase() === key; } * R.pickWith(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} */ R.pickWith = curry2(pickWith); /** * Internal implementation of `pickAll` * * @private * @see R.pickAll */ // TODO: document, even for internals... var pickAll = function _pickAll(names, obj) { var copy = {}; forEach(function(name) { copy[name] = obj[name]; }, names); return copy; }; /** * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to copy onto a new object * @param {Object} obj The object to copy from * @return {Object} A new object with only properties from `names` on it. * @see R.pick * @example * * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} */ R.pickAll = curry2(pickAll); /** * Assigns own enumerable properties of the other object to the destination * object prefering items in other. * * @private * @memberOf R * @category Object * @param {Object} object The destination object. * @param {Object} other The other object to merge with destination. * @returns {Object} Returns the destination object. * @example * * extend({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); * //=> { 'name': 'fred', 'age': 40 } */ function extend(destination, other) { var props = keys(other), idx = -1, length = props.length; while (++idx < length) { destination[props[idx]] = other[props[idx]]; } return destination; } /** * Create a new object with the own properties of a * merged with the own properties of object b. * This function will *not* mutate passed-in objects. * * @func * @memberOf R * @category Object * @sig {k: v} -> {k: v} -> {k: v} * @param {Object} a source object * @param {Object} b object with higher precendence in output * @returns {Object} Returns the destination object. * @example * * R.mixin({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); * //=> { 'name': 'fred', 'age': 40 } */ R.mixin = curry2(function _mixin(a, b) { return extend(extend({}, a), b); }); /** * Creates a shallow copy of an object's own properties. * * @func * @memberOf R * @category Object * @sig {*} -> {*} * @param {Object} obj The object to clone * @returns {Object} A new object * @example * * R.cloneObj({a: 1, b: 2, c: [1, 2, 3]}); // {a: 1, b: 2, c: [1, 2, 3]} */ R.cloneObj = function(obj) { return extend({}, obj); }; /** * Reports whether two functions have the same value for the specified property. Useful as a curried predicate. * * @func * @memberOf R * @category Object * @sig k -> {k: v} -> {k: v} -> Boolean * @param {String} prop The name of the property to compare * @param {Object} obj1 * @param {Object} obj2 * @return {Boolean} * * @example * * var o1 = { a: 1, b: 2, c: 3, d: 4 }; * var o2 = { a: 10, b: 20, c: 3, d: 40 }; * R.eqProps('a', o1, o2); //=> false * R.eqProps('c', o1, o2); //=> true */ R.eqProps = curry3(function eqProps(prop, obj1, obj2) { return obj1[prop] === obj2[prop]; }); /** * internal helper for `where` * * @private * @see R.where */ function satisfiesSpec(spec, parsedSpec, testObj) { if (spec === testObj) { return true; } if (testObj == null) { return false; } parsedSpec.fn = parsedSpec.fn || []; parsedSpec.obj = parsedSpec.obj || []; var key, val, idx = -1, fnLen = parsedSpec.fn.length, j = -1, objLen = parsedSpec.obj.length; while (++idx < fnLen) { key = parsedSpec.fn[idx]; val = spec[key]; // if (!hasOwnProperty.call(testObj, key)) { // return false; // } if (!(key in testObj)) { return false; } if (!val(testObj[key], testObj)) { return false; } } while (++j < objLen) { key = parsedSpec.obj[j]; if (spec[key] !== testObj[key]) { return false; } } return true; } /** * Takes a spec object and a test object and returns true if the test satisfies the spec. * Any property on the spec that is not a function is interpreted as an equality * relation. * * If the spec has a property mapped to a function, then `where` evaluates the function, passing in * the test object's value for the property in question, as well as the whole test object. * * `where` is well suited to declarativley expressing constraints for other functions, e.g., * `filter`, `find`, `pickWith`, etc. * * @func * @memberOf R * @category Object * @sig {k: v} -> {k: v} -> Boolean * @param {Object} spec * @param {Object} testObj * @return {Boolean} * @example * * var spec = {x: 2}; * R.where(spec, {w: 10, x: 2, y: 300}); //=> true * R.where(spec, {x: 1, y: 'moo', z: true}); //=> false * * var spec2 = {x: function(val, obj) { return val + obj.y > 10; }}; * R.where(spec2, {x: 2, y: 7}); //=> false * R.where(spec2, {x: 3, y: 8}); //=> true * * var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; * R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] */ R.where = function where(spec, testObj) { var parsedSpec = R.groupBy(function(key) { return typeof spec[key] === 'function' ? 'fn' : 'obj'; }, keys(spec)); switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(testObj) { return satisfiesSpec(spec, parsedSpec, testObj); }; } return satisfiesSpec(spec, parsedSpec, testObj); }; // Miscellaneous Functions // ----------------------- // // A few functions in need of a good home. // -------- /** * Expose the functions from ramda as properties of another object. * If the provided object is the global object then the ramda * functions become global functions. * Warning: This function *will* mutate the object provided. * * @func * @memberOf R * @category Object * @sig -> {*} -> {*} * @param {Object} obj The object to attach ramda functions * @return {Object} a reference to the mutated object * @example * * var x = {} * R.installTo(x); // x now contains ramda functions * R.installTo(this); // add ramda functions to `this` object */ R.installTo = function(obj) { return extend(obj, R); }; /** * See if an object (`val`) is an instance of the supplied constructor. * This function will check up the inheritance chain, if any. * * @func * @memberOf R * @category type * @sig (* -> {*}) -> a -> Boolean * @param {Object} ctor A constructor * @param {*} val The value to test * @return {Boolean} * @example * * R.is(Object, {}); //=> true * R.is(Number, 1); //=> true * R.is(Object, 1); //=> false * R.is(String, 's'); //=> true * R.is(String, new String('')); //=> true * R.is(Object, new String('')); //=> true * R.is(Object, 's'); //=> false * R.is(Number, {}); //=> false */ R.is = curry2(function is(ctor, val) { return val != null && val.constructor === ctor || val instanceof ctor; }); /** * A function that always returns `0`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> 0 * @see R.always * @return {Number} 0. Always zero. * @example * * R.alwaysZero(); //=> 0 */ R.alwaysZero = always(0); /** * A function that always returns `false`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> false * @see R.always * @return {Boolean} false * @example * * R.alwaysFalse(); //=> false */ R.alwaysFalse = always(false); /** * A function that always returns `true`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> true * @see R.always * @return {Boolean} true * @example * * R.alwaysTrue(); //=> true */ R.alwaysTrue = always(true); // Logic Functions // --------------- // // These functions are very simple wrappers around the built-in logical operators, useful in building up // more complex functional forms. // -------- /** * * A function wrapping calls to the two functions in an `&&` operation, returning `true` or `false`. Note that * this is short-circuited, meaning that the second function will not be invoked if the first returns a false-y * value. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and ANDs their outputs together. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0 }; * var f = R.and(gt10, even); * f(100); //=> true * f(101); //=> false */ R.and = curry2(function and(f, g) { return function _and() { return !!(f.apply(this, arguments) && g.apply(this, arguments)); }; }); /** * A function wrapping calls to the two functions in an `||` operation, returning `true` or `false`. Note that * this is short-circuited, meaning that the second function will not be invoked if the first returns a truth-y * value. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and ORs their outputs together. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0 }; * var f = R.or(gt10, even); * f(101); //=> true * f(8); //=> true */ R.or = curry2(function or(f, g) { return function _or() { return !!(f.apply(this, arguments) || g.apply(this, arguments)); }; }); /** * A function wrapping a call to the given function in a `!` operation. It will return `true` when the * underlying function would return a false-y value, and `false` when it would return a truth-y one. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @return {Function} a function that applies its arguments to `f` and logically inverts its output. * @example * * var gt10 = function(x) { return x > 10; }; * var f = R.not(gt10); * f(11); //=> false * f(9); //=> true */ var not = R.not = function _not(f) { return function() {return !f.apply(this, arguments);}; }; /** * Create a predicate wrapper which will call a pick function (all/any) for each predicate * * @private * @see R.every * @see R.some */ // TODO: document, even for internals... var predicateWrap = function _predicateWrap(predPicker) { return function(preds /* , args */) { var predIterator = function() { var args = arguments; return predPicker(function(predicate) { return predicate.apply(null, args); }, preds); }; return arguments.length > 1 ? // Call function imediately if given arguments predIterator.apply(null, _slice(arguments, 1)) : // Return a function which will call the predicates with the provided arguments arity(max(pluck('length', preds)), predIterator); }; }; /** * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. * * @func * @memberOf R * @category logic * @sig [(*... -> Boolean)] -> (*... -> Boolean) * @param {Array} list An array of predicate functions * @param {*} optional Any arguments to pass into the predicates * @return {Function} a function that applies its arguments to each of * the predicates, returning `true` if all are satisfied. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0}; * var f = R.allPredicates([gt10, even]); * f(11); //=> false * f(12); //=> true */ R.allPredicates = predicateWrap(every); /** * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. * * @func * @memberOf R * @category logic * @sig [(*... -> Boolean)] -> (*... -> Boolean) * @param {Array} list An array of predicate functions * @param {*} optional Any arguments to pass into the predicates * @return {Function} a function that applies its arguments to each of the predicates, returning * `true` if all are satisfied.. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0}; * var f = R.anyPredicates([gt10, even]); * f(11); //=> true * f(8); //=> true * f(9); //=> false */ R.anyPredicates = predicateWrap(some); // Arithmetic Functions // -------------------- // // These functions wrap up the certain core arithmetic operators // -------- /** * Adds two numbers (or strings). Equivalent to `a + b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @sig String -> String -> String * @param {number|string} a The first value. * @param {number|string} b The second value. * @return {number|string} The result of `a + b`. * @example * * var increment = R.add(1); * increment(10); //=> 11 * R.add(2, 3); //=> 5 * R.add(7)(10); //=> 17 */ var add = R.add = curry2(function _add(a, b) { return a + b; }); /** * Multiplies two numbers. Equivalent to `a * b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a * b`. * @example * * var double = R.multiply(2); * var triple = R.multiply(3); * double(3); //=> 6 * triple(4); //=> 12 * R.multiply(2, 5); //=> 10 */ var multiply = R.multiply = curry2(function _multiply(a, b) { return a * b; }); /** * Subtracts two numbers. Equivalent to `a - b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a - b`. * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.subtract(10, 8); //=> 2 * * var minus5 = R.subtract(5); * minus5(17); //=> 12 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var complementaryAngle = R.subtract(90, _); * complementaryAngle(30); //=> 60 * complementaryAngle(72); //=> 18 */ R.subtract = op(function _subtract(a, b) { return a - b; }); /** * Divides two numbers. Equivalent to `a / b`. * While at times the curried version of `divide` might be useful, * probably the curried version of `divideBy` will be more useful. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a / b`. * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.divide(71, 100); //=> 0.71 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var half = R.divide(2); * half(42); //=> 21 * * var reciprocal = R.divide(1, _); * reciprocal(4); //=> 0.25 */ R.divide = op(function _divide(a, b) { return a / b; }); /** * Divides the second parameter by the first and returns the remainder. * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The value to the divide. * @param {number} b The pseudo-modulus * @return {number} The result of `b % a`. * @note Operator: this is right-curried by default, but can be called via sections * @see R.mathMod * @example * * R.modulo(17, 3); //=> 2 * // JS behavior: * R.modulo(-17, 3); //=> -2 * R.modulo(17, -3); //=> 2 * * var isOdd = R.modulo(2); * isOdd(42); //=> 0 * isOdd(21); //=> 1 */ R.modulo = op(function _modulo(a, b) { return a % b; }); /** * Determine if the passed argument is an integer. * * @private * @param {*} n * @category type * @return {Boolean} */ // TODO: document, even for internals... var isInteger = Number.isInteger || function isInteger(n) { return (n << 0) === n; }; /** * mathMod behaves like the modulo operator should mathematically, unlike the `%` * operator (and by extension, R.modulo). So while "-17 % 5" is -2, * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} m The dividend. * @param {number} p the modulus. * @return {number} The result of `b mod a`. * @see R.moduloBy * @example * * R.mathMod(-17, 5); //=> 3 * R.mathMod(17, 5); //=> 2 * R.mathMod(17, -5); //=> NaN * R.mathMod(17, 0); //=> NaN * R.mathMod(17.2, 5); //=> NaN * R.mathMod(17, 5.3); //=> NaN * * var clock = R.mathMod(12); * clock(15); //=> 3 * clock(24); //=> 0 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var seventeenMod = R.mathMod(17, _); * seventeenMod(3); //=> 2 * seventeenMod(4); //=> 1 * seventeenMod(10); //=> 7 */ R.mathMod = op(function _mathMod(m, p) { if (!isInteger(m)) { return NaN; } if (!isInteger(p) || p < 1) { return NaN; } return ((m % p) + p) % p; }); /** * Adds together all the elements of a list. * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list An array of numbers * @return {number} The sum of all the numbers in the list. * @see reduce * @example * * R.sum([2,4,6,8,100,1]); //=> 121 */ R.sum = foldl(add, 0); /** * Multiplies together all the elements of a list. * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list An array of numbers * @return {number} The product of all the numbers in the list. * @see reduce * @example * * R.product([2,4,6,8,100,1]); //=> 38400 */ R.product = foldl(multiply, 1); /** * Returns true if the first parameter is less than the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a < b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.lt(2, 6); //=> true * R.lt(2, 0); //=> false * R.lt(2, 2); //=> false * R.lt(5)(10); //=> false // default currying is right-sectioned * R.lt(5, _)(10); //=> true // left-sectioned currying */ R.lt = op(function _lt(a, b) { return a < b; }); /** * Returns true if the first parameter is less than or equal to the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a <= b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.lte(2, 6); //=> true * R.lte(2, 0); //=> false * R.lte(2, 2); //=> true */ R.lte = op(function _lte(a, b) { return a <= b; }); /** * Returns true if the first parameter is greater than the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a > b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.gt(2, 6); //=> false * R.gt(2, 0); //=> true * R.gt(2, 2); //=> false */ R.gt = op(function _gt(a, b) { return a > b; }); /** * Returns true if the first parameter is greater than or equal to the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a >= b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.gte(2, 6); //=> false * R.gte(2, 0); //=> true * R.gte(2, 2); //=> true */ R.gte = op(function _gte(a, b) { return a >= b; }); /** * Determines the largest of a list of numbers (or elements that can be cast to numbers) * * @func * @memberOf R * @category math * @sig [Number] -> Number * @see R.maxWith * @param {Array} list A list of numbers * @return {Number} The greatest number in the list * @example * * R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9 */ var max = R.max = function _max(list) { return foldl(binary(Math.max), -Infinity, list); }; /** * Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator * * @func * @memberOf R * @category math * @sig (a -> Number) -> [a] -> a * @param {Function} keyFn A comparator function for elements in the list * @param {Array} list A list of comparable elements * @return {*} The greatest element in the list. `undefined` if the list is empty. * @see R.max * @example * * function cmp(obj) { return obj.x; } * var a = {x: 1}, b = {x: 2}, c = {x: 3}; * R.maxWith(cmp, [a, b, c]); //=> {x: 3} */ R.maxWith = curry2(function _maxWith(keyFn, list) { if (!(list && list.length > 0)) { return; } var idx = 0, winner = list[idx], max = keyFn(winner), testKey; while (++idx < list.length) { testKey = keyFn(list[idx]); if (testKey > max) { max = testKey; winner = list[idx]; } } return winner; }); /** * Determines the smallest of a list of numbers (or elements that can be cast to numbers) * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list A list of numbers * @return {Number} The greatest number in the list * @see R.minWith * @example * * R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2 */ R.min = function _min(list) { return foldl(binary(Math.min), Infinity, list); }; /** * Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator * * @func * @memberOf R * @category math * @sig (a -> Number) -> [a] -> a * @param {Function} keyFn A comparator function for elements in the list * @param {Array} list A list of comparable elements * @see R.min * @return {*} The greatest element in the list. `undefined` if the list is empty. * @example * * function cmp(obj) { return obj.x; } * var a = {x: 1}, b = {x: 2}, c = {x: 3}; * R.minWith(cmp, [a, b, c]); //=> {x: 1} */ // TODO: combine this with maxWith? R.minWith = curry2(function _minWith(keyFn, list) { if (!(list && list.length > 0)) { return; } var idx = 0, winner = list[idx], min = keyFn(list[idx]), testKey; while (++idx < list.length) { testKey = keyFn(list[idx]); if (testKey < min) { min = testKey; winner = list[idx]; } } return winner; }); // String Functions // ---------------- // // Much of the String.prototype API exposed as simple functions. // -------- /** * returns a subset of a string between one index and another. * * @func * @memberOf R * @category string * @sig Number -> Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {Number} indexB An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substring(2, 5, 'abcdefghijklm'); //=> 'cde' */ var substring = R.substring = invoker('substring', String.prototype); /** * The trailing substring of a String starting with the nth character: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substringFrom(8, 'abcdefghijklm'); //=> 'ijklm' */ R.substringFrom = flip(substring)(void 0); /** * The leading substring of a String ending before the nth character: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substringTo(8, 'abcdefghijklm'); //=> 'abcdefgh' */ R.substringTo = substring(0); /** * The character at the nth position in a String: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} index An integer between 0 and the length of the string. * @param {String} str The string to extract a char from * @return {String} the character at `index` of `str` * @see R.invoker * @example * * R.charAt(8, 'abcdefghijklm'); //=> 'i' */ R.charAt = invoker('charAt', String.prototype); /** * The ascii code of the character at the nth position in a String: * * @func * @memberOf R * @category string * @sig Number -> String -> Number * @param {Number} index An integer between 0 and the length of the string. * @param {String} str The string to extract a charCode from * @return {Number} the code of the character at `index` of `str` * @see R.invoker * @example * * R.charCodeAt(8, 'abcdefghijklm'); //=> 105 * // (... 'a' ~ 97, 'b' ~ 98, ... 'i' ~ 105) */ R.charCodeAt = invoker('charCodeAt', String.prototype); /** * Tests a regular expression agains a String * * @func * @memberOf R * @category string * @sig RegExp -> String -> [String] | null * @param {RegExp} rx A regular expression. * @param {String} str The string to match against * @return {Array} The list of matches, or null if no matches found * @see R.invoker * @example * * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] */ R.match = invoker('match', String.prototype); /** * Finds the first index of a substring in a string, returning -1 if it's not present * * @func * @memberOf R * @category string * @sig String -> String -> Number * @param {String} c A string to find. * @param {String} str The string to search in * @return {Number} The first index of `c` or -1 if not found * @see R.invoker * @example * * R.strIndexOf('c', 'abcdefg'); //=> 2 */ R.strIndexOf = curry2(function _strIndexOf(c, str) { return str.indexOf(c); }); /** * * Finds the last index of a substring in a string, returning -1 if it's not present * * @func * @memberOf R * @category string * @sig String -> String -> Number * @param {String} c A string to find. * @param {String} str The string to search in * @return {Number} The last index of `c` or -1 if not found * @see R.invoker * @example * * R.strLastIndexOf('a', 'banana split'); //=> 5 */ R.strLastIndexOf = curry2(function(c, str) { return str.lastIndexOf(c); }); /** * The upper case version of a string. * * @func * @memberOf R * @category string * @sig String -> String * @param {string} str The string to upper case. * @return {string} The upper case version of `str`. * @example * * R.toUpperCase('abc'); //=> 'ABC' */ R.toUpperCase = invoker('toUpperCase', String.prototype); /** * The lower case version of a string. * * @func * @memberOf R * @category string * @sig String -> String * @param {string} str The string to lower case. * @return {string} The lower case version of `str`. * @example * * R.toLowerCase('XYZ'); //=> 'xyz' */ R.toLowerCase = invoker('toLowerCase', String.prototype); /** * Splits a string into an array of strings based on the given * separator. * * @func * @memberOf R * @category string * @sig String -> String -> [String] * @param {string} sep The separator string. * @param {string} str The string to separate into an array. * @return {Array} The array of strings from `str` separated by `str`. * @example * * var pathComponents = R.split('/'); * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node'] * * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] */ R.split = invoker('split', String.prototype, 1); /** * internal path function * Takes an array, paths, indicating the deep set of keys * to find. * * @private * @memberOf R * @category string * @param {Array} paths An array of strings to map to object properties * @param {Object} obj The object to find the path in * @return {Array} The value at the end of the path or `undefined`. * @example * * path(['a', 'b'], {a: {b: 2}}); //=> 2 */ function path(paths, obj) { var idx = -1, length = paths.length, val; if (obj == null) { return; } val = obj; while (val != null && ++idx < length) { val = val[paths[idx]]; } return val; } /** * Retrieve a nested path on an object seperated by the specified * separator value. * * @func * @memberOf R * @category string * @sig String -> String -> {*} -> * * @param {string} sep The separator to use in `path`. * @param {string} path The path to use. * @return {*} The data at `path`. * @example * * R.pathOn('/', 'a/b/c', {a: {b: {c: 3}}}); //=> 3 */ R.pathOn = curry3(function pathOn(sep, str, obj) { return path(str.split(sep), obj); }); /** * Retrieve a nested path on an object seperated by periods * * @func * @memberOf R * @category string * @sig String -> {*} -> * * @param {string} path The dot path to use. * @return {*} The data at `path`. * @example * * R.path('a.b', {a: {b: 2}}); //=> 2 */ R.path = R.pathOn('.'); // Data Analysis and Grouping Functions // ------------------------------------ // // Functions performing SQL-like actions on lists of objects. These do // not have any SQL-like optimizations performed on them, however. // -------- /** * Reasonable analog to SQL `select` statement. * * @func * @memberOf R * @category object * @category relation * @string [k] -> [{k: v}] -> [{k: v}] * @param {Array} props The property names to project * @param {Array} objs The objects to query * @return {Array} An array of objects with just the `props` properties. * @example * * var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; * var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; * var kids = [abby, fred]; * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] */ R.project = useWith(map, R.pickAll, identity); // passing `identity` gives correct arity /** * Determines whether the given property of an object has a specific * value according to strict equality (`===`). Most likely used to * filter a list: * * @func * @memberOf R * @category relation * @sig k -> v -> {k: v} -> Boolean * @param {string|number} name The property name (or index) to use. * @param {*} val The value to compare the property with. * @return {boolean} `true` if the properties are equal, `false` otherwise. * @example * * var abby = {name: 'Abby', age: 7, hair: 'blond'}; * var fred = {name: 'Fred', age: 12, hair: 'brown'}; * var rusty = {name: 'Rusty', age: 10, hair: 'brown'}; * var alois = {name: 'Alois', age: 15, disposition: 'surly'}; * var kids = [abby, fred, rusty, alois]; * var hasBrownHair = R.propEq('hair', 'brown'); * R.filter(hasBrownHair, kids); //=> [fred, rusty] */ R.propEq = curry3(function propEq(name, val, obj) { return obj[name] === val; }); /** * Combines two lists into a set (i.e. no duplicates) composed of the * elements of each list. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The first and second lists concatenated, with * duplicates removed. * @example * * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] */ R.union = compose(uniq, R.concat); /** * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is * determined according to the value returned by applying the supplied predicate to two list elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The first and second lists concatenated, with * duplicates removed. * @see R.union * @example * * function cmp(x, y) { return x.a === y.a; } * var l1 = [{a: 1}, {a: 2}]; * var l2 = [{a: 1}, {a: 4}]; * R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] */ R.unionWith = curry3(function _unionWith(pred, list1, list2) { return uniqWith(pred, concat(list1, list2)); }); /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The elements in `list1` that are not in `list2` * @see R.differenceWith * @example * * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] */ R.difference = curry2(function _difference(first, second) { return uniq(reject(flip(contains)(second), first)); }); /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. * Duplication is determined according to the value returned by applying the supplied predicate to two list * elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @see R.difference * @return {Array} The elements in `list1` that are not in `list2` * @example * * function cmp(x, y) { return x.a === y.a; } * var l1 = [{a: 1}, {a: 2}, {a: 3}]; * var l2 = [{a: 3}, {a: 4}]; * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] * */ R.differenceWith = curry3(function differenceWith(pred, first, second) { return uniqWith(pred)(reject(flip(R.containsWith(pred))(second), first)); }); /** * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @see R.intersectionWith * @return {Array} The list of elements found in both `list1` and `list2` * @example * * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] */ R.intersection = curry2(function intersection(list1, list2) { return uniq(filter(flip(contains)(list1), list2)); }); /** * Combines two lists into a set (i.e. no duplicates) composed of those * elements common to both lists. Duplication is determined according * to the value returned by applying the supplied predicate to two list * elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred A predicate function that determines whether * the two supplied elements are equal. * Signatrue: a -> a -> Boolean * @param {Array} list1 One list of items to compare * @param {Array} list2 A second list of items to compare * @see R.intersection * @return {Array} A new list containing those elements common to both lists. * @example * * var buffaloSpringfield = [ * {id: 824, name: 'Richie Furay'}, * {id: 956, name: 'Dewey Martin'}, * {id: 313, name: 'Bruce Palmer'}, * {id: 456, name: 'Stephen Stills'}, * {id: 177, name: 'Neil Young'} * ]; * var csny = [ * {id: 204, name: 'David Crosby'}, * {id: 456, name: 'Stephen Stills'}, * {id: 539, name: 'Graham Nash'}, * {id: 177, name: 'Neil Young'} * ]; * * var sameId = function(o1, o2) {return o1.id === o2.id;}; * * R.intersectionWith(sameId, buffaloSpringfield, csny); * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] */ R.intersectionWith = curry3(function intersectionWith(pred, list1, list2) { var results = [], idx = -1; while (++idx < list1.length) { if (containsWith(pred, list1[idx], list2)) { results[results.length] = list1[idx]; } } return uniqWith(pred, results); }); /** * Creates a new list whose elements each have two properties: `val` is * the value of the corresponding item in the list supplied, and `key` * is the result of applying the supplied function to that item. * * @private * @func * @memberOf R * @category relation * @param {Function} fn An arbitrary unary function returning a potential * object key. Signature: Any -> String * @param {Array} list The list of items to process * @return {Array} A new list with the described structure. * @example * * var people = [ * {first: 'Fred', last: 'Flintstone', age: 23}, * {first: 'Betty', last: 'Rubble', age: 21}, * {first: 'George', last: 'Jetson', age: 29} * ]; * * var fullName = function(p) {return p.first + ' ' + p.last;}; * * keyValue(fullName, people); //=> * // [ * // { * // key: 'Fred Flintstone', * // val: {first: 'Fred', last: 'Flintstone', age: 23} * // }, { * // key: 'Betty Rubble', * // val: {first: 'Betty', last: 'Rubble', age: 21} * // }, { * // key: 'George Jetson', * // val: {first: 'George', last: 'Jetson', age: 29} * // } * // ]; */ function keyValue(fn, list) { // TODO: Should this be made public? return map(function(item) {return {key: fn(item), val: item};}, list); } /** * Sorts the list according to a key generated by the supplied function. * * @func * @memberOf R * @category relation * @sig (a -> String) -> [a] -> [a] * @param {Function} fn The function mapping `list` items to keys. * @param {Array} list The list to sort. * @return {Array} A new list sorted by the keys generated by `fn`. * @example * * var sortByFirstItem = R.sortBy(prop(0)); * var sortByNameCaseInsensitive = R.sortBy(compose(R.toLowerCase, prop('name'))); * var pairs = [[-1, 1], [-2, 2], [-3, 3]]; * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] * var alice = { * name: 'ALICE', * age: 101 * }; * var bob = { * name: 'Bob', * age: -10 * }; * var clara = { * name: 'clara', * age: 314.159 * }; * var people = [clara, bob, alice]; * sortByNameCaseInsensitive(people); //=> [alice, bob, clara] */ R.sortBy = curry2(function sortBy(fn, list) { return pluck('val', keyValue(fn, list).sort(comparator(function(a, b) {return a.key < b.key;}))); }); /** * Counts the elements of a list according to how many match each value * of a key generated by the supplied function. Returns an object * mapping the keys produced by `fn` to the number of occurrences in * the list. Note that all keys are coerced to strings because of how * JavaScript objects work. * * @func * @memberOf R * @category relation * @sig (a -> String) -> [a] -> {*} * @param {Function} fn The function used to map values to keys. * @param {Array} list The list to count elements from. * @return {Object} An object mapping keys to number of occurrences in the list. * @example * * var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; * var letters = R.split('', 'abcABCaaaBBc'); * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} * R.countBy(R.toLowerCase)(letters); //=> {'a': 5, 'b': 4, 'c': 3} */ R.countBy = curry2(function countBy(fn, list) { return foldl(function(counts, obj) { counts[obj.key] = (counts[obj.key] || 0) + 1; return counts; }, {}, keyValue(fn, list)); }); /** * @private * @param {Function} fn The strategy for extracting function names from an object * @return {Function} A function that takes an object and returns an array of function names * */ var functionsWith = function(fn) { return function(obj) { return R.filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj)); }; }; /** * Returns a list of function names of object's own functions * * @func * @memberOf R * @category Object * @sig {*} -> [String] * @param {Object} obj The objects with functions in it * @return {Array} returns a list of the object's own properites that map to functions * @example * * R.functions(R); // returns list of ramda's own function names * * var F = function() { this.x = function(){}; this.y = 1; } * F.prototype.z = function() {}; * F.prototype.a = 100; * R.functions(new F()); //=> ["x"] */ R.functions = functionsWith(R.keys); /** * Returns a list of function names of object's own and prototype functions * * @func * @memberOf R * @category Object * @sig {*} -> [String] * @param {Object} obj The objects with functions in it * @return {Array} returns a list of the object's own properites and prototype * properties that map to functions * @example * * R.functionsIn(R); // returns list of ramda's own and prototype function names * * var F = function() { this.x = function(){}; this.y = 1; } * F.prototype.z = function() {}; * F.prototype.a = 100; * R.functionsIn(new F()); //=> ["x", "z"] */ R.functionsIn = functionsWith(R.keysIn); // All the functional goodness, wrapped in a nice little package, just for you! return R; }));
/** * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. * @author Glen Mailer * @copyright 2015 Glen Mailer */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var FUNCTION_MESSAGE = "Unexpected newline between function and ( of function call."; var PROPERTY_MESSAGE = "Unexpected newline between object and [ of property access."; /** * Check to see if the bracket prior to the node is continuing the previous * line's expression * @param {ASTNode} node The node to check. * @param {string} msg The error message to use. * @returns {void} * @private */ function checkForBreakBefore(node, msg) { var tokens = context.getTokensBefore(node, 2); var paren = tokens[1]; var before = tokens[0]; if (paren.loc.start.line !== before.loc.end.line) { context.report(node, paren.loc.start, msg, { char: paren.value }); } } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- return { "MemberExpression": function(node) { if (!node.computed) { return; } checkForBreakBefore(node.property, PROPERTY_MESSAGE); }, "CallExpression": function(node) { if (node.arguments.length === 0) { return; } checkForBreakBefore(node.arguments[0], FUNCTION_MESSAGE); } }; }; module.exports.schema = [];
YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { // check for a toXXX conversion method first // if it doesn't exist, use the toXxx conversion method var convert = Y.Color.CONVERTS[to], clr = Y.Color[convert](str); return clr.toLowerCase(); }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values. Will return an empty array if the provided string is not able to be parsed. @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]});
/** * @license AngularJS v1.3.10 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; var $sanitizeMinErr = angular.$$minErr('$sanitize'); /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* * HTML Parser By Misko Hevery ([email protected]) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. The input may also contain SVG markup. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getInnerHtml()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ function $SanitizeProvider() { this.$get = ['$$sanitizeUri', function($$sanitizeUri) { return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, angular.noop); writer.chars(chars); return buf.join(''); } // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/, END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\//, COMMENT_REGEXP = /<!--(.*?)-->/g, DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," + "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," + "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," + "stop,svg,switch,text,title,tspan,use"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements, svgElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href"); var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' + 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' + 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' + 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' + 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' + 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' + 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' + 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' + 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' + 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' + 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' + 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' + 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' + 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' + 'zoomAndPan'); var validAttrs = angular.extend({}, uriAttrs, svgAttrs, htmlAttrs); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser(html, handler) { if (typeof html !== 'string') { if (html === null || typeof html === 'undefined') { html = ''; } else { html = '' + html; } } var index, chars, match, stack = [], last = html, text; stack.last = function() { return stack[ stack.length - 1 ]; }; while (html) { text = ''; chars = true; // Make sure we're not in a script or style element if (!stack.last() || !specialElements[ stack.last() ]) { // Comment if (html.indexOf("<!--") === 0) { // comments containing -- are not allowed unless they terminate the comment index = html.indexOf("--", 4); if (index >= 0 && html.lastIndexOf("-->", index) === index) { if (handler.comment) handler.comment(html.substring(4, index)); html = html.substring(index + 3); chars = false; } // DOCTYPE } else if (DOCTYPE_REGEXP.test(html)) { match = html.match(DOCTYPE_REGEXP); if (match) { html = html.replace(match[0], ''); chars = false; } // end tag } else if (BEGING_END_TAGE_REGEXP.test(html)) { match = html.match(END_TAG_REGEXP); if (match) { html = html.substring(match[0].length); match[0].replace(END_TAG_REGEXP, parseEndTag); chars = false; } // start tag } else if (BEGIN_TAG_REGEXP.test(html)) { match = html.match(START_TAG_REGEXP); if (match) { // We only have a valid start-tag if there is a '>'. if (match[4]) { html = html.substring(match[0].length); match[0].replace(START_TAG_REGEXP, parseStartTag); } chars = false; } else { // no ending tag found --- this piece should be encoded as an entity. text += '<'; html = html.substring(1); } } if (chars) { index = html.indexOf("<"); text += index < 0 ? html : html.substring(0, index); html = index < 0 ? "" : html.substring(index); if (handler.chars) handler.chars(decodeEntities(text)); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text) { text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars(decodeEntities(text)); return ""; }); parseEndTag("", stack.last()); } if (html == last) { throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + "of html: {0}", html); } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag(tag, tagName, rest, unary) { tagName = angular.lowercase(tagName); if (blockElements[ tagName ]) { while (stack.last() && inlineElements[ stack.last() ]) { parseEndTag("", stack.last()); } } if (optionalEndTagElements[ tagName ] && stack.last() == tagName) { parseEndTag("", tagName); } unary = voidElements[ tagName ] || !!unary; if (!unary) stack.push(tagName); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { var value = doubleQuotedValue || singleQuotedValue || unquotedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start(tagName, attrs, unary); } function parseEndTag(tag, tagName) { var pos = 0, i; tagName = angular.lowercase(tagName); if (tagName) // Find the closest opened tag of the same type for (pos = stack.length - 1; pos >= 0; pos--) if (stack[ pos ] == tagName) break; if (pos >= 0) { // Close all the open elements, up the stack for (i = stack.length - 1; i >= pos; i--) if (handler.end) handler.end(stack[ i ]); // Remove the open elements from the stack stack.length = pos; } } } var hiddenPre=document.createElement("pre"); var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ function decodeEntities(value) { if (!value) { return ''; } // Note: IE8 does not preserve spaces at the start/end of innerHTML // so we must capture them and reattach them afterward var parts = spaceRe.exec(value); var spaceBefore = parts[1]; var spaceAfter = parts[3]; var content = parts[2]; if (content) { hiddenPre.innerHTML=content.replace(/</g,"&lt;"); // innerText depends on styling as it doesn't display hidden elements. // Therefore, it's better to use textContent not to cause unnecessary // reflows. However, IE<9 don't support textContent so the innerText // fallback is necessary. content = 'textContent' in hiddenPre ? hiddenPre.textContent : hiddenPre.innerText; } return spaceBefore + content + spaceAfter; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { // unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html // decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535 var c = value.charCodeAt(0); // if unsafe character encode if(c <= 159 || c == 173 || (c >= 1536 && c <= 1540) || c == 1807 || c == 6068 || c == 6069 || (c >= 8204 && c <= 8207) || (c >= 8232 && c <= 8239) || (c >= 8288 && c <= 8303) || c == 65279 || (c >= 65520 && c <= 65535)) return '&#' + c + ';'; return value; // avoids multilingual issues }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } var trim = (function() { // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; }; } return function(value) { return angular.isString(value) ? value.trim() : value; }; })(); // Custom logic for accepting certain style options only - textAngular // Currently allows only the color, background-color, text-align, float, width and height attributes // all other attributes should be easily done through classes. function validStyles(styleAttr){ var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function(value){ var v = value.split(':'); if(v.length == 2){ var key = trim(angular.lowercase(v[0])); var value = trim(angular.lowercase(v[1])); if( (key === 'color' || key === 'background-color') && ( value.match(/^rgb\([0-9%,\. ]*\)$/i) || value.match(/^rgba\([0-9%,\. ]*\)$/i) || value.match(/^hsl\([0-9%,\. ]*\)$/i) || value.match(/^hsla\([0-9%,\. ]*\)$/i) || value.match(/^#[0-9a-f]{3,6}$/i) || value.match(/^[a-z]*$/i) ) || key === 'text-align' && ( value === 'left' || value === 'right' || value === 'center' || value === 'justify' ) || key === 'float' && ( value === 'left' || value === 'right' || value === 'none' ) || (key === 'width' || key === 'height') && ( value.match(/[0-9\.]*(px|em|rem|%)/) ) ) result += key + ': ' + value + ';'; } }); return result; } // this function is used to manually allow specific attributes on specific tags with certain prerequisites function validCustomTag(tag, attrs, lkey, value){ // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']){ if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) return true; } return false; } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf, uriValidator) { var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary) { tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] === true) { out('<'); out(tag); angular.forEach(attrs, function(value, key) { var lkey=angular.lowercase(key); var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background'); if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag) { tag = angular.lowercase(tag); if (!ignore && validElements[tag] === true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars) { if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /* global sanitizeText: false */ /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. * @returns {string} Html-linkified text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="linkyExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:[email protected],\n'+ '[email protected],\n'+ 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithTarget = 'http://angularjs.org/'; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, [email protected], ' + '[email protected], and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:[email protected], ' + '[email protected], and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/, MAILTO_REGEXP = /^mailto:/; return function(text, target) { if (!text) return text; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { html.push('<a '); if (angular.isDefined(target)) { html.push('target="', target, '" '); } html.push('href="', url.replace(/"/g, '&quot;'), '">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require rails-ujs //= require turbolinks //= require_tree .
YUI.add('escape', function(Y) { /** Provides utility methods for escaping strings. @module escape @class Escape @static @since 3.3.0 **/ var HTML_CHARS = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;', '`': '&#x60;' }, Escape = { // -- Public Static Methods ------------------------------------------------ /** Returns a copy of the specified string with special HTML characters escaped. The following characters will be converted to their corresponding character entities: & < > " ' / ` This implementation is based on the [OWASP HTML escaping recommendations][1]. In addition to the characters in the OWASP recommendations, we also escape the <code>&#x60;</code> character, since IE interprets it as an attribute delimiter. If _string_ is not already a string, it will be coerced to a string. [1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet @method html @param {String} string String to escape. @return {String} Escaped string. @static **/ html: function (string) { return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer); }, /** Returns a copy of the specified string with special regular expression characters escaped, allowing the string to be used safely inside a regex. The following characters, and all whitespace characters, are escaped: - # $ ^ * ( ) + [ ] { } | \ , . ? If _string_ is not already a string, it will be coerced to a string. @method regex @param {String} string String to escape. @return {String} Escaped string. @static **/ regex: function (string) { return (string + '').replace(/[\-#$\^*()+\[\]{}|\\,.?\s]/g, '\\$&'); }, // -- Protected Static Methods --------------------------------------------- /** * Regex replacer for HTML escaping. * * @method _htmlReplacer * @param {String} match Matched character (must exist in HTML_CHARS). * @returns {String} HTML entity. * @static * @protected */ _htmlReplacer: function (match) { return HTML_CHARS[match]; } }; Escape.regexp = Escape.regex; Y.Escape = Escape; }, '@VERSION@' ,{requires:['yui-base']});
import React, {useState} from 'react'; import { ScrollView, StyleSheet, Text, TouchableOpacity, Platform, Linking, } from 'react-native'; import AutoHeightWebView from 'react-native-autoheight-webview'; import { autoHeightHtml0, autoHeightHtml1, autoHeightScript, autoWidthHtml0, autoWidthHtml1, autoWidthScript, autoDetectLinkScript, style0, inlineBodyStyle, } from './config'; const onShouldStartLoadWithRequest = result => { console.log(result); return true; }; const onError = ({nativeEvent}) => console.error('WebView error: ', nativeEvent); const onMessage = event => { const {data} = event.nativeEvent; let messageData; // maybe parse stringified JSON try { messageData = JSON.parse(data); } catch (e) { console.log(e.message); } if (typeof messageData === 'object') { const {url} = messageData; // check if this message concerns us if (url && url.startsWith('http')) { Linking.openURL(url).catch(error => console.error('An error occurred', error), ); } } }; const onHeightLoadStart = () => console.log('height on load start'); const onHeightLoad = () => console.log('height on load'); const onHeightLoadEnd = () => console.log('height on load end'); const onWidthLoadStart = () => console.log('width on load start'); const onWidthLoad = () => console.log('width on load'); const onWidthLoadEnd = () => console.log('width on load end'); const Explorer = () => { const [{widthHtml, heightHtml}, setHtml] = useState({ widthHtml: autoWidthHtml0, heightHtml: autoHeightHtml0, }); const changeSource = () => setHtml({ widthHtml: widthHtml === autoWidthHtml0 ? autoWidthHtml1 : autoWidthHtml0, heightHtml: heightHtml === autoHeightHtml0 ? autoHeightHtml1 : autoHeightHtml0, }); const [{widthStyle, heightStyle}, setStyle] = useState({ heightStyle: null, widthStyle: inlineBodyStyle, }); const changeStyle = () => setStyle({ widthStyle: widthStyle === inlineBodyStyle ? style0 + inlineBodyStyle : inlineBodyStyle, heightStyle: heightStyle === null ? style0 : null, }); const [{widthScript, heightScript}, setScript] = useState({ heightScript: autoDetectLinkScript, widthScript: null, }); const changeScript = () => setScript({ widthScript: widthScript == autoWidthScript ? autoWidthScript : null, heightScript: heightScript !== autoDetectLinkScript ? autoDetectLinkScript : autoHeightScript + autoDetectLinkScript, }); const [heightSize, setHeightSize] = useState({height: 0, width: 0}); const [widthSize, setWidthSize] = useState({height: 0, width: 0}); return ( <ScrollView style={{ paddingTop: 45, backgroundColor: 'lightyellow', }} contentContainerStyle={{ justifyContent: 'center', alignItems: 'center', }}> <AutoHeightWebView customStyle={heightStyle} onError={onError} onLoad={onHeightLoad} onLoadStart={onHeightLoadStart} onLoadEnd={onHeightLoadEnd} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} onSizeUpdated={setHeightSize} source={{html: heightHtml}} customScript={heightScript} onMessage={onMessage} /> <Text style={{padding: 5}}> height: {heightSize.height}, width: {heightSize.width} </Text> <AutoHeightWebView style={{ marginTop: 15, }} customStyle={widthStyle} onError={onError} onLoad={onWidthLoad} onLoadStart={onWidthLoadStart} onLoadEnd={onWidthLoadEnd} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} onSizeUpdated={setWidthSize} allowFileAccessFromFileURLs={true} allowUniversalAccessFromFileURLs={true} source={{ html: widthHtml, baseUrl: Platform.OS === 'android' ? 'file:///android_asset/' : 'web/', }} customScript={widthScript} /> <Text style={{padding: 5}}> height: {widthSize.height}, width: {widthSize.width} </Text> <TouchableOpacity onPress={changeSource} style={styles.button}> <Text>change source</Text> </TouchableOpacity> <TouchableOpacity onPress={changeStyle} style={styles.button}> <Text>change style</Text> </TouchableOpacity> <TouchableOpacity onPress={changeScript} style={[styles.button, {marginBottom: 100}]}> <Text>change script</Text> </TouchableOpacity> </ScrollView> ); }; const styles = StyleSheet.create({ button: { marginTop: 15, backgroundColor: 'aliceblue', borderRadius: 5, padding: 5, }, }); export default Explorer;
"use strict"; import clear from "rollup-plugin-clear"; import resolve from "rollup-plugin-node-resolve"; import commonjs from "rollup-plugin-commonjs"; import typescript from "rollup-plugin-typescript2"; import screeps from "rollup-plugin-screeps"; let cfg; const dest = process.env.DEST; if (!dest) { console.log("No destination specified - code will be compiled but not uploaded"); } else if ((cfg = require("./screeps.json")[dest]) == null) { throw new Error("Invalid upload destination"); } export default { input: "src/main.ts", output: { file: "dist/main.js", format: "cjs", sourcemap: true }, plugins: [ clear({ targets: ["dist"] }), resolve(), commonjs(), typescript({tsconfig: "./tsconfig.json"}), screeps({config: cfg, dryRun: cfg == null}) ] }
import { timeout as d3_timeout } from 'd3-timer'; export function uiFlash(context) { var _flashTimer; var _duration = 2000; var _iconName = '#iD-icon-no'; var _iconClass = 'disabled'; var _text = ''; var _textClass; function flash() { if (_flashTimer) { _flashTimer.stop(); } context.container().select('.main-footer-wrap') .classed('footer-hide', true) .classed('footer-show', false); context.container().select('.flash-wrap') .classed('footer-hide', false) .classed('footer-show', true); var content = context.container().select('.flash-wrap').selectAll('.flash-content') .data([0]); // Enter var contentEnter = content.enter() .append('div') .attr('class', 'flash-content'); var iconEnter = contentEnter .append('svg') .attr('class', 'flash-icon') .append('g') .attr('transform', 'translate(10,10)'); iconEnter .append('circle') .attr('r', 9); iconEnter .append('use') .attr('transform', 'translate(-7,-7)') .attr('width', '14') .attr('height', '14'); contentEnter .append('div') .attr('class', 'flash-text'); // Update content = content .merge(contentEnter); content .selectAll('.flash-icon') .attr('class', 'flash-icon ' + (_iconClass || '')); content .selectAll('.flash-icon use') .attr('xlink:href', _iconName); content .selectAll('.flash-text') .attr('class', 'flash-text ' + (_textClass || '')) .text(_text); _flashTimer = d3_timeout(function() { _flashTimer = null; context.container().select('.main-footer-wrap') .classed('footer-hide', false) .classed('footer-show', true); context.container().select('.flash-wrap') .classed('footer-hide', true) .classed('footer-show', false); }, _duration); return content; } flash.duration = function(_) { if (!arguments.length) return _duration; _duration = _; return flash; }; flash.text = function(_) { if (!arguments.length) return _text; _text = _; return flash; }; flash.textClass = function(_) { if (!arguments.length) return _textClass; _textClass = _; return flash; }; flash.iconName = function(_) { if (!arguments.length) return _iconName; _iconName = _; return flash; }; flash.iconClass = function(_) { if (!arguments.length) return _iconClass; _iconClass = _; return flash; }; return flash; }
"use strict"; const http_1 = require("http"); const WebSocketServer = require("ws"); const express = require("express"); const dgram = require("dgram"); const readUInt64BE = require("readuint64be"); const buffer_1 = require("buffer"); const _ = require("lodash"); // Health Insurrance: process.on("uncaughtException", function (err) { console.log(err); }); const debug = require("debug")("PeerTracker:Server"), redis = require("redis"), GeoIpNativeLite = require("geoip-native-lite"), bencode = require("bencode"); // Load in GeoData GeoIpNativeLite.loadDataSync(); // Keep statistics going, update every 30 min let stats = { seedCount: 0, leechCount: 0, torrentCount: 0, activeTcount: 0, scrapeCount: 0, successfulDown: 0, countries: {} }; const ACTION_CONNECT = 0, ACTION_ANNOUNCE = 1, ACTION_SCRAPE = 2, ACTION_ERROR = 3, INTERVAL = 1801, startConnectionIdHigh = 0x417, startConnectionIdLow = 0x27101980; // Without using streams, this can handle ~320 IPv4 addresses. More doesn't necessarily mean better. const MAX_PEER_SIZE = 1500; const FOUR_AND_FIFTEEN_DAYS = 415 * 24 * 60 * 60; // assuming start time is seconds for redis; // Redis let client; class Server { constructor(opts) { this._debug = (...args) => { args[0] = "[" + this._debugId + "] " + args[0]; debug.apply(null, args); }; const self = this; if (!opts) opts = { port: 80, udpPort: 1337, docker: false }; self._debugId = ~~((Math.random() * 100000) + 1); self._debug("peer-tracker Server instance created"); self.PORT = opts.port; self.udpPORT = opts.udpPort; self.server = http_1.createServer(); self.wss = new WebSocketServer.Server({ server: self.server }); self.udp4 = dgram.createSocket({ type: "udp4", reuseAddr: true }); self.app = express(); // PREP VISUAL AID: console.log(` . | | | ||| /___\\ |_ _| | | | | | | | | |__| |__| | | | | | | | | | | | | Peer Tracker 1.1.0 | | | | | | | | Running in standalone mode | | | | UDP PORT: ${self.udpPORT} | | | | HTTP & WS PORT: ${self.PORT} | | | | | |_| | |__| |__| | | | | LET'S BUILD AN EMPIRE! | | | | https://github.com/CraigglesO/peer-tracker | | | | | | | | |____|_|____| `); // Redis if (opts.docker) client = redis.createClient("6379", "redis"); else client = redis.createClient(); // If an error occurs, print it to the console client.on("error", function (err) { console.log("Redis error: " + err); }); client.on("ready", function () { console.log(new Date() + ": Redis is up and running."); }); self.app.set("trust proxy", function (ip) { return true; }); // Express self.app.get("/", function (req, res) { let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; if (ip.indexOf("::ffff:") !== -1) ip = ip.slice(7); res.status(202).send("Welcome to the Empire. Your address: " + ip); }); self.app.get("/stat.json", function (req, res) { res.status(202).send(stats); }); self.app.get("/stat", function (req, res) { // { seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }; let parsedResponce = `<h1><span style="color:blue;">V1.0.3</span> - ${stats.torrentCount} Torrents {${stats.activeTcount} active}</h1>\n <h2>Successful Downloads: ${stats.successfulDown}</h2>\n <h2>Number of Scrapes to this tracker: ${stats.scrapeCount}</h2>\n <h3>Connected Peers: ${stats.seedCount + stats.leechCount}</h3>\n <h3><ul>Seeders: ${stats.seedCount}</ul></h3>\n <h3><ul>Leechers: ${stats.leechCount}</ul></h3>\n <h3>Countries that have connected: <h3>\n <ul>`; let countries; for (countries in stats.countries) parsedResponce += `<li>${stats.countries[countries]}</li>\n`; parsedResponce += "</ul>"; res.status(202).send(parsedResponce); }); self.app.get("*", function (req, res) { res.status(404).send("<h1>404 Not Found</h1>"); }); self.server.on("request", self.app.bind(self)); self.server.listen(self.PORT, function () { console.log(new Date() + ": HTTP Server Ready" + "\n" + new Date() + ": Websockets Ready."); }); // WebSocket: self.wss.on("connection", function connection(ws) { // let location = url.parse(ws.upgradeReq.url, true); let ip; let peerAddress; let port; if (opts.docker) { ip = ws.upgradeReq.headers["x-forwarded-for"]; peerAddress = ip.split(":")[0]; port = ip.split(":")[1]; } else { peerAddress = ws._socket.remoteAddress; port = ws._socket.remotePort; } if (peerAddress.indexOf("::ffff:") !== -1) peerAddress = peerAddress.slice(7); console.log("peerAddress", peerAddress); ws.on("message", function incoming(msg) { handleMessage(msg, peerAddress, port, "ws", (reply) => { ws.send(reply); }); }); }); // UDP: self.udp4.bind(self.udpPORT); self.udp4.on("message", function (msg, rinfo) { handleMessage(msg, rinfo.address, rinfo.port, "udp", (reply) => { self.udp4.send(reply, 0, reply.length, rinfo.port, rinfo.address, (err) => { if (err) { console.log("udp4 error: ", err); } ; }); }); }); self.udp4.on("error", function (err) { console.log("error", err); }); self.udp4.on("listening", () => { console.log(new Date() + ": UDP-4 Bound and ready."); }); self.updateStatus((info) => { stats = info; }); setInterval(() => { console.log("STAT UPDATE, " + Date.now()); self.updateStatus((info) => { stats = info; }); }, 30 * 60 * 1000); } updateStatus(cb) { const self = this; // Get hashes -> iterate through hashes and get all peers and leechers // Also get number of scrapes 'scrape' // Number of active hashes hash+':time' let NOW = Date.now(), seedCount = 0, // check leechCount = 0, // check torrentCount = 0, // check activeTcount = 0, // check scrapeCount = 0, // check successfulDown = 0, // check countries = {}; client.get("hashes", (err, reply) => { if (!reply) return; let hashList = reply.split(","); torrentCount = hashList.length; client.get("scrape", (err, rply) => { if (err) { return; } if (!rply) return; scrapeCount = rply; }); hashList.forEach((hash, i) => { client.mget([hash + ":seeders", hash + ":leechers", hash + ":time", hash + ":completed"], (err, rply) => { if (err) { return; } // iterate through: // seeders if (rply[0]) { rply[0] = rply[0].split(","); seedCount += rply[0].length; rply[0].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[1]) { rply[1] = rply[1].split(","); seedCount += rply[1].length; rply[1].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[2]) { if (((NOW - rply[2]) / 1000) < 432000) activeTcount++; } if (rply[3]) { successfulDown += Number(rply[3]); } if (i === (torrentCount - 1)) { cb({ seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }); } }); }); }); } } // MESSAGE FUNCTIONS: function handleMessage(msg, peerAddress, port, type, cb) { // PACKET SIZES: // CONNECT: 16 - ANNOUNCE: 98 - SCRAPE: 16 OR (16 + 20 * n) let buf = new buffer_1.Buffer(msg), bufLength = buf.length, transaction_id = 0, action = null, connectionIdHigh = null, connectionIdLow = null, hash = null, responce = null, PEER_ID = null, PEER_ADDRESS = null, PEER_KEY = null, NUM_WANT = null, peerPort = port, peers = null; // Ensure packet fullfills the minimal 16 byte requirement. if (bufLength < 16) { ERROR(); } else { // Get generic data: connectionIdHigh = buf.readUInt32BE(0), connectionIdLow = buf.readUInt32BE(4), action = buf.readUInt32BE(8), transaction_id = buf.readUInt32BE(12); // 12 32-bit integer transaction_id } switch (action) { case ACTION_CONNECT: // Check whether the transaction ID is equal to the one you chose. if (startConnectionIdLow !== connectionIdLow || startConnectionIdHigh !== connectionIdHigh) { ERROR(); break; } // Create a new Connection ID and Transaction ID for this user... kill after 30 seconds: let newConnectionIDHigh = ~~((Math.random() * 100000) + 1); let newConnectionIDLow = ~~((Math.random() * 100000) + 1); client.setex(peerAddress + ":" + newConnectionIDHigh, 60, 1); client.setex(peerAddress + ":" + newConnectionIDLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdHigh, 60, 1); // client.setex(peerAddress + ':' + transaction_id , 30 * 1000, 1); // THIS MIGHT BE WRONG // Create a responce buffer: responce = new buffer_1.Buffer(16); responce.fill(0); responce.writeUInt32BE(ACTION_CONNECT, 0); // 0 32-bit integer action 0 // connect responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(newConnectionIDHigh, 8); // 8 64-bit integer connection_id responce.writeUInt32BE(newConnectionIDLow, 12); // 8 64-bit integer connection_id cb(responce); break; case ACTION_ANNOUNCE: // Checks to make sure the packet is worth analyzing: // 1. packet is atleast 84 bytes if (bufLength < 84) { ERROR(); break; } // Minimal requirements: hash = buf.slice(16, 36); hash = hash.toString("hex"); PEER_ID = buf.slice(36, 56); // -WD0017-I0mH4sMSAPOJ && -LT1000-9BjtQhMtTtTc PEER_ID = PEER_ID.toString(); let DOWNLOADED = readUInt64BE(buf, 56), LEFT = readUInt64BE(buf, 64), UPLOADED = readUInt64BE(buf, 72), EVENT = buf.readUInt32BE(80); if (bufLength > 96) { PEER_ADDRESS = buf.readUInt16BE(84); PEER_KEY = buf.readUInt16BE(88); NUM_WANT = buf.readUInt16BE(92); peerPort = buf.readUInt16BE(96); } // 2. check that Transaction ID and Connection ID match client.mget([peerAddress + ":" + connectionIdHigh, peerAddress + ":" + connectionIdLow], (err, reply) => { if (!reply[0] || !reply[1] || err) { ERROR(); return; } addHash(hash); // Check EVENT // 0: none; 1: completed; 2: started; 3: stopped // If 1, 2, or 3 do sets first. if (EVENT === 1) { // Change the array this peer is housed in. removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); // Increment total users who completed file client.incr(hash + ":completed"); } else if (EVENT === 2) { // Add to array (leecher array if LEFT is > 0) if (LEFT > 0) addPeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); else addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); } else if (EVENT === 3) { // Remove peer from array (leecher array if LEFT is > 0) removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); removePeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); return; } client.mget([hash + type + ":seeders", hash + type + ":leechers"], (err, rply) => { if (err) { ERROR(); return; } // Convert all addresses to a proper hex buffer: // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize let addresses = addrToBuffer(rply[0], rply[1], LEFT); // Create a responce buffer: responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(ACTION_ANNOUNCE, 0); // 0 32-bit integer action 1 -> announce responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(INTERVAL, 8); // 8 32-bit integer interval responce.writeUInt32BE(addresses[0], 12); // 12 32-bit integer leechers responce.writeUInt32BE(addresses[1], 16); // 16 32-bit integer seeders responce = buffer_1.Buffer.concat([responce, addresses[2]]); // 20 + 6 * n 32-bit integer IP address // 24 + 6 * n 16-bit integer TCP port cb(responce); }); }); break; case ACTION_SCRAPE: // Check whether the transaction ID is equal to the one you chose. // 2. check that Transaction ID and Connection ID match // addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Create a responce buffer: client.incr("scrape"); let responces = new buffer_1.Buffer(8); responces.fill(0); responces.writeUInt32BE(ACTION_SCRAPE, 0); // 0 32-bit integer action 2 -> scrape responces.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id let bufferSum = []; // LOOP THROUGH REQUESTS for (let i = 16; i < (buf.length - 16); i += 20) { hash = buf.slice(i, i + 20); hash = hash.toString("hex"); client.mget([hash + type + ":seeders", hash + type + ":leechers", hash + type + ":completed"], (err, rply) => { if (err) { ERROR(); return; } // convert all addresses to a proper hex buffer: let addresses = addrToBuffer(rply[0], rply[1], 1); let responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(addresses[1], 8); // 8 + 12 * n 32-bit integer seeders responce.writeUInt32BE(rply[2], 12); // 12 + 12 * n 32-bit integer completed responce.writeUInt32BE(addresses[0], 16); // 16 + 12 * n 32-bit integer leechers bufferSum.push(responce); if ((i + 16) >= (buf.length - 16)) { let scrapes = buffer_1.Buffer.concat(bufferSum); responces = buffer_1.Buffer.concat([responces, scrapes]); cb(responces); } }); } break; default: ERROR(); } function ERROR() { responce = new buffer_1.Buffer(11); responce.fill(0); responce.writeUInt32BE(ACTION_ERROR, 0); responce.writeUInt32BE(transaction_id, 4); responce.write("900", 8); cb(responce); } function addPeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) reply = peer; else reply = peer + "," + reply; reply = reply.split(","); reply = _.uniq(reply); // Keep the list under MAX_PEER_SIZE; if (reply.length > MAX_PEER_SIZE) { reply = reply.slice(0, MAX_PEER_SIZE); } reply = reply.join(","); client.set(where, reply); } }); } function removePeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) return; else { reply = reply.split(","); let index = reply.indexOf(peer); if (index > -1) { reply.splice(index, 1); } reply = reply.join(","); client.set(where, reply); } } }); } function addrToBuffer(seeders, leechers, LEFT) { // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Also we don't need to send the users own address // If peer is a leecher, send more seeders; if peer is a seeder, send only leechers let leecherCount = 0, seederCount = 0, peerBuffer = null, peerBufferSize = 0; if (LEFT === 0 || !seeders || seeders === "") seeders = new buffer_1.Buffer(0); else { seeders = seeders.split(","); seederCount = seeders.length; seeders = seeders.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); seeders = buffer_1.Buffer.concat(seeders); } if (LEFT > 0 && seederCount > 50 && leechers > 15) leechers = leechers.slice(0, 15); if (!leechers || leechers === "") leechers = new buffer_1.Buffer(0); else { leechers = leechers.split(","); leecherCount = leechers.length; leechers = leechers.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); leechers = buffer_1.Buffer.concat(leechers); } peerBuffer = buffer_1.Buffer.concat([seeders, leechers]); // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize return [leecherCount, seederCount, peerBuffer]; } // Add a new hash to the swarm, ensure uniqeness function addHash(hash) { client.get("hashes", (err, reply) => { if (err) { ERROR(); return; } if (!reply) reply = hash; else reply = hash + "," + reply; reply = reply.split(","); reply = _.uniq(reply); reply = reply.join(","); client.set("hashes", reply); client.set(hash + ":time", Date.now()); }); } function getHashes() { let r = client.get("hashes", (err, reply) => { if (err) { ERROR(); return null; } reply = reply.split(","); return reply; }); return r; } } function binaryToHex(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "binary").toString("hex"); } function hexToBinary(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "hex").toString("binary"); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Server; //# sourceMappingURL=/Users/connor/Desktop/Programming/myModules/peer-tracker/ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js.map
var parseString = require('xml2js').parseString; module.exports = function(req, res, next){ if (req.is('xml')){ var data = ''; req.setEncoding('utf8'); req.on('data', function(chunk){ data += chunk; }); req.on('end', function(){ if (!data){ return next(); } parseString(data, { trim: true, explicitArray: false }, function(err, result){ if (!err){ req.body = result || {}; } else { return res.error('BAD_REQUEST'); } next(); }); }); } else { next(); } };
"use strict"; var CustomError = require('custom-error-instance'); var inventory = require('./inventory'); var menu = require('./menu'); var OrderError = CustomError('OrderError'); module.exports = function() { var done = false; var factory = {}; var store = {}; /** * Add an item from the menu to the order. * @param {string} name The name of the menu item to add. */ factory.add = function(name) { var item = menu.get(name); if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' }); if (!item) throw new OrderError('Menu item does not exist: ' + name, { code: 'EDNE' }); if (!menu.available(name)) throw new OrderError('Insufficient inventory', { code: 'EINV' }); if (!store.hasOwnProperty(name)) store[name] = 0; store[name]++; item.ingredients.forEach(function(ingredient) { inventory.changeQuantity(ingredient.name, -1 * ingredient.quantity); }); return factory; }; factory.checkout = function() { done = true; console.log('Order complete. Income: $' + factory.cost()); }; factory.cost = function() { var total = 0; Object.keys(store).forEach(function(menuItemName) { var item = menu.get(menuItemName); if (item) { total += item.cost; } else { factory.remove(menuItemName); } }); return total; }; factory.remove = function(name) { var item; if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' }); if (!store.hasOwnProperty(name)) return; store[name]--; if (store[name] <= 0) delete store[name]; item = menu.get(name); item.ingredients.forEach(function(ingredient) { inventory.changeQuantity(ingredient.name, ingredient.quantity); }); return factory; }; return factory; };
const test = require('tape') const helpers = require('../test/helpers') const bindFunc = helpers.bindFunc const unary = require('./unary') test('unary helper', t => { const f = bindFunc(unary) const err = /unary: Argument must be a Function/ t.throws(f(undefined), err, 'throws with undefined') t.throws(f(null), err, 'throws with null') t.throws(f(0), err, 'throws with falsey number') t.throws(f(1), err, 'throws with truthy number') t.throws(f(''), err, 'throws with falsey string') t.throws(f('string'), err, 'throws with truthy string') t.throws(f(false), err, 'throws with false') t.throws(f(true), err, 'throws with true') t.throws(f({}), err, 'throws with object') t.throws(f([]), err, 'throws with array') const fn = unary((x, y, z) => ({ x: x, y: y, z: z })) t.same(fn(1, 2, 3), { x: 1, y: undefined, z: undefined }, 'only applies first argument to function') t.end() })
export const DEFAULTS = { API_BASE_URI: 'http://localhost:3000/axway', granularity: 'monthly', startDate: '2010-01-01', cacheExpirySeconds: 300//5 minutes }; export class Settings { /** * @param {string} setting * @returns {*} */ getSetting(setting) { return DEFAULTS[setting]; } /** * @param {string} customerNumber * @param {string} meterType * @returns {string} usageEndpoint */ getUsageEndpoint(customerNumber, meterType) { return `/v1/customers/${customerNumber}/usage/${meterType}`; } } export default new Settings;
'use strict'; var DB = require('./lib/database'); var rc_util = require('./lib/utility.js'); var modelsFactory = require('./lib/models.js'); var selective = require('./program').selective; var Promise = require('bluebird'); module.exports = function(dbUrl, commander, lastCrawl) { return new Promise(function(resolve, reject) { function useLatestCrawl(latestCrawl) { var ipps = rc_util.getIpps(latestCrawl); if (ipps) { selective(ipps, commander) .then(resolve) .catch(reject); } } if (lastCrawl) { useLatestCrawl(lastCrawl); } else { rc_util.getLatestRow(dbUrl, commander.logsql) .then(function(row) { useLatestCrawl(JSON.parse(row.data)); }) .catch(reject); } }); };
import {takeEvery} from 'redux-saga' import {call, put, take, fork, select, cancel} from 'redux-saga/effects' import * as Actions from './actions/actions' let ws = null const getUsername = state => state.username function* createWebSocket(url) { ws = new WebSocket(url) let deferred, open_deferred, close_deferred, error_deferred; ws.onopen = event => { if (open_deferred) { open_deferred.resolve(event) open_deferred = null } } ws.onmessage = event => { if (deferred) { deferred.resolve(JSON.parse(event.data)) deferred = null } } ws.onerror = event => { if (error_deferred) { error_deferred.resolve(JSON.parse(event.data)) error_deferred = null } } ws.onclose = event => { if (close_deferred) { close_deferred.resolve(event) close_deferred = null } } return { open: { nextMessage() { if (!open_deferred) { open_deferred = {} open_deferred.promise = new Promise(resolve => open_deferred.resolve = resolve) } return open_deferred.promise } }, message: { nextMessage() { if (!deferred) { deferred = {} deferred.promise = new Promise(resolve => deferred.resolve = resolve) } return deferred.promise } }, error: { nextMessage() { if (!error_deferred) { error_deferred = {} error_deferred.promise = new Promise(resolve => error_deferred.resolve = resolve) } return error_deferred.promise } }, close: { nextMessage() { if (!close_deferred) { close_deferred = {} close_deferred.promise = new Promise(resolve => close_deferred.resolve = resolve) } return close_deferred.promise } } } } function* watchOpen(ws) { let msg = yield call(ws.nextMessage) while (msg) { yield put(Actions.connected(msg.srcElement)) msg = yield call(ws.nextMessage) } } function* watchClose(ws) { let msg = yield call(ws.nextMessage) yield put(Actions.disconnected()) ws = null } function* watchErrors(ws) { let msg = yield call(ws.nextMessage) while (msg) { msg = yield call(ws.nextMessage) } } function* watchMessages(ws) { let msg = yield call(ws.nextMessage) while (msg) { yield put(msg) msg = yield call(ws.nextMessage) } } function* connect() { let openTask, msgTask, errTask, closeTask while (true) { const {ws_url} = yield take('connect') const ws = yield call(createWebSocket, ws_url) if (openTask) { yield cancel(openTask) yield cancel(msgTask) yield cancel(errTask) yield cancel(closeTask) } openTask = yield fork(watchOpen, ws.open) msgTask = yield fork(watchMessages, ws.message) errTask = yield fork(watchErrors, ws.error) closeTask = yield fork(watchClose, ws.close) } } const send = (data) => { try { ws.send(JSON.stringify(data)) } catch (error) { alert("Send error: " + error) } } function* login() { while (true) { const login_action = yield take('login') send(login_action) } } function* hello() { while (true) { const hello_action = yield take('hello') const username = yield select(getUsername) if (username) { send(Actions.login(username)) } } } function* disconnected() { while (true) { yield take('disconnected') } } export default function* rootSaga() { yield [ connect(), hello(), login(), disconnected() ] }
import React from 'react'; const isArray = x => Array.isArray(x); const isString = x => typeof x === 'string' && x.length > 0; const isSelector = x => isString(x) && (startsWith(x, '.') || startsWith(x, '#')); const isChildren = x => /string|number|boolean/.test(typeof x) || isArray(x); const startsWith = (string, start) => string.indexOf(start) === 0; const split = (string, separator) => string.split(separator); const subString = (string, start, end) => string.substring(start, end); const parseSelector = selector => { const classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; const parts = split(selector, classIdSplit); return parts.reduce((acc, part) => { if (startsWith(part, '#')) { acc.id = subString(part, 1); } else if (startsWith(part, '.')) { acc.className = `${acc.className} ${subString(part, 1)}`.trim(); } return acc; }, { className: '' }); }; const createElement = (nameOrType, properties = {}, children = []) => { if (properties.isRendered !== undefined && !properties.isRendered) { return null; } const { isRendered, ...props } = properties; const args = [nameOrType, props]; if (!isArray(children)) { args.push(children); } else { args.push(...children); } return React.createElement.apply(React, args); }; export const hh = nameOrType => (first, second, third) => { if (isSelector(first)) { const selector = parseSelector(first); // selector, children if (isChildren(second)) { return createElement(nameOrType, selector, second); } // selector, props, children let { className = '' } = second || {}; className = `${selector.className} ${className} `.trim(); const props = { ...second, ...selector, className }; if (isChildren(third)) { return createElement(nameOrType, props, third); } return createElement(nameOrType, props); } // children if (isChildren(first)) { return createElement(nameOrType, {}, first); } // props, children if (isChildren(second)) { return createElement(nameOrType, first, second); } return createElement(nameOrType, first); }; const h = (nameOrType, ...rest) => hh(nameOrType)(...rest); const TAG_NAMES = [ 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'video', 'wbr', 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan' ]; module.exports = TAG_NAMES.reduce((exported, type) => { exported[type] = hh(type); return exported; }, { h, hh });
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventEmitter = require('events').EventEmitter; function LHServer() { this.fnStack = []; this.defaultPort = 3000; this.options = {}; this.viewEngine = null; EventEmitter.call(this); } util.inherits(LHServer, EventEmitter); LHServer.prototype.use = function(path, options, fn) { if(typeof path === 'function') { fn = path; } if(typeof options === 'function') { fn = options; } if(!fn) return; var fnObj = { fn: fn, method: null, path: typeof path === 'string' ? path : null, options: typeof options === 'object' ? options : {}, } this.fnStack.push(fnObj); } LHServer.prototype.execute = function(req, res) { var self = this; var url_parts = url.parse(req.url); var callbackStack = this.getFunctionList(url_parts.pathname, req.method); if(callbackStack.length === 0) { return; } var func = callbackStack.shift(); // add session capabilities if(this.options['session']) { var session = sessions.lookupOrCreate(req,{ lifetime: this.options['session'].lifetime || 604800, secret: this.options['session'].secret || '', }); if(!res.finished) { res.setHeader('Set-Cookie', session.getSetCookieHeaderValue()); } req.session = session; } // add template rendering if(typeof this.options['view engine'] !== 'undefined') { res.render = render.bind(this,res); } res.statusCode = 200; res.send = send.bind(this,res); res.redirect = redirect.bind(this,res); res.status = status.bind(this,res); res.header = header.bind(this,res); try{ func.apply(this,[req,res, function(){self.callbackNextFunction(req,res,callbackStack)}]); } catch (e) { this.emit('error', e, res, req); } } LHServer.prototype.callbackNextFunction = function(req,res,callbackStack) { var self = this; if(callbackStack.length === 0) { return; } callbackStack[0] && callbackStack[0].apply && callbackStack[0].apply(this,[req,res,function() { callbackStack.shift(); self.callbackNextFunction(req,res,callbackStack) }]); } LHServer.prototype.listen = function(options, cb) { var opt = {}; if(typeof options === 'number' || typeof options === 'string'){ opt.port = options; } else { opt = Object.assign(opt,options) } var httpServer; if(opt.cert && opt.key) { httpServer = https.createServer(opt, this.execute.bind(this)).listen(opt.port || this.defaultPort); } else { httpServer = http.createServer(this.execute.bind(this)).listen(opt.port || this.defaultPort); } if(httpServer) { this.emit('ready'); }; cb && cb(httpServer); } LHServer.prototype.set = function(option, value) { this.options[option] = value; if(option === 'view engine' && value && value !== '') { try { this.viewEngine = require(value); } catch (err) { this.emit('error',err); } } } LHServer.prototype.getFunctionList = function(requestPath, method) { var ret = []; if(this.options['static']) { ret.push(readStaticFile.bind(this)); } for(var i in this.fnStack) { var pathMatch = ( this.fnStack[i].options && this.fnStack[i].options.partialPath ? this.fnStack[i].path === requestPath.substr(0, this.fnStack[i].path.length) : this.fnStack[i].path === requestPath ) || this.fnStack[i].path === null; if((this.fnStack[i].method === method || this.fnStack[i].method === null) && pathMatch) { if(this.fnStack[i].fn) { ret.push(this.fnStack[i].fn); } } } return ret; } LHServer.prototype.get = LHServer.prototype.post = LHServer.prototype.put = LHServer.prototype.delete = function() {}; var methods = ['get', 'put', 'post', 'delete',]; methods.map(function(method) { LHServer.prototype[method] = function(path, options, fn) { if(typeof path === 'function') { fn = path; } if(typeof options === 'function') { fn = options; } if(!fn) return; var fnObj = { fn: fn, method: method.toUpperCase(), path: typeof path === 'string' ? path : null, options: typeof options === 'object' ? options : {}, } this.fnStack.push(fnObj); } }) function readStaticFile(req,res,next) { if(res.finished){ return next && next(); } var self = this; var url_parts = url.parse(req.url); var requestPath = path.normalize(url_parts.pathname ).replace(/^(\.\.(\/|\\|$))+/, ''); if(requestPath === '/'){ requestPath = '/index.html' } var filePath = path.join(this.options['static'],requestPath); const contentTypes = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; var fExt = path.extname(filePath); var contentType; if(fExt && contentTypes.hasOwnProperty(fExt)) { contentType = contentTypes[fExt]; } else { return next && next(); } fs.readFile(filePath, function(err, content) { if (err) { return next && next(); } else { res.header('Content-Type', contentType); res.header('Content-Length', Buffer.byteLength(content)); res.writeHead( res.statusCode, res.headerValues ); res.end(content, 'utf-8'); return next && next(); } }); } function send(res, data) { if(res.finished){ return; } var contentType = 'text/html'; var responseBody = data; if(typeof data === 'object') { contentType = 'application/json' responseBody = JSON.stringify(data); } res.header('Content-Type', contentType) res.header('Content-Length', Buffer.byteLength(responseBody)) res.writeHead( res.statusCode, res.headerValues ); res.end(responseBody); } function render(res,template,options,callback){ if(res.finished){ return; } var self = this; if(typeof self.viewEngine === 'undefined') { return callback && callback(); } if(self.viewEngine.renderFile) { return self.viewEngine.renderFile( (self.options['views'] || '') + '/'+template+'.pug', options, function(err, result) { if(err){ self.emit('error',err); } if(result){ res.header('Content-Type', 'text/html') res.header('Content-Length', Buffer.byteLength(result)) res.writeHead( res.statusCode, res.headerValues ); res.end(result); } callback && callback(err,result); } ) } } function status(res,code) { res.statusCode = code; } function header(res, key, value) { if(typeof res.headerValues === 'undefined'){ res.headerValues = {}; } res.headerValues[key] = value } function redirect(res,url) { var address = url; var status = 302; if (arguments.length === 3) { if (typeof arguments[1] === 'number') { status = arguments[1]; address = arguments[2]; } } var responseBody = 'Redirecting to ' + address; res.header('Content-Type', 'text/html') res.header('Cache-Control', 'no-cache') res.header('Content-Length', Buffer.byteLength(responseBody)) res.header('Location', address) res.writeHead( status, res.headerValues ); res.end(responseBody); }; module.exports = new LHServer();
'use strict'; import path from 'path'; import webpack, { optimize, HotModuleReplacementPlugin, NoErrorsPlugin } from 'webpack'; export default { devtool: 'eval-cheap-module-source-map', entry: [ 'webpack-hot-middleware/client', './app/js/bootstrap' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new optimize.OccurenceOrderPlugin(), new HotModuleReplacementPlugin(), new NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: path.resolve(__dirname, 'node_modules'), include: [ path.resolve(__dirname) ] } ] } };
'use strict'; var expect = chai.expect; function run(scope,done) { done(); } describe('SendCtrl', function(){ var rootScope, scope, controller_injector, dependencies, ctrl, sendForm, network, timeout, spy, stub, mock, res, transaction, data; beforeEach(module("rp")); beforeEach(inject(function($rootScope, $controller, $q, $timeout, rpNetwork) { network = rpNetwork; rootScope = rootScope; timeout = $timeout; scope = $rootScope.$new(); scope.currencies_all = [{ name: 'XRP - Ripples', value: 'XRP'}]; controller_injector = $controller; // Stub the sendForm, which should perhaps be tested using // End To End tests scope.sendForm = { send_destination: { $setValidity: function(){} }, $setPristine: function(){}, $setValidity: function(){} }; scope.$apply = function(func){func()}; scope.saveAddressForm = { $setPristine: function () {} } scope.check_dt_visibility = function () {}; dependencies = { $scope: scope, $element: null, $network: network, rpId: { loginStatus: true, account: 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk' } } ctrl = controller_injector("SendCtrl", dependencies); })); it('should be initialized with defaults', function (done) { assert.equal(scope.mode, 'form'); assert.isObject(scope.send); assert.equal(scope.send.currency, 'XRP - Ripples'); assert.isFalse(scope.show_save_address_form); assert.isFalse(scope.addressSaved); assert.equal(scope.saveAddressName, ''); assert.isFalse(scope.addressSaving); done() }); it('should reset destination dependencies', function (done) { assert.isFunction(scope.reset_destination_deps); done(); }); describe('updating the destination', function (done) { beforeEach(function () { scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk'; }) it('should have a function to do so', function (done) { assert.isFunction(scope.update_destination); done(); }); describe('when the recipient is the same as last time', function (done) { beforeEach(function () { scope.send.last_recipient = scope.send.recipient_address; }); it('should not reset destination dependencies', function (done) { spy = sinon.spy(scope, 'reset_destination_deps'); scope.update_destination(); assert(spy.notCalled); done(); }); it('should not check destination tag visibility', function (done) { spy = sinon.spy(scope, 'check_dt_visibility'); scope.update_destination(); assert(spy.notCalled); done(); }); }); describe('when the recipient is new', function (done) { beforeEach(function () { scope.send.last_recipient = null; }); it('should reset destination dependencies', function (done) { spy = sinon.spy(scope, 'reset_destination_deps'); scope.update_destination(); assert(spy.called); done(); }); it('should check destination tag visibility', function (done) { spy = sinon.spy(scope, 'check_dt_visibility'); scope.update_destination(); assert(spy.called); done(); }); }); }) describe('updating the destination remote', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.update_destination_remote); done(); }); it('should validate the federation field by default', function (done) { var setValiditySpy = sinon.spy( scope.sendForm.send_destination, '$setValidity'); scope.update_destination_remote(); assert(setValiditySpy.withArgs('federation', true).called); done(); }) describe('when it is not bitcoin', function (done) { beforeEach(function () { scope.send.bitcoin = null }) it('should check destination', function (done) { var spy = sinon.spy(scope, 'check_destination'); scope.update_destination_remote(); assert(spy.calledOnce); done(); }); }); describe('when it is bitcoin', function (done) { beforeEach(function () { scope.send.bitcoin = true; }); it('should update currency constraints', function (done) { var spy = sinon.spy(scope, 'update_currency_constraints'); scope.update_destination_remote(); spy.should.have.been.calledOnce; done(); }); it('should not check destination', function (done) { var spy = sinon.spy(scope, 'check_destination'); scope.update_destination_remote(); assert(!spy.called); done(); }); }) }) it('should check the destination', function (done) { assert.isFunction(scope.check_destination); done(); }) it('should handle paths', function (done) { assert.isFunction(scope.handle_paths); done(); }); it('should update paths', function (done) { assert.isFunction(scope.update_paths); done(); }); describe('updating currency constraints', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.update_currency_constraints); done(); }); it('should update the currency', function (done) { stub = sinon.stub(scope, 'update_currency'); scope.update_currency_constraints(); assert(spy.called); done(); }); describe('when recipient info is not loaded', function () { it('should not update the currency', function (done) { stub = sinon.stub(scope, 'update_currency'); scope.send.recipient_info.loaded = false; scope.update_currency_constraints(); assert(spy.called); done(); }); }); }); it('should reset the currency dependencies', function (done) { assert.isFunction(scope.reset_currency_deps); var spy = sinon.spy(scope, 'reset_amount_deps'); scope.reset_currency_deps(); assert(spy.calledOnce); done(); }); it('should update the currency', function (done) { assert.isFunction(scope.update_currency); done(); }); describe('resetting the amount dependencies', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_amount_deps); done(); }); it('should set the quote to false', function (done) { scope.send.quote = true; scope.reset_amount_deps(); assert.isFalse(scope.send.quote); done(); }); it('should falsify the sender insufficient xrp flag', function (done) { scope.send.sender_insufficient_xrp = true; scope.reset_amount_deps(); assert.isFalse(scope.send.sender_insufficient_xrp); done(); }); it('should reset the paths', function (done) { spy = sinon.spy(scope, 'reset_paths'); scope.reset_amount_deps(); assert(spy.calledOnce); done(); }); }); it('should update the amount', function (done) { assert.isFunction(scope.update_amount); done(); }); it('should update the quote', function (done) { assert.isFunction(scope.update_quote); done(); }); describe('resetting paths', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_paths); done(); }); it('should set the send alternatives to an empty array', function (done) { scope.send.alternatives = ['not_an_empty_array']; scope.reset_paths(); assert(Array.isArray(scope.send.alternatives)); assert.equal(scope.send.alternatives.length, 0); done(); }); }); it('should rest the paths', function (done) { assert.isFunction(scope.reset_paths); done(); }); it('should cancel the form', function (done) { assert.isFunction(scope.cancelConfirm); scope.send.alt = ''; scope.mode = null; scope.cancelConfirm(); assert.equal(scope.mode, 'form'); assert.isNull(scope.send.alt); done(); }); describe('resetting the address form', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.resetAddressForm); done(); }); it('should falsify show_save_address_form field', function (done) { scope.show_save_address_form = true scope.resetAddressForm(); assert.isFalse(scope.show_save_address_form); done(); }); it('should falsify the addressSaved field', function (done) { scope.addressSaved = true; scope.resetAddressForm(); assert.isFalse(scope.addressSaved); done(); }); it('should falsify the addressSaving field', function (done) { scope.saveAddressName = null; scope.resetAddressForm(); assert.equal(scope.saveAddressName, ''); done(); }); it('should empty the saveAddressName field', function (done) { scope.addressSaving = true; scope.resetAddressForm(); assert.isFalse(scope.addressSaving); done(); }); it('should set the form to pristine state', function (done) { spy = sinon.spy(scope.saveAddressForm, '$setPristine'); scope.resetAddressForm(); assert(spy.calledOnce); done(); }); }); describe('performing reset goto', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_goto); done(); }); it('should reset the scope', function (done) { spy = sinon.spy(scope, 'reset'); scope.reset_goto(); assert(spy.calledOnce); done(); }); it('should navigate the page to the tabname provide', function (done) { var tabName = 'someAwesomeTab'; scope.reset_goto(tabName); assert.equal(document.location.hash, '#' + tabName); done(); }); }) it('should perform a reset goto', function (done) { var mock = sinon.mock(scope); mock.expects('reset').once(); scope.reset_goto(); mock.verify(); done(); }); describe("handling when the send is prepared", function () { it('should have a function to do so', function (done) { assert.isFunction(scope.send_prepared); done(); }); it('should set confirm wait to true', function (done) { scope.send_prepared(); assert.isTrue(scope.confirm_wait); done(); }); it("should set the mode to 'confirm'", function (done) { assert.notEqual(scope.mode, 'confirm'); scope.send_prepared(); assert.equal(scope.mode, 'confirm'); done(); }) it('should set confirm_wait to false after a timeout', function (done) { scope.send_prepared(); assert.isTrue(scope.confirm_wait); // For some reason $timeout.flush() works but then raises an exception try { timeout.flush() } catch (e) {} assert.isFalse(scope.confirm_wait); done(); }); }); describe('handling when a transaction send is confirmed', function (done) { beforeEach(function () { scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk'; }); describe("handling a 'propose' event from ripple-lib", function (done) { beforeEach(function () { scope.send = { amount_feedback: { currency: function () { function to_human () { return 'somestring'; } return { to_human: to_human } } } } transaction = { hash: 'E64165A4ED2BF36E5922B11C4E192DF068E2ADC21836087DE5E0B1FDDCC9D82F' } res = { engine_result: 'arbitrary_engine_result', engine_result_message: 'arbitrary_engine_result_message' } }); it('should call send with the transaction hash', function (done) { spy = sinon.spy(scope, 'sent'); scope.onTransactionProposed(res, transaction); assert(spy.calledWith(transaction.hash)); done(); }); it('should set the engine status with the response', function (done) { spy = sinon.spy(scope, 'setEngineStatus'); scope.onTransactionProposed(res, transaction); assert(spy.called); done(); }); }); describe("handling errors from the server", function () { describe("any error", function (done) { it('should set the mode to error', function (done) { var res = { error: null }; scope.onTransactionError(res, null); setTimeout(function (){ assert.equal(scope.mode, "error"); done(); }, 10) }); }); }); it('should have a function to handle send confirmed', function (done) { assert.isFunction(scope.send_confirmed); done(); }); it('should create a transaction', function (done) { spy = sinon.spy(network.remote, 'transaction'); scope.send_confirmed(); assert(spy.called); done(); }); }) describe('saving an address', function () { beforeEach(function () { scope.userBlob = { data: { contacts: [] } }; }); it('should have a function to do so', function (done) { assert.isFunction(scope.saveAddress); done(); }); it("should set the addressSaving property to true", function (done) { assert.isFalse(scope.addressSaving); scope.saveAddress(); assert.isTrue(scope.addressSaving); done(); }) it("should listen for blobSave event", function (done) { var onBlobSaveSpy = sinon.spy(scope, '$on'); scope.saveAddress(); assert(onBlobSaveSpy.withArgs('$blobSave').calledOnce); done(); }); it("should add the contact to the blob's contacts", function (done) { assert(scope.userBlob.data.contacts.length == 0); scope.saveAddress(); assert(scope.userBlob.data.contacts.length == 1); done(); }); describe('handling a blobSave event', function () { describe('having called saveAddress', function () { beforeEach(function () { scope.saveAddress(); }); it('should set addressSaved to true', function (done) { assert.isFalse(scope.addressSaved); scope.$emit('$blobSave'); assert.isTrue(scope.addressSaved); done(); }); it("should set the contact as the scope's contact", function (done) { assert.isUndefined(scope.contact); scope.$emit('$blobSave'); assert.isObject(scope.contact); done(); }); }) describe('without having called saveAddress', function () { it('should not set addressSaved', function (done) { assert.isFalse(scope.addressSaved); scope.$emit('$blobSave'); assert.isFalse(scope.addressSaved); done(); }); }) }) }); describe('setting engine status', function () { beforeEach(function () { res = { engine_result: 'arbitrary_engine_result', engine_result_message: 'arbitrary_engine_result_message' } }); describe("when the response code is 'tes'", function() { beforeEach(function () { res.engine_result = 'tes'; }) describe('when the transaction is accepted', function () { it("should set the transaction result to cleared", function (done) { var accepted = true; scope.setEngineStatus(res, accepted); assert.equal(scope.tx_result, 'cleared'); done(); }); }); describe('when the transaction not accepted', function () { it("should set the transaction result to pending", function (done) { var accepted = false; scope.setEngineStatus(res, accepted); assert.equal(scope.tx_result, 'pending'); done(); }); }); }); describe("when the response code is 'tep'", function() { beforeEach(function () { res.engine_result = 'tep'; }) it("should set the transaction result to partial", function (done) { scope.setEngineStatus(res, true); assert.equal(scope.tx_result, 'partial'); done(); }); }); }); describe('handling sent transactions', function () { it('should update the mode to status', function (done) { assert.isFunction(scope.sent); assert.equal(scope.mode, 'form'); scope.sent(); assert.equal(scope.mode, 'status'); done(); }) it('should listen for transactions on the network', function (done) { var remoteListenerSpy = sinon.spy(network.remote, 'on'); scope.sent(); assert(remoteListenerSpy.calledWith('transaction')); done(); }) describe('handling a transaction event', function () { beforeEach(function () { var hash = 'testhash'; scope.sent(hash); data = { transaction: { hash: hash } } stub = sinon.stub(scope, 'setEngineStatus'); }); afterEach(function () { scope.setEngineStatus.restore(); }) it('should set the engine status', function (done) { network.remote.emit('transaction', data); assert(stub.called); done(); }); it('should stop listening for transactions', function (done) { spy = sinon.spy(network.remote, 'removeListener'); network.remote.emit('transaction', data); assert(spy.called); done(); }) }) }) });
"use strict"; (function (ConflictType) { ConflictType[ConflictType["IndividualAttendeeConflict"] = 0] = "IndividualAttendeeConflict"; ConflictType[ConflictType["GroupConflict"] = 1] = "GroupConflict"; ConflictType[ConflictType["GroupTooBigConflict"] = 2] = "GroupTooBigConflict"; ConflictType[ConflictType["UnknownAttendeeConflict"] = 3] = "UnknownAttendeeConflict"; })(exports.ConflictType || (exports.ConflictType = {})); var ConflictType = exports.ConflictType;
export default function applyLocationOffset(rect, location, isOffsetBody) { var top = rect.top; var left = rect.left; if (isOffsetBody) { left = 0; top = 0; } return { top: top + location.top, left: left + location.left, height: rect.height, width: rect.width }; } //# sourceMappingURL=apply-location-offset.js.map
KB.component('task-move-position', function (containerElement, options) { function getSelectedValue(id) { var element = KB.dom(document).find('#' + id); if (element) { return parseInt(element.options[element.selectedIndex].value); } return null; } function getSwimlaneId() { var swimlaneId = getSelectedValue('form-swimlanes'); return swimlaneId === null ? options.board[0].id : swimlaneId; } function getColumnId() { var columnId = getSelectedValue('form-columns'); return columnId === null ? options.board[0].columns[0].id : columnId; } function getPosition() { var position = getSelectedValue('form-position'); return position === null ? 1 : position; } function getPositionChoice() { var element = KB.find('input[name=positionChoice]:checked'); if (element) { return element.value; } return 'before'; } function onSwimlaneChanged() { var columnSelect = KB.dom(document).find('#form-columns'); KB.dom(columnSelect).replace(buildColumnSelect()); var taskSection = KB.dom(document).find('#form-tasks'); KB.dom(taskSection).replace(buildTasks()); } function onColumnChanged() { var taskSection = KB.dom(document).find('#form-tasks'); KB.dom(taskSection).replace(buildTasks()); } function onError(message) { KB.trigger('modal.stop'); KB.find('#message-container') .replace(KB.dom('div') .attr('id', 'message-container') .attr('class', 'alert alert-error') .text(message) .build() ); } function onSubmit() { var position = getPosition(); var positionChoice = getPositionChoice(); if (positionChoice === 'after') { position++; } KB.find('#message-container').replace(KB.dom('div').attr('id', 'message-container').build()); KB.http.postJson(options.saveUrl, { "column_id": getColumnId(), "swimlane_id": getSwimlaneId(), "position": position }).success(function () { window.location.reload(true); }).error(function (response) { if (response) { onError(response.message); } }); } function buildSwimlaneSelect() { var swimlanes = []; options.board.forEach(function(swimlane) { swimlanes.push({'value': swimlane.id, 'text': swimlane.name}); }); return KB.dom('select') .attr('id', 'form-swimlanes') .change(onSwimlaneChanged) .for('option', swimlanes) .build(); } function buildColumnSelect() { var columns = []; var swimlaneId = getSwimlaneId(); options.board.forEach(function(swimlane) { if (swimlaneId === swimlane.id) { swimlane.columns.forEach(function(column) { columns.push({'value': column.id, 'text': column.title}); }); } }); return KB.dom('select') .attr('id', 'form-columns') .change(onColumnChanged) .for('option', columns) .build(); } function buildTasks() { var tasks = []; var swimlaneId = getSwimlaneId(); var columnId = getColumnId(); var container = KB.dom('div').attr('id', 'form-tasks'); options.board.forEach(function (swimlane) { if (swimlaneId === swimlane.id) { swimlane.columns.forEach(function (column) { if (columnId === column.id) { column.tasks.forEach(function (task) { tasks.push({'value': task.position, 'text': '#' + task.id + ' - ' + task.title}); }); } }); } }); if (tasks.length > 0) { container .add(KB.html.label(options.positionLabel, 'form-position')) .add(KB.dom('select').attr('id', 'form-position').for('option', tasks).build()) .add(KB.html.radio(options.beforeLabel, 'positionChoice', 'before')) .add(KB.html.radio(options.afterLabel, 'positionChoice', 'after')) ; } return container.build(); } this.render = function () { KB.on('modal.submit', onSubmit); var form = KB.dom('div') .on('submit', onSubmit) .add(KB.dom('div').attr('id', 'message-container').build()) .add(KB.html.label(options.swimlaneLabel, 'form-swimlanes')) .add(buildSwimlaneSelect()) .add(KB.html.label(options.columnLabel, 'form-columns')) .add(buildColumnSelect()) .add(buildTasks()) .build(); containerElement.appendChild(form); }; });
const AES = require('./aesjs'); function encrypt(text, key) { key = new TextEncoder().encode(key); const textBytes = AES.utils.utf8.toBytes(text); const aesCtr = new AES.ModeOfOperation.ctr(key); const encryptedBytes = aesCtr.encrypt(textBytes); return AES.utils.hex.fromBytes(encryptedBytes); } function decrypt(encryptedHex, key) { key = new TextEncoder().encode(key); const encryptedBytes = AES.utils.hex.toBytes(encryptedHex); const aesCtr = new AES.ModeOfOperation.ctr(key); const decryptedBytes = aesCtr.decrypt(encryptedBytes); return AES.utils.utf8.fromBytes(decryptedBytes); } module.exports = { encrypt, decrypt, };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _index = require('../../isSameWeek/index.js'); var _index2 = _interopRequireDefault(_index); var _index3 = require('../_lib/convertToFP/index.js'); var _index4 = _interopRequireDefault(_index3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. var isSameWeekWithOptions = (0, _index4.default)(_index2.default, 3); exports.default = isSameWeekWithOptions; module.exports = exports['default'];
angular.module('EggApp', ['ngRoute'], function($routeProvider) { $routeProvider .when('/', { templateUrl: '/app/view/search.html', controller: 'SearchController' }) .when('/show/:id', { templateUrl: '/app/view/show.html', controller: 'ShowController' }) .otherwise({ redirectTo: '/' }); });
var Phaser = require('phaser-unofficial'); /** * Wall class. * @param {object} game * @param {number} x * @param {number} y */ Wall = function (game, x, y) { Phaser.Sprite.call(this, game, x, y, 'paddle'); this.game.physics.arcade.enable(this); this.width = 200; this.height = this.game.world.bounds.height; this.blendMode = Phaser.blendModes.ADD; this.body.bounce.setTo(1, 1); this.body.immovable = true; this.alpha = 0; }; Wall.prototype = Object.create(Phaser.Sprite.prototype); Wall.prototype.constructor = Wall; module.exports = Wall;
exports.definition = { /** * Add custom methods to your Model`s Records * just define a function: * ```js * this.function_name = function(){ * //this == Record * }; * ``` * This will automatically add the new method to your Record * * @class Definition * @name Custom Record Methods * */ mixinCallback: function() { var objKeys = [] var self = this this.use(function() { // get all current property names objKeys = Object.keys(this) }, 90) this.on('finished', function() { // an now search for new ones ==> instance methods for our new model class Object.keys(self).forEach(function(name) { if (objKeys.indexOf(name) === -1) { self.instanceMethods[name] = self[name] delete self[name] } }) }) } }
/* ---------------------------------- * PUSH v2.0.0 * Licensed under The MIT License * inspired by chris's jquery.pjax.js * http://opensource.org/licenses/MIT * ---------------------------------- */ !function () { var noop = function () {}; // Pushstate cacheing // ================== var isScrolling; var maxCacheLength = 20; var cacheMapping = sessionStorage; var domCache = {}; var transitionMap = { 'slide-in' : 'slide-out', 'slide-out' : 'slide-in', 'fade' : 'fade' }; var bars = { bartab : '.bar-tab', barnav : '.bar-nav', barfooter : '.bar-footer', barheadersecondary : '.bar-header-secondary' }; var cacheReplace = function (data, updates) { PUSH.id = data.id; if (updates) data = getCached(data.id); cacheMapping[data.id] = JSON.stringify(data); window.history.replaceState(data.id, data.title, data.url); domCache[data.id] = document.body.cloneNode(true); }; var cachePush = function () { var id = PUSH.id; var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]'); var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]'); cacheBackStack.push(id); while (cacheForwardStack.length) delete cacheMapping[cacheForwardStack.shift()]; while (cacheBackStack.length > maxCacheLength) delete cacheMapping[cacheBackStack.shift()]; window.history.pushState(null, '', cacheMapping[PUSH.id].url); cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack); cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack); }; var cachePop = function (id, direction) { var forward = direction == 'forward'; var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]'); var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]'); var pushStack = forward ? cacheBackStack : cacheForwardStack; var popStack = forward ? cacheForwardStack : cacheBackStack; if (PUSH.id) pushStack.push(PUSH.id); popStack.pop(); cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack); cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack); }; var getCached = function (id) { return JSON.parse(cacheMapping[id] || null) || {}; }; var getTarget = function (e) { var target = findTarget(e.target); if ( ! target || e.which > 1 || e.metaKey || e.ctrlKey || isScrolling || location.protocol !== target.protocol || location.host !== target.host || !target.hash && /#/.test(target.href) || target.hash && target.href.replace(target.hash, '') === location.href.replace(location.hash, '') || target.getAttribute('data-ignore') == 'push' ) return; return target; }; // Main event handlers (touchend, popstate) // ========================================== var touchend = function (e) { var target = getTarget(e); if (!target) return; e.preventDefault(); PUSH({ url : target.href, hash : target.hash, timeout : target.getAttribute('data-timeout'), transition : target.getAttribute('data-transition') }); }; var popstate = function (e) { var key; var barElement; var activeObj; var activeDom; var direction; var transition; var transitionFrom; var transitionFromObj; var id = e.state; if (!id || !cacheMapping[id]) return; direction = PUSH.id < id ? 'forward' : 'back'; cachePop(id, direction); activeObj = getCached(id); activeDom = domCache[id]; if (activeObj.title) document.title = activeObj.title; if (direction == 'back') { transitionFrom = JSON.parse(direction == 'back' ? cacheMapping.cacheForwardStack : cacheMapping.cacheBackStack); transitionFromObj = getCached(transitionFrom[transitionFrom.length - 1]); } else { transitionFromObj = activeObj; } if (direction == 'back' && !transitionFromObj.id) return PUSH.id = id; transition = direction == 'back' ? transitionMap[transitionFromObj.transition] : transitionFromObj.transition; if (!activeDom) { return PUSH({ id : activeObj.id, url : activeObj.url, title : activeObj.title, timeout : activeObj.timeout, transition : transition, ignorePush : true }); } if (transitionFromObj.transition) { activeObj = extendWithDom(activeObj, '.content', activeDom.cloneNode(true)); for (key in bars) { barElement = document.querySelector(bars[key]) if (activeObj[key]) swapContent(activeObj[key], barElement); else if (barElement) barElement.parentNode.removeChild(barElement); } } swapContent( (activeObj.contents || activeDom).cloneNode(true), document.querySelector('.content'), transition ); PUSH.id = id; document.body.offsetHeight; // force reflow to prevent scroll }; // Core PUSH functionality // ======================= var PUSH = function (options) { var key; var data = {}; var xhr = PUSH.xhr; options.container = options.container || options.transition ? document.querySelector('.content') : document.body; for (key in bars) { options[key] = options[key] || document.querySelector(bars[key]); } if (xhr && xhr.readyState < 4) { xhr.onreadystatechange = noop; xhr.abort() } xhr = new XMLHttpRequest(); xhr.open('GET', options.url, true); xhr.setRequestHeader('X-PUSH', 'true'); xhr.onreadystatechange = function () { if (options._timeout) clearTimeout(options._timeout); if (xhr.readyState == 4) xhr.status == 200 ? success(xhr, options) : failure(options.url); }; if (!PUSH.id) { cacheReplace({ id : +new Date, url : window.location.href, title : document.title, timeout : options.timeout, transition : null }); } if (options.timeout) { options._timeout = setTimeout(function () { xhr.abort('timeout'); }, options.timeout); } xhr.send(); if (xhr.readyState && !options.ignorePush) cachePush(); }; // Main XHR handlers // ================= var success = function (xhr, options) { var key; var barElement; var data = parseXHR(xhr, options); if (!data.contents) return locationReplace(options.url); if (data.title) document.title = data.title; if (options.transition) { for (key in bars) { barElement = document.querySelector(bars[key]) if (data[key]) swapContent(data[key], barElement); else if (barElement) barElement.parentNode.removeChild(barElement); } } swapContent(data.contents, options.container, options.transition, function () { cacheReplace({ id : options.id || +new Date, url : data.url, title : data.title, timeout : options.timeout, transition : options.transition }, options.id); triggerStateChange(); }); if (!options.ignorePush && window._gaq) _gaq.push(['_trackPageview']) // google analytics if (!options.hash) return; }; var failure = function (url) { throw new Error('Could not get: ' + url) }; // PUSH helpers // ============ var swapContent = function (swap, container, transition, complete) { var enter; var containerDirection; var swapDirection; if (!transition) { if (container) container.innerHTML = swap.innerHTML; else if (swap.classList.contains('content')) document.body.appendChild(swap); else document.body.insertBefore(swap, document.querySelector('.content')); } else { enter = /in$/.test(transition); if (transition == 'fade') { container.classList.add('in'); container.classList.add('fade'); swap.classList.add('fade'); } if (/slide/.test(transition)) { swap.classList.add('sliding-in', enter ? 'right' : 'left'); swap.classList.add('sliding'); container.classList.add('sliding'); } container.parentNode.insertBefore(swap, container); } if (!transition) complete && complete(); if (transition == 'fade') { container.offsetWidth; // force reflow container.classList.remove('in'); container.addEventListener('webkitTransitionEnd', fadeContainerEnd); function fadeContainerEnd() { container.removeEventListener('webkitTransitionEnd', fadeContainerEnd); swap.classList.add('in'); swap.addEventListener('webkitTransitionEnd', fadeSwapEnd); } function fadeSwapEnd () { swap.removeEventListener('webkitTransitionEnd', fadeSwapEnd); container.parentNode.removeChild(container); swap.classList.remove('fade'); swap.classList.remove('in'); complete && complete(); } } if (/slide/.test(transition)) { container.offsetWidth; // force reflow swapDirection = enter ? 'right' : 'left' containerDirection = enter ? 'left' : 'right' container.classList.add(containerDirection); swap.classList.remove(swapDirection); swap.addEventListener('webkitTransitionEnd', slideEnd); function slideEnd() { swap.removeEventListener('webkitTransitionEnd', slideEnd); swap.classList.remove('sliding', 'sliding-in'); swap.classList.remove(swapDirection); container.parentNode.removeChild(container); complete && complete(); } } }; var triggerStateChange = function () { var e = new CustomEvent('push', { detail: { state: getCached(PUSH.id) }, bubbles: true, cancelable: true }); window.dispatchEvent(e); }; var findTarget = function (target) { var i, toggles = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = toggles.length; i--;) { if (toggles[i] === target) return target; } } }; var locationReplace = function (url) { window.history.replaceState(null, '', '#'); window.location.replace(url); }; var parseURL = function (url) { var a = document.createElement('a'); a.href = url; return a; }; var extendWithDom = function (obj, fragment, dom) { var i; var result = {}; for (i in obj) result[i] = obj[i]; Object.keys(bars).forEach(function (key) { var el = dom.querySelector(bars[key]); if (el) el.parentNode.removeChild(el); result[key] = el; }); result.contents = dom.querySelector(fragment); return result; }; var parseXHR = function (xhr, options) { var head; var body; var data = {}; var responseText = xhr.responseText; data.url = options.url; if (!responseText) return data; if (/<html/i.test(responseText)) { head = document.createElement('div'); body = document.createElement('div'); head.innerHTML = responseText.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0] body.innerHTML = responseText.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0] } else { head = body = document.createElement('div'); head.innerHTML = responseText; } data.title = head.querySelector('title'); data.title = data.title && data.title.innerText.trim(); if (options.transition) data = extendWithDom(data, '.content', body); else data.contents = body; return data; }; // Attach PUSH event handlers // ========================== window.addEventListener('touchstart', function () { isScrolling = false; }); window.addEventListener('touchmove', function () { isScrolling = true; }) window.addEventListener('touchend', touchend); window.addEventListener('click', function (e) { if (getTarget(e)) e.preventDefault(); }); window.addEventListener('popstate', popstate); window.PUSH = PUSH; }();
/***************************************************** * Copyright (c) 2014 Colby Brown * * This program is released under the MIT license. * * For more information about the MIT license, * * visit http://opensource.org/licenses/MIT * *****************************************************/ var app = angular.module('volunteer', [ 'ajoslin.promise-tracker', 'cn.offCanvas', 'ncy-angular-breadcrumb', 'ngCookies', 'ui.bootstrap', 'ui.router', 'accentbows.controller', 'alerts.controller', 'bears.controller', 'configure.controller', 'confirm.controller', 'home.volunteer.controller', 'letters.controller', 'mums.volunteer.controller', 'mumtypes.controller', 'accessoriesAdd.controller', 'accessoriesAll.controller', 'accessoriesEdit.controller', 'accentbows.service', 'alerts.service', 'bears.service', 'confirm.service', 'letters.service', 'mum.service', 'mumtypes.service', 'pay.service', 'accessories.service', 'volunteer.service']); app.config(function($stateProvider, $urlRouterProvider, $httpProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', templateUrl: 'public/views/volunteer/home/index.html', controller: 'homeController' }) .state('home.logout', { url: '/logout', onEnter: function($cookieStore, $rootScope, $state) { $cookieStore.remove('volunteerToken'); $rootScope.updateHeader(); $state.go('home'); } }) .state('configure', { url: '/configure', templateUrl: 'public/views/volunteer/configure/index.html', controller: 'configureController' }) .state('configure.accentbows', { url: '/accentbows', templateUrl: 'public/views/volunteer/accentbows/index.html', controller: 'accentbowsController' }) .state('configure.bears', { url: '/bears', templateUrl: 'public/views/volunteer/bears/index.html', controller: 'bearsController' }) .state('configure.letters', { url: '/letters', templateUrl: 'public/views/volunteer/letters/index.html', controller: 'lettersController' }) .state('configure.volunteers', { url: '/volunteers', templateUrl: 'public/views/volunteer/configure/volunteers.html', controller: 'configureVolunteerController' }) .state('configure.yearly', { url: '/yearly', templateUrl: 'public/views/volunteer/configure/yearly.html', controller: 'configureYearlyController' }) .state('mums', { url: '/mums', templateUrl: 'public/views/volunteer/mums/index.html', controller: 'mumsController', abstract: true }) .state('mums.all', { url: '', templateUrl: 'public/views/volunteer/mums/all.html', controller: 'mumsAllController' }) .state('mums.view', { url: '/view/:mumId', templateUrl: 'public/views/volunteer/mums/view.html', controller: 'mumsViewController' }) .state('configure.mumtypes', { url: '/mumtypes', templateUrl: 'public/views/volunteer/mumtypes/index.html', controller: 'mumtypesController', abstract: true }) .state('configure.mumtypes.grade', { url: '', templateUrl: 'public/views/volunteer/mumtypes/grade.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function(MumtypesService) { return { formController: 'mumtypesEditGradeController', service: MumtypesService.grades, fetch: [] }; } } }) .state('configure.mumtypes.product', { url: '/:gradeId', templateUrl: 'public/views/volunteer/mumtypes/product.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditProductController', service: MumtypesService.products, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); } ] }; } } }) .state('configure.mumtypes.size', { url: '/:gradeId/:productId', templateUrl: 'public/views/volunteer/mumtypes/size.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditSizeController', service: MumtypesService.sizes, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); }, function($scope) { return MumtypesService.products.fetch($stateParams.productId) .success(function(data) { $scope.product = data; }); } ] }; } } }) .state('configure.mumtypes.backing', { url: '/:gradeId/:productId/:sizeId', templateUrl: 'public/views/volunteer/mumtypes/backing.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditBackingController', service: MumtypesService.backings, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); }, function($scope) { return MumtypesService.products.fetch($stateParams.productId) .success(function(data) { $scope.product = data; }); }, function($scope) { return MumtypesService.sizes.fetch($stateParams.sizeId) .success(function(data) { $scope.size = data; }); } ] } } } }) .state('configure.accessories', { url: '/accessories', template: '<ui-view />', abstract: true }) .state('configure.accessories.all', { url: '', templateUrl: 'public/views/volunteer/accessories/all.html', controller: 'accessoriesAllController' }) .state('configure.accessories.add', { url: '/add', templateUrl: 'public/views/volunteer/accessories/edit.html', controller: 'accessoriesAddController' }) .state('configure.accessories.edit', { url: '/edit/:accessoryId', templateUrl: 'public/views/volunteer/accessories/edit.html', controller: 'accessoriesEditController' }); $httpProvider.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'}; $httpProvider.defaults.headers.put = {'Content-Type': 'application/x-www-form-urlencoded'}; //PHP does not play nice with this feature. It's no big deal. //$locationProvider.html5Mode(true); }); app.run(['$cookieStore', '$injector', function($cookieStore, $injector) { $injector.get("$http").defaults.transformRequest.unshift(function(data, headersGetter) { var token = $cookieStore.get('volunteerToken'); if (token) { headersGetter()['Authentication'] = token.jwt; } if (data === undefined) { return data; } // If this is not an object, defer to native stringification. if ( ! angular.isObject( data ) ) { return( ( data == null ) ? "" : data.toString() ); } var buffer = []; // Serialize each key in the object. for ( var name in data ) { if ( ! data.hasOwnProperty( name ) ) { continue; } var value = data[ name ]; buffer.push( encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value ) ); } // Serialize the buffer and clean it up for transportation. var source = buffer.join( "&" ).replace( /%20/g, "+" ); return( source ); }); }]); app.controller('headerController', function($rootScope, $cookieStore) { $rootScope.updateHeader = function() { $rootScope.volunteer = $cookieStore.get('volunteerToken'); }; $rootScope.updateHeader(); }); //This filter is used to convert MySQL datetimes into AngularJS a readable ISO format. app.filter('dateToISO', function() { return function(badTime) { if (!badTime) return ""; if (badTime.date) { return badTime.date.replace(/(.+) (.+)/, "$1T$2Z"); } else { return badTime.replace(/(.+) (.+)/, "$1T$2Z"); } }; });
import { exec, getById } from "../database/database"; import Gender from "../entities/gender"; export default class GenderController { constructor() {} static getById(id, as_object = true) { let gender = null; let results = getById(id, ` SELECT t1.id, t1.identifier as name FROM genders as t1 `); if(results) { gender = (as_object) ? new Gender(results) : results; } console.log(results); return gender; } }
'use strict'; var format = require('util').format , scripts = require('./scripts') , loadScriptSource = require('./load-script-source') // Ports: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp function ignore(cb) { cb() } function InspectorDebuggerAgent() { if (!(this instanceof InspectorDebuggerAgent)) return new InspectorDebuggerAgent(); this._enabled = false; this._breakpointsCookie = {} } module.exports = InspectorDebuggerAgent; var proto = InspectorDebuggerAgent.prototype; proto.enable = function enable(cb) { this._enabled = true; cb() } proto.disable = function disable(cb) { this._enabled = false; cb() } // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=606 proto._resolveBreakpoint = function _resolveBreakpoint(breakpointId, script, breakpoint, cb) { var result = { breakpointId: breakpointId, locations: [ ] }; // if a breakpoint registers on startup, the script's source may not have been loaded yet // in that case we load it, the script's source is set automatically during that step // should not be needed once other debugger methods are implemented if (script.source) onensuredSource(); else loadScriptSource(script.url, onensuredSource) function onensuredSource(err) { if (err) return cb(err); if (breakpoint.lineNumber < script.startLine || script.endLine < breakpoint.lineNumber) return cb(null, result); // TODO: scriptDebugServer().setBreakpoint(scriptId, breakpoint, &actualLineNumber, &actualColumnNumber, false); // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/bindings/core/v8/ScriptDebugServer.cpp&l=89 var debugServerBreakpointId = 'TBD' if (!debugServerBreakpointId) return cb(null, result); // will be returned from call to script debug server var actualLineNumber = breakpoint.lineNumber , actualColumnNumber = breakpoint.columnNumber result.locations.push({ scriptId : script.id , lineNumber : actualLineNumber , columnNumber : actualColumnNumber }) cb(null, result); } } // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=333 proto.setBreakpointByUrl = function setBreakpointByUrl(opts, cb) { if (opts.urlRegex) return cb(new Error('Not supporting setBreakpointByUrl with urlRegex')); var isAntibreakpoint = !!opts.isAntibreakpoint , url = opts.url , condition = opts.condition || '' , lineNumber = opts.lineNumber , columnNumber if (typeof opts.columnNumber === Number) { columnNumber = opts.columnNumber; if (columnNumber < 0) return cb(new Error('Incorrect column number.')); } else { columnNumber = isAntibreakpoint ? -1 : 0; } var breakpointId = format('%s:%d:%d', url, lineNumber, columnNumber); if (this._breakpointsCookie[breakpointId]) return cb(new Error('Breakpoint at specified location already exists.')); this._breakpointsCookie[breakpointId] = { url : url , lineNumber : lineNumber , columnNumber : columnNumber , condition : condition , isAntibreakpoint : isAntibreakpoint } if (isAntibreakpoint) return cb(null, { breakpointId: breakpointId }); var match = scripts.byUrl[url]; if (!match) return cb(null, { breakpointId: breakpointId, locations: [] }) var breakpoint = { lineNumber: lineNumber, columnNumber: columnNumber, condition: condition } this._resolveBreakpoint(breakpointId, match, breakpoint, cb) } proto._removeBreakpoint = function _removeBreakpoint(breakpointId, cb) { // todo cb() } // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=416 proto.removeBreakpoint = function removeBreakpoint(breakpointId, cb) { var breakpoint = this._breakpointsCookie[breakpointId]; if (!breakpoint) return; this._breakpointsCookie[breakpointId] = undefined; if (!breakpoint.isAntibreakpoint) this._removeBreakpoint(breakpointId, cb); else cb() } proto.getScriptSource = function getScriptSource(id, cb) { var script = scripts.byId[id]; if (!script) return cb(new Error('Script with id ' + id + 'was not found')) cb(null, { scriptSource: script.source }) } proto.setBreakpointsActive = ignore proto.setSkipAllPauses = ignore proto.setBreakpoint = ignore proto.continueToLocation = ignore proto.stepOver = ignore proto.stepInto = ignore proto.stepOut = ignore proto.pause = ignore proto.resume = ignore proto.searchInContent = ignore proto.canSetScriptSource = ignore proto.setScriptSource = ignore proto.restartFrame = ignore proto.getFunctionDetails = ignore proto.getCollectionEntries = ignore proto.setPauseOnExceptions = ignore proto.evaluateOnCallFrame = ignore proto.compileScript = ignore proto.runScript = ignore proto.setOverlayMessage = ignore proto.setVariableValue = ignore proto.getStepInPositions = ignore proto.getBacktrace = ignore proto.skipStackFrames = ignore proto.setAsyncCallStackDepth = ignore proto.enablePromiseTracker = ignore proto.disablePromiseTracker = ignore proto.getPromises = ignore proto.getPromiseById = ignore
/* eslint no-console: 0 */ 'use strict'; const fs = require('fs'); const mkdirp = require('mkdirp'); const rollup = require('rollup'); const nodeResolve = require('rollup-plugin-node-resolve'); const commonjs = require('rollup-plugin-commonjs'); const uglify = require('rollup-plugin-uglify'); const src = 'src'; const dest = 'dist/rollup-aot'; Promise.all([ // build main/app rollup.rollup({ entry: `${src}/main-aot.js`, context: 'this', plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify({ output: { comments: /@preserve|@license|@cc_on/i, }, mangle: { keep_fnames: true, }, compress: { warnings: false, }, }), ], }).then(app => app.write({ format: 'iife', dest: `${dest}/app.js`, sourceMap: false, }) ), // build polyfills rollup.rollup({ entry: `${src}/polyfills-aot.js`, context: 'this', plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify(), ], }).then(app => app.write({ format: 'iife', dest: `${dest}/polyfills.js`, sourceMap: false, }) ), // create index.html new Promise((resolve, reject) => { fs.readFile(`${src}/index.html`, 'utf-8', (readErr, indexHtml) => { if (readErr) return reject(readErr); const newIndexHtml = indexHtml .replace('</head>', '<script src="polyfills.js"></script></head>') .replace('</body>', '<script src="app.js"></script></body>'); mkdirp(dest, mkdirpErr => { if (mkdirpErr) return reject(mkdirpErr); return true; }); return fs.writeFile( `${dest}/index.html`, newIndexHtml, 'utf-8', writeErr => { if (writeErr) return reject(writeErr); console.log('Created index.html'); return resolve(); } ); }); }), ]).then(() => { console.log('Rollup complete'); }).catch(err => { console.error('Rollup failed with ', err); });
function checkHeadersSent(res, cb) { return (err, results) => { if (res.headersSent) { if (err) { return cb(err) } return null } cb(err, results) } } exports.finish = function finish(req, res, next) { const check = checkHeadersSent.bind(null, res) if (req.method === 'GET') { return check((err, results) => { if (err) { return next(err) // Send to default handler } res.json(results) }) } else if (req.method === 'POST') { return check((err, results) => { if (err) { return next(err) // Send to default handler } /* eslint-disable max-len */ // http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api?hn#useful-post-responses if (results) { res.json(results, 200) } else { res.json(204, {}) } }) } else if (req.method === 'PUT') { return check((err, results) => { if (err) { return next(err) // Send to default handler } if (results) { res.json(results, 200) } else { res.json(204, {}) } }) } else if (req.method === 'PATCH') { return check((err, results) => { if (err) { return next(err) // Send to default handler } if (results) { res.json(results) } else { res.json(204, {}) } }) } else if (req.method === 'DELETE') { return check((err, results) => { if (err) { return next(err) // Send to default handler } if (results) { res.json(results) } else { res.json(204, {}) } }) } }
var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); var testCase = require('../deps/nodeunit').testCase, debug = require('util').debug, inspect = require('util').inspect, nodeunit = require('../deps/nodeunit'), gleak = require('../tools/gleak'), Db = mongodb.Db, Cursor = mongodb.Cursor, Script = require('vm'), Collection = mongodb.Collection, Server = mongodb.Server, Step = require("../deps/step/lib/step"), ServerManager = require('./tools/server_manager').ServerManager; var MONGODB = 'integration_tests'; var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); /** * Module for parsing an ISO 8601 formatted string into a Date object. */ var ISODate = function (string) { var match; if (typeof string.getTime === "function") return string; else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { var date = new Date(); date.setUTCFullYear(Number(match[1])); date.setUTCMonth(Number(match[3]) - 1 || 0); date.setUTCDate(Number(match[5]) || 0); date.setUTCHours(Number(match[7]) || 0); date.setUTCMinutes(Number(match[8]) || 0); date.setUTCSeconds(Number(match[10]) || 0); date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); if (match[13] && match[13] !== "Z") { var h = Number(match[16]) || 0, m = Number(match[17]) || 0; h *= 3600000; m *= 60000; var offset = h + m; if (match[15] == "+") offset = -offset; new Date(date.valueOf() + offset); } return date; } else throw new Error("Invalid ISO 8601 date given.", __filename); }; // Define the tests, we want them to run as a nested test so we only clean up the // db connection once var tests = testCase({ setUp: function(callback) { client.open(function(err, db_p) { if(numberOfTestsRun == Object.keys(tests).length) { // If first test drop the db client.dropDatabase(function(err, done) { callback(); }); } else { return callback(); } }); }, tearDown: function(callback) { numberOfTestsRun = numberOfTestsRun - 1; // Drop the database and close it if(numberOfTestsRun <= 0) { // client.dropDatabase(function(err, done) { // Close the client client.close(); callback(); // }); } else { client.close(); callback(); } }, shouldForceMongoDbServerToAssignId : function(test) { /// Set up server with custom pk factory var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null), 'forceServerObjectId':true}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.open(function(err, client) { client.createCollection('test_insert2', function(err, r) { client.collection('test_insert2', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 1; i < 1000; i++) { collection.insert({c:i}, {safe:true}, group()); } }, function done(err, result) { collection.insert({a:2}, {safe:true}, function(err, r) { collection.insert({a:3}, {safe:true}, function(err, r) { collection.count(function(err, count) { test.equal(1001, count); // Locate all the entries using find collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(1001, results.length); test.ok(results[0] != null); client.close(); // Let's close the db test.done(); }); }); }); }); }); } ) }); }); }); }, shouldCorrectlyPerformSingleInsert : function(test) { client.createCollection('shouldCorrectlyPerformSingleInsert', function(err, collection) { collection.insert({a:1}, {safe:true}, function(err, result) { collection.findOne(function(err, item) { test.equal(1, item.a); test.done(); }) }) }) }, shouldCorrectlyPerformBasicInsert : function(test) { client.createCollection('test_insert', function(err, r) { client.collection('test_insert', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 1; i < 1000; i++) { collection.insert({c:i}, {safe:true}, group()); } }, function done(err, result) { collection.insert({a:2}, {safe:true}, function(err, r) { collection.insert({a:3}, {safe:true}, function(err, r) { collection.count(function(err, count) { test.equal(1001, count); // Locate all the entries using find collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(1001, results.length); test.ok(results[0] != null); // Let's close the db test.done(); }); }); }); }); }); } ) }); }); }, // Test multiple document insert shouldCorrectlyHandleMultipleDocumentInsert : function(test) { client.createCollection('test_multiple_insert', function(err, r) { var collection = client.collection('test_multiple_insert', function(err, collection) { var docs = [{a:1}, {a:2}]; collection.insert(docs, {safe:true}, function(err, ids) { ids.forEach(function(doc) { test.ok(((doc['_id']) instanceof client.bson_serializer.ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]')); }); // Let's ensure we have both documents collection.find(function(err, cursor) { cursor.toArray(function(err, docs) { test.equal(2, docs.length); var results = []; // Check that we have all the results we want docs.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); // Let's close the db test.done(); }); }); }); }); }); }, shouldCorrectlyExecuteSaveInsertUpdate: function(test) { client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { collection.save({ email : 'save' }, {safe:true}, function() { collection.insert({ email : 'insert' }, {safe:true}, function() { collection.update( { email : 'update' }, { email : 'update' }, { upsert: true, safe:true}, function() { collection.find(function(e, c) { c.toArray(function(e, a) { test.equal(3, a.length) test.done(); }); }); } ); }); }); }); }, shouldCorrectlyInsertAndRetrieveLargeIntegratedArrayDocument : function(test) { client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) { var doc = {'a':0, 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] }; // Insert the collection collection.insert(doc, {safe:true}, function(err, r) { // Fetch and check the collection collection.findOne({'a': 0}, function(err, result) { test.deepEqual(doc.a, result.a); test.deepEqual(doc.b, result.b); test.done(); }); }); }); }, shouldCorrectlyInsertAndRetrieveDocumentWithAllTypes : function(test) { client.createCollection('test_all_serialization_types', function(err, collection) { var date = new Date(); var oid = new client.bson_serializer.ObjectID(); var string = 'binstring' var bin = new client.bson_serializer.Binary() for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)) } var motherOfAllDocuments = { 'string': 'hello', 'array': [1,2,3], 'hash': {'a':1, 'b':2}, 'date': date, 'oid': oid, 'binary': bin, 'int': 42, 'float': 33.3333, 'regexp': /regexp/, 'boolean': true, 'long': date.getTime(), 'where': new client.bson_serializer.Code('this.a > i', {i:1}), 'dbref': new client.bson_serializer.DBRef('namespace', oid, 'integration_tests_') } collection.insert(motherOfAllDocuments, {safe:true}, function(err, docs) { collection.findOne(function(err, doc) { // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); test.done(); }) }); }); }, shouldCorrectlyInsertAndUpdateDocumentWithNewScriptContext: function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { //convience curried handler for functions of type 'a -> (err, result) function getResult(callback){ return function(error, result) { test.ok(error == null); return callback(result); } }; db.collection('users', getResult(function(user_collection){ user_collection.remove({}, {safe:true}, function(err, result) { //first, create a user object var newUser = { name : 'Test Account', settings : {} }; user_collection.insert([newUser], {safe:true}, getResult(function(users){ var user = users[0]; var scriptCode = "settings.block = []; settings.block.push('test');"; var context = { settings : { thisOneWorks : "somestring" } }; Script.runInNewContext(scriptCode, context, "testScript"); //now create update command and issue it var updateCommand = { $set : context }; user_collection.update({_id : user._id}, updateCommand, {safe:true}, getResult(function(updateCommand) { // Fetch the object and check that the changes are persisted user_collection.findOne({_id : user._id}, function(err, doc) { test.ok(err == null); test.equal("Test Account", doc.name); test.equal("somestring", doc.settings.thisOneWorks); test.equal("test", doc.settings.block[0]); // Let's close the db db.close(); test.done(); }); }) ); })); }); })); }); }, shouldCorrectlySerializeDocumentWithAllTypesInNewContext : function(test) { client.createCollection('test_all_serialization_types_new_context', function(err, collection) { var date = new Date(); var scriptCode = "var string = 'binstring'\n" + "var bin = new mongo.Binary()\n" + "for(var index = 0; index < string.length; index++) {\n" + " bin.put(string.charAt(index))\n" + "}\n" + "motherOfAllDocuments['string'] = 'hello';" + "motherOfAllDocuments['array'] = [1,2,3];" + "motherOfAllDocuments['hash'] = {'a':1, 'b':2};" + "motherOfAllDocuments['date'] = date;" + "motherOfAllDocuments['oid'] = new mongo.ObjectID();" + "motherOfAllDocuments['binary'] = bin;" + "motherOfAllDocuments['int'] = 42;" + "motherOfAllDocuments['float'] = 33.3333;" + "motherOfAllDocuments['regexp'] = /regexp/;" + "motherOfAllDocuments['boolean'] = true;" + "motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" + "motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" + "motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');"; var context = { motherOfAllDocuments : {}, mongo:client.bson_serializer, date:date}; // Execute function in context Script.runInNewContext(scriptCode, context, "testScript"); // sys.puts(sys.inspect(context.motherOfAllDocuments)) var motherOfAllDocuments = context.motherOfAllDocuments; collection.insert(context.motherOfAllDocuments, {safe:true}, function(err, docs) { collection.findOne(function(err, doc) { // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); test.done(); }) }); }); }, shouldCorrectlyDoToJsonForLongValue : function(test) { client.createCollection('test_to_json_for_long', function(err, collection) { test.ok(collection instanceof Collection); collection.insertAll([{value: client.bson_serializer.Long.fromNumber(32222432)}], {safe:true}, function(err, ids) { collection.findOne({}, function(err, item) { test.equal(32222432, item.value); test.done(); }); }); }); }, shouldCorrectlyInsertAndUpdateWithNoCallback : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, client) { client.createCollection('test_insert_and_update_no_callback', function(err, collection) { // Insert the update collection.insert({i:1}, {safe:true}) // Update the record collection.update({i:1}, {"$set":{i:2}}, {safe:true}) // Make sure we leave enough time for mongodb to record the data setTimeout(function() { // Locate document collection.findOne({}, function(err, item) { test.equal(2, item.i) client.close(); test.done(); }); }, 100) }) }); }, shouldInsertAndQueryTimestamp : function(test) { client.createCollection('test_insert_and_query_timestamp', function(err, collection) { // Insert the update collection.insert({i:client.bson_serializer.Timestamp.fromNumber(100), j:client.bson_serializer.Long.fromNumber(200)}, {safe:true}, function(err, r) { // Locate document collection.findOne({}, function(err, item) { test.ok(item.i instanceof client.bson_serializer.Timestamp); test.equal(100, item.i); test.ok(typeof item.j == "number"); test.equal(200, item.j); test.done(); }); }) }) }, shouldCorrectlyInsertAndQueryUndefined : function(test) { client.createCollection('test_insert_and_query_undefined', function(err, collection) { // Insert the update collection.insert({i:undefined}, {safe:true}, function(err, r) { // Locate document collection.findOne({}, function(err, item) { test.equal(null, item.i) test.done(); }); }) }) }, shouldCorrectlySerializeDBRefToJSON : function(test) { var dbref = new client.bson_serializer.DBRef("foo", client.bson_serializer.ObjectID.createFromHexString("fc24a04d4560531f00000000"), null); JSON.stringify(dbref); test.done(); }, shouldCorrectlyPerformSafeInsert : function(test) { var fixtures = [{ name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: "" }, { name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something" }, { name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested" }]; client.createCollection('test_safe_insert', function(err, collection) { Step( function inserts() { var group = this.group(); for(var i = 0; i < fixtures.length; i++) { collection.insert(fixtures[i], {safe:true}, group()); } }, function done() { collection.count(function(err, count) { test.equal(3, count); collection.find().toArray(function(err, docs) { test.equal(3, docs.length) }); }); collection.find({}, {}, function(err, cursor) { var counter = 0; cursor.each(function(err, doc) { if(doc == null) { test.equal(3, counter); test.done(); } else { counter = counter + 1; } }); }); } ) }) }, shouldThrowErrorIfSerializingFunction : function(test) { client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) { var func = function() { return 1}; // Insert the update collection.insert({i:1, z:func }, {safe:true}, function(err, result) { collection.findOne({_id:result[0]._id}, function(err, object) { test.equal(func.toString(), object.z.code); test.equal(1, object.i); test.done(); }) }) }) }, shouldCorrectlyInsertDocumentWithUUID : function(test) { client.collection("insert_doc_with_uuid", function(err, collection) { collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { test.equal(null, err); collection.find({_id : "12345678123456781234567812345678"}).toArray(function(err, items) { test.equal(null, err); test.equal(items[0]._id, "12345678123456781234567812345678") test.equal(items[0].field, '1') // Generate a binary id var binaryUUID = new client.bson_serializer.Binary('00000078123456781234567812345678', client.bson_serializer.BSON.BSON_BINARY_SUBTYPE_UUID); collection.insert({_id : binaryUUID, field: '2'}, {safe:true}, function(err, result) { collection.find({_id : binaryUUID}).toArray(function(err, items) { test.equal(null, err); test.equal(items[0].field, '2') test.done(); }); }); }) }); }); }, shouldCorrectlyCallCallbackWithDbDriverInStrictMode : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, client) { client.createCollection('test_insert_and_update_no_callback_strict', function(err, collection) { collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { test.equal(null, err); collection.update({ '_id': "12345678123456781234567812345678" }, { '$set': { 'field': 0 }}, function(err, numberOfUpdates) { test.equal(null, err); test.equal(1, numberOfUpdates); db.close(); test.done(); }); }); }); }); }, shouldCorrectlyInsertDBRefWithDbNotDefined : function(test) { client.createCollection('shouldCorrectlyInsertDBRefWithDbNotDefined', function(err, collection) { var doc = {_id: new client.bson_serializer.ObjectID()}; var doc2 = {_id: new client.bson_serializer.ObjectID()}; var doc3 = {_id: new client.bson_serializer.ObjectID()}; collection.insert(doc, {safe:true}, function(err, result) { // Create object with dbref doc2.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id); doc3.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id, MONGODB); collection.insert([doc2, doc3], {safe:true}, function(err, result) { // Get all items collection.find().toArray(function(err, items) { test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[1].ref.namespace); test.equal(doc._id.toString(), items[1].ref.oid.toString()); test.equal(null, items[1].ref.db); test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[2].ref.namespace); test.equal(doc._id.toString(), items[2].ref.oid.toString()); test.equal(MONGODB, items[2].ref.db); test.done(); }) }); }); }); }, shouldCorrectlyInsertUpdateRemoveWithNoOptions : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { db.collection('shouldCorrectlyInsertUpdateRemoveWithNoOptions', function(err, collection) { collection.insert({a:1});//, function(err, result) { collection.update({a:1}, {a:2});//, function(err, result) { collection.remove({a:2});//, function(err, result) { collection.count(function(err, count) { test.equal(0, count); db.close(); test.done(); }) }); }); }, shouldCorrectlyExecuteMultipleFetches : function(test) { var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; // Search parameter var to = 'ralph' // Execute query db.open(function(err, db) { db.collection('shouldCorrectlyExecuteMultipleFetches', function(err, collection) { collection.insert({addresses:{localPart:'ralph'}}, {safe:true}, function(err, result) { // Let's find our user collection.findOne({"addresses.localPart" : to}, function( err, doc ) { test.equal(null, err); test.equal(to, doc.addresses.localPart); db.close(); test.done(); }); }); }); }); }, shouldCorrectlyFailWhenNoObjectToUpdate: function(test) { client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { collection.update({_id : new client.bson_serializer.ObjectID()}, { email : 'update' }, {safe:true}, function(err, result) { test.equal(0, result); test.done(); } ); }); }, 'Should correctly insert object and retrieve it when containing array and IsoDate' : function(test) { var doc = { "_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"), "str" : "foreign", "type" : 2, "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), "links" : [ "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" ] } client.createCollection('Should_correctly_insert_object_and_retrieve_it_when_containing_array_and_IsoDate', function(err, collection) { collection.insert(doc, {safe:true}, function(err, result) { test.ok(err == null); collection.findOne(function(err, item) { test.ok(err == null); test.deepEqual(doc, item); test.done(); }); }); }); }, 'Should correctly insert object with timestamps' : function(test) { var doc = { "_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"), "str" : "foreign", "type" : 2, "timestamp" : new client.bson_serializer.Timestamp(10000), "links" : [ "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" ], "timestamp2" : new client.bson_serializer.Timestamp(33333), } client.createCollection('Should_correctly_insert_object_with_timestamps', function(err, collection) { collection.insert(doc, {safe:true}, function(err, result) { test.ok(err == null); collection.findOne(function(err, item) { test.ok(err == null); test.deepEqual(doc, item); test.done(); }); }); }); }, noGlobalsLeaked : function(test) { var leaks = gleak.detectNew(); test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); test.done(); } }) // Stupid freaking workaround due to there being no way to run setup once for each suite var numberOfTestsRun = Object.keys(tests).length; // Assign out tests module.exports = tests;
const createImmutableEqualsSelector = require('./customSelectorCreator'); const compare = require('../util/compare'); const exampleReducers = require('../reducers/exampleReducers'); /** * Get state function */ const getSortingState = exampleReducers.getSortingState; const getPaginationState = exampleReducers.getPaginationState; const getDataState = exampleReducers.getDataState; /** * Sorting immutable data source * @param {Map} source immutable data source * @param {string} sortingKey property of data * @param {string} orderByCondition 'asc' or 'desc' * @return {List} immutable testing data source with sorting */ const sortingData = (source, sortingKey, orderByCondition) => { let orderBy = orderByCondition === 'asc' ? 1 : -1; return source.sortBy(data => data.get(sortingKey), (v, k) => orderBy * compare(v, k)); } /** * Paginating data from sortingSelector * @param {List} sortedData immutable data source with sorting * @param {number} start * @param {number} end * @return {array} sorting data with pagination and converting Immutable.List to array */ const pagination = (sortedData, start, end) => sortedData.slice(start, end).toList().toJS() /** * Partial selector only to do sorting */ const sortingSelector = createImmutableEqualsSelector( [ getDataState, // get data source getSortingState ], (dataState, sortingCondition) => sortingData(dataState, sortingCondition.get('sortingKey'), sortingCondition.get('orderBy')) ) /** * Root selector to paginate data from sortingSelector */ const paginationSelector = createImmutableEqualsSelector( [ sortingSelector, // bind selector to be new data source getPaginationState ], (sortedData, paginationCondition) => pagination(sortedData, paginationCondition.get('start'), paginationCondition.get('end')) ) module.exports = paginationSelector;
var stream = require('readable-stream') var util = require('util') var fifo = require('fifo') var toStreams2 = function(s) { if (s._readableState) return s var wrap = new stream.Readable().wrap(s) if (s.destroy) wrap.destroy = s.destroy.bind(s) return wrap } var Parallel = function(streams, opts) { if (!(this instanceof Parallel)) return new Parallel(streams, opts) stream.Readable.call(this, opts) this.destroyed = false this._forwarding = false this._drained = false this._queue = fifo() for (var i = 0; i < streams.length; i++) this.add(streams[i]) this._current = this._queue.node } util.inherits(Parallel, stream.Readable) Parallel.obj = function(streams) { return new Parallel(streams, {objectMode: true, highWaterMark: 16}) } Parallel.prototype.add = function(s) { s = toStreams2(s) var self = this var node = this._queue.push(s) var onend = function() { if (node === self._current) self._current = node.next self._queue.remove(node) s.removeListener('readable', onreadable) s.removeListener('end', onend) s.removeListener('error', onerror) s.removeListener('close', onclose) self._forward() } var onreadable = function() { self._forward() } var onclose = function() { if (!s._readableState.ended) self.destroy() } var onerror = function(err) { self.destroy(err) } s.on('end', onend) s.on('readable', onreadable) s.on('close', onclose) s.on('error', onerror) } Parallel.prototype._read = function () { this._drained = true this._forward() } Parallel.prototype._forward = function () { if (this._forwarding || !this._drained) return this._forwarding = true var stream = this._get() if (!stream) return var chunk while ((chunk = stream.read()) !== null) { this._current = this._current.next this._drained = this.push(chunk) stream = this._get() if (!stream) return } this._forwarding = false } Parallel.prototype._get = function() { var stream = this._current && this._queue.get(this._current) if (!stream) this.push(null) else return stream } Parallel.prototype.destroy = function (err) { if (this.destroyed) return this.destroyed = true var next while ((next = this._queue.shift())) { if (next.destroy) next.destroy() } if (err) this.emit('error', err) this.emit('close') } module.exports = Parallel
const App = require('./spec/app'); module.exports = config => { const params = { basePath: '', frameworks: [ 'express-http-server', 'jasmine' ], files: [ 'lib/**/*.js' ], colors: true, singleRun: true, logLevel: config.LOG_WARN, browsers: [ 'Chrome', 'PhantomJS' ], concurrency: Infinity, reporters: [ 'spec', 'coverage' ], preprocessors: { 'lib/**/*.js': ['coverage'] }, coverageReporter: { dir: 'coverage/', reporters: [ { type: 'html', subdir: 'report' }, { type: 'lcovonly', subdir: './', file: 'coverage-front.info' }, { type: 'lcov', subdir: '.' } ] }, browserDisconnectTimeout: 15000, browserNoActivityTimeout: 120000, expressHttpServer: { port: 8092, appVisitor: App } }; if (process.env.TRAVIS) { params.browsers = [ 'PhantomJS' ]; } config.set(params); };
"use strict"; let fs = require("fs") , chalk = require("chalk"); module.exports = function(name) { let file = process.env.CONFIG_PATH + "initializers/" + name; if (!fs.existsSync(file + ".js")) console.log(chalk.red("\tInitializer", name + ".js not found, add it on /config/initializers")); return require(file); };
"use strict"; // Controller function Avatar(app, req, res) { // HTTP action this.action = (params) => { app.sendFile(res, './storage/users/' + params[0] + '/' + params[1]); }; }; module.exports = Avatar;
"use strict"; var Response = (function () { function Response(result, childWork) { this.result = result; this.childWork = childWork; } return Response; }()); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Response; //# sourceMappingURL=response.js.map
Package.describe({ name: 'craigslist-utils', summary: 'Npm Craigslist-utils packaged for Meteor.' }); Npm.depends ({ 'craigslist-utils': '0.0.7' }); Package.on_use(function (api) { api.add_files('craigslist-utils.js', ['server']); api.export('CL'); }); Package.on_test(function (api) { api.use('craigslist-utils'); api.use('tinytest'); api.add_files('craigslist-utils_tests.js'); });
'use strict'; import Application from '../../core/Application.js'; import Action from '../../core/Action.js'; describe('Action', () => { var app; var action; class ChildAction extends Action { get name() { return 'ChildAction'; } } beforeEach(() => { app = new Application(); action = new ChildAction(app); }); it('has to be defined, be a function and can be instantiated', () => { expect(ChildAction).toBeDefined(); expect(ChildAction).toEqual(jasmine.any(Function)); expect(action instanceof ChildAction).toBe(true); }); it('holds an app instance', () => { var myApp = action.app; expect(myApp).toEqual(jasmine.any(Application)); expect(myApp).toBe(app); }); it('has an execute function that throws an error if it is not implemented', () => { expect(action.execute).toEqual(jasmine.any(Function)); expect(() => action.execute(payload)).toThrow(); }); });
$(document).ready(function() { $('#mostrar_menu').click(function() { $('#sidebar-wrapper').toggle(300); }); });
const { app, BrowserWindow } = require('electron'); const {ipcMain} = require('electron'); // shared to-do list data global.sharedData = { itemList: [ { id: 0, text: "First meet up with David Lau on 5th July", isCompleted: true }, { id: 1, text: "David Bewick meet with David Lau on Monday", isCompleted: true }, { id: 2, text: "David Lau to speak with Kaspar on Wednesday", isCompleted: false } ], itemLatestID: 2 }; // electron main process app.on('ready', () => { const numOfWindows = 3; // number of windows, can grow dynamically var windows = []; for(var i = 0; i < numOfWindows; i++){ const win = new BrowserWindow({ width: 800, height: 600, show: true, }); win.loadURL(`file://${__dirname}/dist/index.html`); // win.openDevTools(); windows.push(win); } ipcMain.on('item-list-update', () => { windows.forEach((win) => { win.webContents.send('refresh-item-data'); }); }); });
function generalAttack(attacker, receiver, weaponBonus){ //Weapon bonus of one means attacker gets bonus, 0 = neutral, and -1 = penalty if(attacker.attack > receiver.defense){ if(weaponBonus == 1){ receiver.health = receiver.health - ((attacker.attack + 2) - receiver.defense); }else if(weaponBonus == -1){ receiver.health = receiver.health - ((attacker.attack - 2) - receiver.defense); }else{ receiver.health = receiver.health - (attacker.attack - receiver.defense); } }else { receiver.health -= 2; } } function death(){ console.log("should be dead"); hero.alive = false; } // Global variables, we're all going to hell var healthPlaceholder = 0; var damageTaken = 0; var totalDamageDealt = 0; var totalDamageTaken = 0; var totalKills = 0; var totalTurns = 0; function wolvesAttack() { var wolf = new Character(); wolf.health = 30; wolf.attack = 5; wolf.defense = 5; while(wolf.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(wolf, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A wolf runs up and bites "+hero.name+" for " + damageTaken + " damage"); }else{ print_to_path("A wolf claww "+hero.name+" for " + damageTaken + " damage"); } } else { healthPlaceholder = wolf.health; generalAttack(hero, wolf,0); totalDamageDealt += (healthPlaceholder - wolf.health); print_to_path(hero.name+" attacks the wolf!"); print_to_path("The wolf's health falls to "+wolf.health); } totalTurns += 1; } if(wolf.health <= 0){ console.log("wolf dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function banditsAttack() { var bandit = new Character(); bandit.health = 40; bandit.attack = 10; bandit.defense = 5; while(bandit.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 30){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(bandit, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A clan of bandits knocks "+hero.name+" to the ground dealing " + damageTaken + " Damage"); }else{ print_to_path("A bandit Seaks up from behind stabbs "+hero.name+" dealing " + damageTaken + " Damage"); } } else { healthPlaceholder = bandit.health; if(hero.weapon == "Sword"){ generalAttack(hero, bandit,1); }else if(hero.weapon == "Bow"){ generalAttack(hero, bandit,-1); }else{ generalAttack(hero, bandit,0); } totalDamageDealt += (healthPlaceholder - bandit.health); print_to_path(hero.name+" attacks a bandit!"); print_to_path("The bandit's health falls to "+bandit.health); } totalTurns += 1; } if(bandit.health <= 0){ console.log("bandit dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function trollsAttack() { var troll = new Character(); troll.health = 50; troll.attack = 25; troll.defense = 15; while(troll.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 35){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(troll, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A troll throws a small axe at "+hero.name+" dealing " + damageTaken + " damage"); }else{ print_to_path("A troll smashes "+hero.name+" with his club for " + damageTaken + " damage"); } } else { healthPlaceholder = troll.health; generalAttack(hero, troll); totalDamageDealt += (healthPlaceholder - troll.health); print_to_path(hero.name+" attacks the troll!"); print_to_path("The troll's health falls to "+troll.health); } totalTurns += 1; } if(troll.health <= 0){ console.log("troll dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function golemsAttack() { var golem = new Character(); golem.health = 60; golem.attack = 10; golem.defense = 50; while(golem.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(golem, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A golem flails its arms, smashing "+hero.name+" into the ground, dealing " + damageTaken + " damage"); }else{ print_to_path("A golem stomps its foot on the ground causing rocks to fall on "+hero.name+" from the nearby mountain. dealing " + damageTaken + " Damage"); } } else { healthPlaceholder = golem.health; if(hero.weapon == "Mace"){ generalAttack(hero, golem,1); }else if(hero.weapon == "Sword"){ generalAttack(hero, golem,-1); }else{ generalAttack(hero, golem,0); } totalDamageDealt += (healthPlaceholder - golem.health); print_to_path(hero.name+" attacks the golem!"); print_to_path("The golem's health falls to "+golem.health); } totalTurns += 1; } if(golem.health <= 0){ console.log("golem dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function dragonAttack() { // atk 30 var dragon = new Character(); dragon.health = 60; dragon.attack = 30; dragon.defense = 30; while(dragon.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(dragon, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A dragon breaths green flames at "+hero.name+" which inflicted a burn, dealing " + damageTaken + " damage"); }else{ print_to_path("A dragon wipes its tail along the floor flinging "+hero.name+" into the wall, dealing " + damageTaken + " damage"); } } else { healthPlaceholder = dragon.health; if(hero.weapon == "Bow"){ generalAttack(hero, dragon,1); }else if(hero.weapon == "Mace"){ generalAttack(hero, dragon,-1); }else{ generalAttack(hero, dragon,0); } totalDamageDealt += (healthPlaceholder - dragon.health); print_to_path(hero.name+" attacks the dragon!"); print_to_path("The dragon's health falls to: "+dragon.health); } totalTurns += 1; } if(dragon.health <= 0){ console.log("dragon dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function blackSquirrelAttacks() { // I has no Tail D: } function statistics() { print_to_path("<b>Score:</b>"); print_to_path("Total kills: " + totalKills + " | " + "Total turns: " + totalTurns + " | " + "Total damage dealt: " + totalDamageDealt + " | " + "Total damage taken: " + totalDamageTaken ); }
var draw = SVG('mainPage'); var energyBar = draw.rect(0,5).move(0,598) .fill({ color: '#cc0', opacity: '1' }) .stroke({ color: '#fff', width: '1', opacity: '0.6'}); var port = 25550; var images = "http://"+document.location.hostname+":"+port+"/game/images/"; var localPlayers = new Array(); var localBullets = new Array(); var localBonus = new Array(); var bonusBars = new Array(); function PlayerEntity(mark, text) { this.mark = mark; this.text = text; } // Gestion des joueurs socket.on('refreshPlayers', function (players) { for(var i in players) { // Création des nouveaux joueurs if(typeof(localPlayers[i]) === "undefined") { var ownColor = '#fff'; if(players[i].id == socket.socket.sessionid) { // Attribution d'un marqueur de couleur pour le joueur en cours ownColor = '#c00'; } // Création des éléments var circle = draw.circle(6).move(players[i].x,players[i].y) .fill({ color: ownColor, opacity: '1' }) .stroke({ color: '#fff', width: '1' }); var text = draw.text(players[i].pseudo).font({ size: 12 }) .fill({ color: '#fff', opacity: '0.6' }) .stroke({ color: '#fff', width: '1', opacity: '0.4'}); // Déplacement du texte au dessus du marqueur text.move(players[i].x - text.bbox().width /2, players[i].y - text.bbox().height - 10); // Ajout de l'entité au tableau localPlayers[i] = new PlayerEntity(circle, text); } else { // Déplacement du joueur localPlayers[i].mark.move(players[i].x, players[i].y); localPlayers[i].text.move(players[i].x - localPlayers[i].text.bbox().width /2, players[i].y - localPlayers[i].text.bbox().height - 10); // Actualisation du joueur local if(players[i].id == socket.socket.sessionid) { // Affichage du bouton au bon endroit en fonction du mode if(players[i].spec == false) { document.getElementById("b1").style.display = "none"; document.getElementById("b2").style.display = "block"; } else { document.getElementById("b2").style.display = "none"; document.getElementById("b1").style.display = "block"; } // Actualisation de la barre d'énergie if (players[i].energy > 1) { energyBar.width(((players[i].energy-1)/100)*800); } else { energyBar.width(0); } // Actualisation des barres de bonus for(var j in bonusBars) { switch(bonusBars[j].name) { case "speed": bonusBars[j].bar.width(players[i].bSpeed); break; case "arrow": bonusBars[j].bar.width(players[i].bArrow); break; } } } } } }); // Passage en spectateur function _setSpec() { socket.emit('setSpec', 1); } // Ajout d'une barre de bonus socket.on('newPlayerBonus', function (bonus) { // Vérification de la non existence de la barre for(var i in bonusBars) { if(bonusBars[i].name == bonus.name) { return; } } var rect = draw.rect(0,12).move(0,15*(bonusBars.length+1)) .fill({ color: bonus.color, opacity: '0.4' }); bonusBars.push({name: bonus.name, bar: rect}); }); // Rerait d'un joueur socket.on('removePlayer', function (id) { localPlayers[id].mark.remove(); localPlayers[id].text.remove(); localPlayers.splice(id,1); }); // Affichage d'un bonus socket.on('displayBonus', function (bonus) { for(var i in bonus) { // Création des nouveaux bonus if(typeof(localBonus[i]) === "undefined") { localBonus[i] = draw.image(images+""+bonus[i].image+".png") .move(bonus[i].x,bonus[i].y); } } }); // Retrait d'un bonus socket.on('removeBonus', function (bonusID) { if (bonusID == -1) { for(var i in localBonus) { localBonus[i].remove(); } localBonus = []; } else { localBonus[bonusID].remove(); localBonus.splice(bonusID,1); } }); // Rafraichissement du tableau de scores socket.on('refreshScores', function (players) { // Arrangement du tableau en fonction des scores players = players.sort(function(a,b) { return a.points > b.points; }).reverse(); // Formattage de la liste des joueurs var list = "<b>Joueurs en ligne : </b><br />"; var listSpec = "<b>Spectateurs : </b><br />"; for(var i in players) { if(players[i].spec == 0) { if(players[i].alive == 0) { list = list + "<span style='color:#" + players[i].color + "; float:left;'><s>" + players[i].pseudo + "</s></span><span style='float:right;'>- " + players[i].points + " points</span><br />"; } else { list = list + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><span style='float:right;'>- " + players[i].points + " points</span><br />"; } } else { listSpec = listSpec + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><br />"; } } // Mise à jour de l'affichage de la liste des joueurs document.getElementById("scores").innerHTML = list; document.getElementById("specs").innerHTML = listSpec; }); // Ajout des nouvelles balles contenues dans le buffer var max = 0; socket.on('refreshBullets', function (bulletTable) { for(var i in bulletTable) { // Création des traces var length = max + i; if(typeof(localBullets[length]) === "undefined") { localBullets[length] = draw.circle(5/*heignt line*/) .move(bulletTable[i].x,bulletTable[i].y) .fill({ color:'#'+bulletTable[i].color }) .stroke({ color: '#fff', width: '1', opacity: '0.5' }); max++; } } }); // Réinitialisation du terrain socket.on('resetGround', function (e) { for(var i in localBullets) { localBullets[i].remove(); } localBullets = []; }); // Arret du serveur socket.on('stopServer', function (e) { window.location.replace("http://"+document.location.hostname+"/?alert=1"); }); // Kick du joueur socket.on('kickPlayer', function (e) { window.location.replace("http://"+document.location.hostname+"/?kick=1"); }); // Gestion d'un nouveau message socket.on('newMessage', function (e) { var tmp = document.getElementById("comments").innerHTML; document.getElementById("comments").innerHTML = "<b>"+e.pseudo+" : </b>"+e.message+"<br />"+tmp; }); // Affichage d'une alerte socket.on('displayAlert', function(text, color, duration) { if(color == '') { color = "#fff"; } if(duration == '') { duration = 1000; } var appear, disappear, deleteAlert, alert = draw.text(text).font({ size: 36 }); appear = function() { alert.move(400-(alert.bbox().width / 2), 100) .fill({ color: color, opacity: '0' }) .animate(100).fill({ opacity: '1' }) .after(disappear); }; disappear = function() { setTimeout(function() { alert.animate(500).fill({ opacity: '0' }).after(deleteAlert); }, duration); }; deleteAlert = function() { alert.remove(); } appear(); }); // Affichage d'une victoire socket.on('displayVictory', function(pseudo) { var appear, disappear, deleteAlert, alert = draw.text("Victoire de "+pseudo+" !").font({ size: 20 }); appear = function() { alert.move(400-(alert.bbox().width / 2), 50) .fill({ color: '#fff', opacity: '0' }) .animate(100).fill({ opacity: '1' }) .after(disappear); }; disappear = function() { setTimeout(function() { alert.animate(500).fill({ opacity: '0' }).after(deleteAlert); }, 1000); }; deleteAlert = function() { alert.remove(); } appear(); });
goog.provide('gmf.DisplayquerygridController'); goog.provide('gmf.displayquerygridDirective'); goog.require('gmf'); goog.require('ngeo.CsvDownload'); goog.require('ngeo.GridConfig'); /** @suppress {extraRequire} */ goog.require('ngeo.gridDirective'); goog.require('ngeo.FeatureOverlay'); goog.require('ngeo.FeatureOverlayMgr'); goog.require('ol.Collection'); goog.require('ol.style.Circle'); goog.require('ol.style.Fill'); goog.require('ol.style.Stroke'); goog.require('ol.style.Style'); ngeo.module.value('gmfDisplayquerygridTemplateUrl', /** * @param {angular.JQLite} element Element. * @param {angular.Attributes} attrs Attributes. * @return {string} Template. */ function(element, attrs) { var templateUrl = attrs['gmfDisplayquerygridTemplateurl']; return templateUrl !== undefined ? templateUrl : gmf.baseTemplateUrl + '/displayquerygrid.html'; }); /** * Provides a directive to display results of the {@link ngeo.queryResult} in a * grid and shows related features on the map using * the {@link ngeo.FeatureOverlayMgr}. * * You can override the default directive's template by setting the * value `gmfDisplayquerygridTemplateUrl`. * * Features displayed on the map use a default style but you can override these * styles by passing ol.style.Style objects as attributes of this directive. * * Example: * * <gmf-displayquerygrid * gmf-displayquerygrid-map="ctrl.map" * gmf-displayquerygrid-featuresstyle="ctrl.styleForAllFeatures" * gmf-displayquerygrid-selectedfeaturestyle="ctrl.styleForTheCurrentFeature"> * </gmf-displayquerygrid> * * @htmlAttribute {boolean} gmf-displayquerygrid-active The active state of the component. * @htmlAttribute {ol.style.Style} gmf-displayquerygrid-featuresstyle A style * object for all features from the result of the query. * @htmlAttribute {ol.style.Style} gmf-displayquerygrid-selectedfeaturestyle A style * object for the currently selected features. * @htmlAttribute {ol.Map} gmf-displayquerygrid-map The map. * @htmlAttribute {boolean?} gmf-displayquerygrid-removeemptycolumns Optional. Should * empty columns be hidden? Default: `false`. * @htmlAttribute {number?} gmf-displayquerygrid-maxrecenterzoom Optional. Maximum * zoom-level to use when zooming to selected features. * @htmlAttribute {gmfx.GridMergeTabs?} gmf-displayquerygrid-gridmergetabas Optional. * Configuration to merge grids with the same attributes into a single grid. * @param {string} gmfDisplayquerygridTemplateUrl URL to a template. * @return {angular.Directive} Directive Definition Object. * @ngInject * @ngdoc directive * @ngname gmfDisplayquerygrid */ gmf.displayquerygridDirective = function( gmfDisplayquerygridTemplateUrl) { return { bindToController: true, controller: 'GmfDisplayquerygridController', controllerAs: 'ctrl', templateUrl: gmfDisplayquerygridTemplateUrl, replace: true, restrict: 'E', scope: { 'active': '=gmfDisplayquerygridActive', 'featuresStyleFn': '&gmfDisplayquerygridFeaturesstyle', 'selectedFeatureStyleFn': '&gmfDisplayquerygridSourceselectedfeaturestyle', 'getMapFn': '&gmfDisplayquerygridMap', 'removeEmptyColumnsFn': '&?gmfDisplayquerygridRemoveemptycolumns', 'maxResultsFn': '&?gmfDisplayquerygridMaxresults', 'maxRecenterZoomFn': '&?gmfDisplayquerygridMaxrecenterzoom', 'mergeTabsFn': '&?gmfDisplayquerygridMergetabs' } }; }; gmf.module.directive('gmfDisplayquerygrid', gmf.displayquerygridDirective); /** * Controller for the query grid. * * @param {!angular.Scope} $scope Angular scope. * @param {ngeox.QueryResult} ngeoQueryResult ngeo query result. * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr The ngeo feature * overlay manager service. * @param {angular.$timeout} $timeout Angular timeout service. * @param {ngeo.CsvDownload} ngeoCsvDownload CSV download service. * @param {ngeo.Query} ngeoQuery Query service. * @param {angular.JQLite} $element Element. * @constructor * @export * @ngInject * @ngdoc Controller * @ngname GmfDisplayquerygridController */ gmf.DisplayquerygridController = function($scope, ngeoQueryResult, ngeoFeatureOverlayMgr, $timeout, ngeoCsvDownload, ngeoQuery, $element) { /** * @type {!angular.Scope} * @private */ this.$scope_ = $scope; /** * @type {angular.$timeout} * @private */ this.$timeout_ = $timeout; /** * @type {ngeox.QueryResult} * @export */ this.ngeoQueryResult = ngeoQueryResult; /** * @type {ngeo.CsvDownload} * @private */ this.ngeoCsvDownload_ = ngeoCsvDownload; /** * @type {angular.JQLite} * @private */ this.$element_ = $element; /** * @type {number} * @export */ this.maxResults = ngeoQuery.getLimit(); /** * @type {boolean} * @export */ this.active = false; /** * @type {boolean} * @export */ this.pending = false; /** * @type {!Object.<string, gmfx.GridSource>} * @export */ this.gridSources = {}; /** * IDs of the grid sources in the order they were loaded. * @type {Array.<string>} * @export */ this.loadedGridSources = []; /** * The id of the currently shown query source. * @type {string|number|null} * @export */ this.selectedTab = null; /** * @type {boolean} * @private */ this.removeEmptyColumns_ = this['removeEmptyColumnsFn'] ? this['removeEmptyColumnsFn']() === true : false; /** * @type {number|undefined} * @export */ this.maxRecenterZoom = this['maxRecenterZoomFn'] ? this['maxRecenterZoomFn']() : undefined; var mergeTabs = this['mergeTabsFn'] ? this['mergeTabsFn']() : {}; /** * @type {!gmfx.GridMergeTabs} * @private */ this.mergeTabs_ = mergeTabs ? mergeTabs : {}; /** * A mapping between row uid and the corresponding feature for each * source. * @type {!Object.<string, Object.<string, ol.Feature>>} * @private */ this.featuresForSources_ = {}; // Styles for displayed features (features) and selected features // (highlightFeatures_) (user can set both styles). /** * @type {ol.Collection} * @private */ this.features_ = new ol.Collection(); var featuresOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay(); var featuresStyle = this['featuresStyleFn'](); if (featuresStyle !== undefined) { goog.asserts.assertInstanceof(featuresStyle, ol.style.Style); featuresOverlay.setStyle(featuresStyle); } featuresOverlay.setFeatures(this.features_); /** * @type {ngeo.FeatureOverlay} * @private */ this.highlightFeatureOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay(); /** * @type {ol.Collection} * @private */ this.highlightFeatures_ = new ol.Collection(); this.highlightFeatureOverlay_.setFeatures(this.highlightFeatures_); var highlightFeatureStyle = this['selectedFeatureStyleFn'](); if (highlightFeatureStyle !== undefined) { goog.asserts.assertInstanceof(highlightFeatureStyle, ol.style.Style); } else { var fill = new ol.style.Fill({color: [255, 0, 0, 0.6]}); var stroke = new ol.style.Stroke({color: [255, 0, 0, 1], width: 2}); highlightFeatureStyle = new ol.style.Style({ fill: fill, image: new ol.style.Circle({fill: fill, radius: 5, stroke: stroke}), stroke: stroke, zIndex: 10 }); } this.highlightFeatureOverlay_.setStyle(highlightFeatureStyle); var map = null; var mapFn = this['getMapFn']; if (mapFn) { map = mapFn(); goog.asserts.assertInstanceof(map, ol.Map); } /** * @type {ol.Map} * @private */ this.map_ = map; // Watch the ngeo query result service. this.$scope_.$watchCollection( function() { return ngeoQueryResult; }, function(newQueryResult, oldQueryResult) { if (newQueryResult !== oldQueryResult) { this.updateData_(); } }.bind(this)); /** * An unregister function returned from `$scope.$watchCollection` for * "on-select" changes (when rows are selected/unselected). * @type {?function()} * @private */ this.unregisterSelectWatcher_ = null; }; /** * Returns a list of grid sources in the order they were loaded. * @export * @return {Array.<gmfx.GridSource>} Grid sources. */ gmf.DisplayquerygridController.prototype.getGridSources = function() { return this.loadedGridSources.map(function(sourceId) { return this.gridSources[sourceId]; }.bind(this)); }; /** * @private */ gmf.DisplayquerygridController.prototype.updateData_ = function() { // close if there are no results if (this.ngeoQueryResult.total === 0 && !this.hasOneWithTooManyResults_()) { var oldActive = this.active; this.clear(); if (oldActive) { // don't close if there are pending queries this.active = this.ngeoQueryResult.pending; this.pending = this.ngeoQueryResult.pending; } return; } this.active = true; this.pending = false; var sources = this.ngeoQueryResult.sources; // merge sources if requested if (Object.keys(this.mergeTabs_).length > 0) { sources = this.getMergedSources_(sources); } // create grids (only for source with features or with too many results) sources.forEach(function(source) { if (source.tooManyResults) { this.makeGrid_(null, source); } else { var features = source.features; if (features.length > 0) { this.collectData_(source); } } }.bind(this)); if (this.loadedGridSources.length == 0) { // if no grids were created, do not show this.active = false; return; } // keep the first existing navigation tab open if (this.selectedTab === null || !(('' + this.selectedTab) in this.gridSources)) { // selecting the tab is done in a timeout, because otherwise in rare cases // `ng-class` might set the `active` class on multiple tabs. this.$timeout_(function() { var firstSourceId = this.loadedGridSources[0]; this.selectTab(this.gridSources[firstSourceId]); this.reflowGrid_(firstSourceId); }.bind(this), 0); } }; /** * @private * @return {boolean} If one of the source has too many results. */ gmf.DisplayquerygridController.prototype.hasOneWithTooManyResults_ = function() { return this.ngeoQueryResult.sources.some(function(source) { return source.tooManyResults; }); }; /** * Returns if the given grid source is selected? * @export * @param {gmfx.GridSource} gridSource Grid source. * @return {boolean} Is selected? */ gmf.DisplayquerygridController.prototype.isSelected = function(gridSource) { return this.selectedTab === gridSource.source.id; }; /** * Try to merge the mergable sources. * @param {Array.<ngeox.QueryResultSource>} sources Sources. * @return {Array.<ngeox.QueryResultSource>} The merged sources. * @private */ gmf.DisplayquerygridController.prototype.getMergedSources_ = function(sources) { var allSources = []; /** @type {Object.<string, ngeox.QueryResultSource>} */ var mergedSources = {}; sources.forEach(function(source) { // check if this source can be merged var mergedSource = this.getMergedSource_(source, mergedSources); if (mergedSource === null) { // this source should not be merged, add as is allSources.push(source); } }.bind(this)); for (var mergedSourceId in mergedSources) { allSources.push(mergedSources[mergedSourceId]); } return allSources; }; /** * Check if the given source should be merged. If so, an artificial source * that will contain the features of all mergable sources is returned. If not, * `null` is returned. * @param {ngeox.QueryResultSource} source Source. * @param {Object.<string, ngeox.QueryResultSource>} mergedSources Merged sources. * @return {?ngeox.QueryResultSource} A merged source of null if the source should * not be merged. * @private */ gmf.DisplayquerygridController.prototype.getMergedSource_ = function(source, mergedSources) { var mergeSourceId = null; for (var currentMergeSourceId in this.mergeTabs_) { var sourceIds = this.mergeTabs_[currentMergeSourceId]; var containsSource = sourceIds.some(function(sourceId) { return sourceId == source.id; }); if (containsSource) { mergeSourceId = currentMergeSourceId; break; } } if (mergeSourceId === null) { // this source should not be merged return null; } /** @type {ngeox.QueryResultSource} */ var mergeSource; if (mergeSourceId in mergedSources) { mergeSource = mergedSources[mergeSourceId]; } else { mergeSource = { features: [], id: mergeSourceId, label: mergeSourceId, pending: false, queried: true, tooManyResults: false, totalFeatureCount: undefined }; mergedSources[mergeSourceId] = mergeSource; } // add features of source to merge source source.features.forEach(function(feature) { mergeSource.features.push(feature); }); // if one of the source has too many results, the resulting merged source will // also be marked with `tooManyResults` and will not contain any features. mergeSource.tooManyResults = mergeSource.tooManyResults || source.tooManyResults; if (mergeSource.tooManyResults) { mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ? mergeSource.totalFeatureCount + mergeSource.features.length : mergeSource.features.length; mergeSource.features = []; } if (source.totalFeatureCount !== undefined) { mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ? mergeSource.totalFeatureCount + source.totalFeatureCount : source.totalFeatureCount; } return mergeSource; }; /** * Collect all features in the queryResult object. * @param {ngeox.QueryResultSource} source Result source. * @private */ gmf.DisplayquerygridController.prototype.collectData_ = function(source) { var features = source.features; var allProperties = []; var featureGeometriesNames = []; var featuresForSource = {}; var properties, featureGeometryName; features.forEach(function(feature) { properties = feature.getProperties(); if (properties !== undefined) { // Keeps distinct geometry names to remove theme later. featureGeometryName = feature.getGeometryName(); if (featureGeometriesNames.indexOf(featureGeometryName) === -1) { featureGeometriesNames.push(featureGeometryName); } allProperties.push(properties); featuresForSource[ngeo.GridConfig.getRowUid(properties)] = feature; } }.bind(this)); this.cleanProperties_(allProperties, featureGeometriesNames); if (allProperties.length > 0) { var gridCreated = this.makeGrid_(allProperties, source); if (gridCreated) { this.featuresForSources_['' + source.id] = featuresForSource; } } }; /** * Remove all unwanted columns. * @param {Array.<Object>} allProperties A row. * @param {Array.<string>} featureGeometriesNames Geometry names. * @private */ gmf.DisplayquerygridController.prototype.cleanProperties_ = function( allProperties, featureGeometriesNames) { allProperties.forEach(function(properties) { featureGeometriesNames.forEach(function(featureGeometryName) { delete properties[featureGeometryName]; }); delete properties['boundedBy']; }); if (this.removeEmptyColumns_ === true) { this.removeEmptyColumnsFn_(allProperties); } }; /** * Remove columns that will be completely empty between each properties. * @param {Array.<Object>} allProperties A row. * @private */ gmf.DisplayquerygridController.prototype.removeEmptyColumnsFn_ = function( allProperties) { // Keep all keys that correspond to at least one value in a properties object. var keysToKeep = []; var i, key; for (key in allProperties[0]) { for (i = 0; i < allProperties.length; i++) { if (allProperties[i][key] !== undefined) { keysToKeep.push(key); break; } } } // Get all keys that previously always refers always to an empty value. var keyToRemove; allProperties.forEach(function(properties) { keyToRemove = []; for (key in properties) { if (keysToKeep.indexOf(key) === -1) { keyToRemove.push(key); } } // Remove these keys. keyToRemove.forEach(function(key) { delete properties[key]; }); }); }; /** * @param {?Array.<Object>} data Grid rows. * @param {ngeox.QueryResultSource} source Query source. * @return {boolean} Returns true if a grid was created. * @private */ gmf.DisplayquerygridController.prototype.makeGrid_ = function(data, source) { var sourceId = '' + source.id; var gridConfig = null; if (data !== null) { gridConfig = this.getGridConfiguration_(data); if (gridConfig === null) { return false; } } if (this.loadedGridSources.indexOf(sourceId) == -1) { this.loadedGridSources.push(sourceId); } this.gridSources[sourceId] = { configuration: gridConfig, source: source }; return true; }; /** * @param {Array.<!Object>} data Grid rows. * @return {?ngeo.GridConfig} Grid config. * @private */ gmf.DisplayquerygridController.prototype.getGridConfiguration_ = function( data) { goog.asserts.assert(data.length > 0); var columns = Object.keys(data[0]); /** @type {Array.<ngeox.GridColumnDef>} */ var columnDefs = []; columns.forEach(function(column) { if (column !== 'ol_uid') { columnDefs.push(/** @type {ngeox.GridColumnDef} */ ({ name: column })); } }); if (columnDefs.length > 0) { return new ngeo.GridConfig(data, columnDefs); } else { // no columns, do not show grid return null; } }; /** * Remove the current selected feature and source and remove all features * from the map. * @export */ gmf.DisplayquerygridController.prototype.clear = function() { this.active = false; this.pending = false; this.gridSources = {}; this.loadedGridSources = []; this.selectedTab = null; this.tooManyResults = false; this.features_.clear(); this.highlightFeatures_.clear(); this.featuresForSources_ = {}; if (this.unregisterSelectWatcher_) { this.unregisterSelectWatcher_(); } }; /** * Select the tab for the given grid source. * @param {gmfx.GridSource} gridSource Grid source. * @export */ gmf.DisplayquerygridController.prototype.selectTab = function(gridSource) { var source = gridSource.source; this.selectedTab = source.id; if (this.unregisterSelectWatcher_) { this.unregisterSelectWatcher_(); this.unregisterSelectWatcher_ = null; } if (gridSource.configuration !== null) { this.unregisterSelectWatcher_ = this.$scope_.$watchCollection( function() { return gridSource.configuration.selectedRows; }, function(newSelected, oldSelectedRows) { if (Object.keys(newSelected) !== Object.keys(oldSelectedRows)) { this.onSelectionChanged_(); } }.bind(this)); } this.updateFeatures_(gridSource); }; /** * @private * @param {string|number} sourceId Id of the source that should be refreshed. */ gmf.DisplayquerygridController.prototype.reflowGrid_ = function(sourceId) { // this is a "work-around" to make sure that the grid is rendered correctly. // when a pane is activated by setting `this.selectedTab`, the class `active` // is not yet set on the pane. that's why the class is set manually, and // after the pane is shown (in the next digest loop), the grid table can // be refreshed. var activePane = this.$element_.find('div.tab-pane#' + sourceId); activePane.removeClass('active').addClass('active'); this.$timeout_(function() { activePane.find('div.ngeo-grid-table-container table')['trigger']('reflow'); }); }; /** * Called when the row selection has changed. * @private */ gmf.DisplayquerygridController.prototype.onSelectionChanged_ = function() { if (this.selectedTab === null) { return; } var gridSource = this.gridSources['' + this.selectedTab]; this.updateFeatures_(gridSource); }; /** * @param {gmfx.GridSource} gridSource Grid source * @private */ gmf.DisplayquerygridController.prototype.updateFeatures_ = function(gridSource) { this.features_.clear(); this.highlightFeatures_.clear(); if (gridSource.configuration === null) { return; } var sourceId = '' + gridSource.source.id; var featuresForSource = this.featuresForSources_[sourceId]; var selectedRows = gridSource.configuration.selectedRows; for (var rowId in featuresForSource) { var feature = featuresForSource[rowId]; if (rowId in selectedRows) { this.highlightFeatures_.push(feature); } else { this.features_.push(feature); } } }; /** * Get the currently shown grid source. * @export * @return {gmfx.GridSource|null} Grid source. */ gmf.DisplayquerygridController.prototype.getActiveGridSource = function() { if (this.selectedTab === null) { return null; } else { return this.gridSources['' + this.selectedTab]; } }; /** * Returns if a row of the currently active grid is selected? * @export * @return {boolean} Is one selected? */ gmf.DisplayquerygridController.prototype.isOneSelected = function() { var source = this.getActiveGridSource(); if (source === null || source.configuration === null) { return false; } else { return source.configuration.getSelectedCount() > 0; } }; /** * Returns the number of selected rows of the currently active grid. * @export * @return {number} The number of selected rows. */ gmf.DisplayquerygridController.prototype.getSelectedRowCount = function() { var source = this.getActiveGridSource(); if (source === null || source.configuration === null) { return 0; } else { return source.configuration.getSelectedCount(); } }; /** * Select all rows of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.selectAll = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.selectAll(); } }; /** * Unselect all rows of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.unselectAll = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.unselectAll(); } }; /** * Invert the selection of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.invertSelection = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.invertSelection(); } }; /** * Zoom to the selected features. * @export */ gmf.DisplayquerygridController.prototype.zoomToSelection = function() { var source = this.getActiveGridSource(); if (source !== null) { var extent = ol.extent.createEmpty(); this.highlightFeatures_.forEach(function(feature) { ol.extent.extend(extent, feature.getGeometry().getExtent()); }); var mapSize = this.map_.getSize(); goog.asserts.assert(mapSize !== undefined); this.map_.getView().fit(extent, mapSize, {maxZoom: this.maxRecenterZoom}); } }; /** * Start a CSV download for the selected features. * @export */ gmf.DisplayquerygridController.prototype.downloadCsv = function() { var source = this.getActiveGridSource(); if (source !== null) { var columnDefs = source.configuration.columnDefs; goog.asserts.assert(columnDefs !== undefined); var selectedRows = source.configuration.getSelectedRows(); this.ngeoCsvDownload_.startDownload( selectedRows, columnDefs, 'query-results'); } }; gmf.module.controller('GmfDisplayquerygridController', gmf.DisplayquerygridController);
var expect = chai.expect; describe("sails", function() { beforeEach(function() { }); afterEach(function() { }); it('should not fail', function() { expect(true).to.be.true; }); });
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getContent(['issues', '1', '心智', '2', 'article.md'])。 * getCurrentIssue: 获取最新期刊号,无需参数。 * getAbstracts: 获取所有文章简介,需要提供期刊号。 */ class magazineStorage { /** * 建立新期刊instance. * @param {string} owner - github项目有所有者 * @param {string} repo - github项目名称 * @param {array} columns - 各子栏目列表 */ constructor(owner = 'Perspicere', repo = 'PerspicereContent', columns = ['心智', '此岸', '梦境']) { // github account settings this.owner = owner this.repo = repo // array of submodules this.columns = columns // grap window storage this.storage = window.sessionStorage // keys to be replaced with content this.urlReplace = ['img', 'image'] // github api this.baseURL = 'https://api.github.com/' // github api // github 禁止使用明文储存access token,此处使用加密token // 新生成token之后可以通过encrypt函数加密 // TODO: use OAuth? this.github = axios.create({ baseURL: this.baseURL, auth: { username: 'guoliu', password: decrypt( '6a1975233d2505057cfced9c0c847f9c99f97f8f54df8f4cd90d4d3949d8dff02afdac79c3dec4a9135fad4a474f8288' ) }, timeout: 10000 }) } // get content from local storage // 总数据大小如果超过5mb限制,需要优化存储 get content() { let content = this.storage.getItem('content') if (!content) { return {} } return JSON.parse(content) } // cache content to local storage set content(tree) { this.storage.setItem('content', JSON.stringify(tree)) } // get current issue number from local storage get currentIssue() { return this.storage.getItem('currentIssue') } // cache current issue number set currentIssue(issue) { this.storage.setItem('currentIssue', issue) } // locate leaf note in a tree static locateLeaf(tree, location) { if (location.length === 0) { return tree } try { return magazineStorage.locateLeaf(tree[location[0]], location.slice(1)) } catch (err) { return null } } // helper function to return tree with an extra leaf node static appendLeaf(tree, location, leaf) { if (location.length === 0) { return leaf } else if (!tree) { tree = {} } return { ...tree, [location[0]]: magazineStorage.appendLeaf(tree[location[0]], location.slice(1), leaf) } } // build url for image imageURL = location => `https://github.com/${this.owner}/${this.repo}/raw/master/${path.join(...location)}` // pull content from github with given path pullContent = async location => { try { const res = await this.github.get(`/repos/${this.owner}/${this.repo}/contents/${path.join(...location)}`) return res.data } catch (err) { console.warn(`Error pulling data from [${location.join(', ')}], null value will be returned instead`, err) return null } } // parse responce, returns an object parseData = data => { if (!data) { return null } // if we get an array, parse every element if (data.constructor === Array) { return data.reduce( (accumulated, current) => ({ ...accumulated, [current.name]: this.parseData(current) }), {} ) } if (data.content) { const ext = path.extname(data.path) const content = Base64.decode(data.content) // if it's a markdown file, parse it and get meta info if (ext === '.md') { const { attributes, body } = fm(content) // replace image paths const bodyWithUrl = body.replace( /(!\[.*?\]\()(.*)(\)\s)/, (_, prev, url, post) => `${prev}${this.imageURL([...data.path.split('/').slice(0, -1), url])}${post}` ) return { ...attributes, body: bodyWithUrl } } if (ext === '.json') { // if it's a json, parse it return JSON.parse(content) } return content } if (data.type === 'dir') { // if we get a directory return {} } return null } /** * 调用期刊内容. * @param {string} location - 内容位置,描述目标文档位置。例如第1期“心智”子栏目中第2篇文章正文:['issues', '1', '心智', '2', 'article.md']。 * @return {object} 目标内容 */ getContent = async location => { // 尝试从本地获取 let contentNode = magazineStorage.locateLeaf(this.content, location) || {} // 本地无值,从远程调用 if (contentNode.constructor === Object && Object.keys(contentNode).length === 0) { const data = await this.pullContent(location) contentNode = this.parseData(data) // 将json中路径替换为url,例如图片 if (contentNode && contentNode.constructor === Object && Object.keys(contentNode).length > 0) { const URLkeys = Object.keys(contentNode).filter(field => this.urlReplace.includes(field)) const URLs = URLkeys.map(key => this.imageURL([...location.slice(0, -1), contentNode[key]])) contentNode = { ...contentNode, ...zipObject(URLkeys, URLs) } } this.content = magazineStorage.appendLeaf(this.content, location, contentNode) } return contentNode } /** * 获取最新期刊号。 * @return {int} 最新期刊号。 */ getCurrentIssue = async () => { if (!this.currentIssue) { const data = await this.getContent(['issues']) this.currentIssue = Object.keys(data) .filter( entry => data[entry] && data[entry].constructor === Object // is a directory ) .reduce((a, b) => Math.max(parseInt(a), parseInt(b))) } return this.currentIssue } /** * 获取期刊所有文章简介。 * @param {int} issue - 期刊号。 * @return {object} 该期所有文章简介。 */ getIssueAbstract = async issue => { // 默认获取最新一期 let issueNumber = issue if (!issue) { issueNumber = await this.getCurrentIssue() } const issueContent = await Promise.all( this.columns.map(async column => { // 栏目文章列表 const articleList = Object.keys(await this.getContent(['issues', issueNumber, column])) // 各文章元信息 const columnContent = await Promise.all( articleList.map(article => this.getContent(['issues', issueNumber, column, article, 'article.md'])) ) return zipObject(articleList, columnContent) }) ) // 本期信息 const meta = await this.getContent(['issues', issueNumber, 'meta.json']) return { ...meta, content: zipObject(this.columns, issueContent) } } /** * 获取期刊所有单篇文章。 * @return {object} 所有单篇文章。 * TODO: 仅返回一定数量各子栏目最新文章 */ getArticleAbstract = async () => { // 各栏目 const articlesContent = await Promise.all( this.columns.map(async column => { // 栏目文章列表 const articleList = Object.keys((await this.getContent(['articles', column])) || {}) // 各文章元信息 const columnContent = await Promise.all( articleList.map(article => this.getContent(['articles', column, article, 'article.md'])) ) return zipObject(articleList, columnContent) }) ) return zipObject(this.columns, articlesContent) } } export default new magazineStorage()
export default { navigator: { doc: 'Docs', demo: 'Demo', started: 'Get Started' }, features: { userExperience: { title: 'Optimize Experience', desc: 'To make scroll more smoothly, We support flexible configurations about inertial scrolling, rebound, fade scrollbar, etc. which could optimize user experience obviously.' }, application: { title: 'Rich Features', desc: 'It can be applied to normal scroll list, picker, slide, index list, start guidance, etc. What\'s more, some complicated needs like pull down refresh and pull up load can be implemented much easier.' }, dependence: { title: 'Dependence Free', desc: 'As a plain JavaScript library, BetterScroll doesn\'t depend on any framework, you could use it alone, or with any other MVVM frameworks.' } }, examples: { normalScrollList: 'Normal Scroll List', indexList: 'Index List', picker: 'Picker', slide: 'Slide', startGuidance: 'Start Guidance', freeScroll: 'Free Scroll', formList: 'Form List', verticalScrollImg: 'vertical-scroll-en.jpeg', indexListImg: 'index-list.jpeg', pickerImg: 'picker-en.jpeg', slideImg: 'slide.jpeg', startGuidanceImg: 'full-page-slide.jpeg', freeScrollImg: 'free-scroll.jpeg', formListImg: 'form-list-en.jpeg' }, normalScrollListPage: { desc: 'Nomal scroll list based on BetterScroll', scrollbar: 'Scrollbar', pullDownRefresh: 'Pull Down Refresh', pullUpLoad: 'Pull Up Load', previousTxt: 'I am the No.', followingTxt: ' line', newDataTxt: 'I am new data: ' }, scrollComponent: { defaultLoadTxtMore: 'Load more', defaultLoadTxtNoMore: 'There is no more data', defaultRefreshTxt: 'Refresh success' }, indexListPage: { title: 'Current City: Beijing' }, pickerPage: { desc: 'Picker is a typical choose component at mobile end. And it could dynamic change the data of every column to realize linkage picker.', picker: ' picker', pickerDemo: ' picker demo ...', oneColumn: 'One column', twoColumn: 'Two column', threeColumn: 'Three column', linkage: 'Linkage', confirmTxt: 'confirm | ok', cancelTxt: 'cancel | close' }, slidePage: { desc: 'Slide is a typical component at mobile end, support horizontal move.' }, fullPageSlideComponent: { buttonTxt: 'Start Use' }, freeScrollPage: { desc: 'Free scroll supports horizontal and vertical move at the same time.' }, formListPage: { desc: 'To use form in better-scroll, you need to make sure the option click is configured as false, since some native element events will be prevented when click is true. And in this situation, we recommend to handle click by listening tap event.', previousTxt: 'No.', followingTxt: ' option' } }
/* @flow */ import assert from 'assert'; import { CONVERSION_TABLE } from './06-export'; import type { Unit, UnitValue } from './06-export'; // We didn't cover any edge cases yet, so let's do this now export function convertUnit(from: Unit, to: Unit, value: number): ?number { if (from === to) { return value; } // If there is no conversion possible, return null // Note how we are using '== null' instead of '=== null' // because the first notation will cover both cases, 'null' // and 'undefined', which spares us a lot of extra code. // You will need to set eslint's 'eqeqeq' rule to '[2, "smart"]' if (CONVERSION_TABLE[from] == null || CONVERSION_TABLE[from][to] == null) { return null; } const transform = CONVERSION_TABLE[from][to]; return transform(value); } // Intersection Type for assuming unit to be 'm' // unit cannot be anything but a `Unit`, so we even // prevent errors on definition type MeterUnitValue = { unit: 'm' } & UnitValue; // Convert whole UnitValues instead of single values function convertToKm(unitValue: MeterUnitValue): ?UnitValue { const { unit, value } = unitValue; const converted = convertUnit(unit, 'km', value); if (converted == null) { return null; } return { unit: 'km', value: converted, } } const value = convertToKm({ unit: 'm', value: 1500 }); assert.deepEqual(value, { unit: 'km', value: 1.5 });
$(document).ready(function () { // add classes to check boxes $('#id_notify_at_threshold').addClass('form-control'); $('#id_in_live_deal').addClass('form-control'); $('#id_is_subscription').addClass('form-control'); });
import React, { Component } from 'react'; export default React.createClass({ getInitialState: function () { return { title: '', body: '' }; }, handleChangeTitle: function (e) { this.setState({ title: e.target.value }); }, handleChangeBody: function (e) { this.setState({ body: e.target.value }); }, handleSubmit: function (e) { e.preventDefault(); this.props.addPost(this.state); }, render() { return ( <div> <h3>New post</h3> <form onSubmit={this.handleSubmit}> <input type="text" placeholder="sdfsd" value={this.title} placeholder="title" onChange={this.handleChangeTitle} /> <br /> <textarea type="text" placeholder="sdfsd" placeholder="body" onChange={this.handleChangeBody} > {this.body} </textarea> <button>Submit</button> </form> </div> ); }, });
export default { '/': { component: require('./components/NowPlayingView'), name: 'NowPlaying' } }
/** Copyright (c) 2007 Bill Orcutt (http://lilyapp.org, http://publicbeta.cx) 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. */ /** * Construct a new color object * @class * @constructor * @extends LilyObjectBase */ function $color(arg) { var thisPtr=this; var websafe=arg||false; this.outlet1 = new this.outletClass("outlet1",this,"random color in hexadecimal"); this.inlet1=new this.inletClass("inlet1",this,"\"bang\" outputs random color"); // getRandomColor() // Returns a random hex color. Passing true for safe returns a web safe color //code hijacked from http://www.scottandrew.com/js/js_util.js function getRandomColor(safe) { var vals,r,n; if (safe) { v = "0369CF"; n = 3; } else { v = "0123456789ABCDEF"; n = 6; } var c = "#"; for (var i=0;i<n;i++) { var ch = v.charAt(Math.round(Math.random() * (v.length-1))); c += (safe)?ch+ch:ch; } return c; } function RGBtoHex(R,G,B) { return toHex(R)+toHex(G)+toHex(B); } function toHex(N) { if (N==null) return "00"; N=parseInt(N); if (N==0 || isNaN(N)) return "00"; N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N); return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16); } function HSLtoRGB (h,s,l) { if (s == 0) return [l,l,l] // achromatic h=h*360/255;s/=255;l/=255; if (l <= 0.5) rm2 = l + l * s; else rm2 = l + s - l * s; rm1 = 2.0 * l - rm2; return [toRGB1(rm1, rm2, h + 120.0),toRGB1(rm1, rm2, h),toRGB1(rm1, rm2, h - 120.0)]; } function toRGB1(rm1,rm2,rh) { if (rh > 360.0) rh -= 360.0; else if (rh < 0.0) rh += 360.0; if (rh < 60.0) rm1 = rm1 + (rm2 - rm1) * rh / 60.0; else if (rh < 180.0) rm1 = rm2; else if (rh < 240.0) rm1 = rm1 + (rm2 - rm1) * (240.0 - rh) / 60.0; return Math.round(rm1 * 255); } //output random color this.inlet1["random"]=function() { thisPtr.outlet1.doOutlet(getRandomColor(websafe)); } //convert RGB to hex this.inlet1["RGBtoHEX"]=function(rgb) { var tmp = rgb.split(" "); thisPtr.outlet1.doOutlet("#"+RGBtoHex(tmp[0],tmp[1],tmp[2])); } //convert HSL to hex this.inlet1["HSLtoHEX"]=function(hsl) { var tmp = hsl.split(" "); var rgb = HSLtoRGB(tmp[0],tmp[1],tmp[2]); thisPtr.outlet1.doOutlet("#"+RGBtoHex(rgb[0],rgb[1],rgb[2])); } return this; } var $colorMetaData = { textName:"color", htmlName:"color", objectCategory:"Math", objectSummary:"Various color related utilities", objectArguments:"websafe colors only [false]" }
Ext.provide('Phlexible.users.UserWindow'); Ext.require('Ext.ux.TabPanel'); Phlexible.users.UserWindow = Ext.extend(Ext.Window, { title: Phlexible.users.Strings.user, strings: Phlexible.users.Strings, plain: true, iconCls: 'p-user-user-icon', width: 530, minWidth: 530, height: 400, minHeight: 400, layout: 'fit', border: false, modal: true, initComponent: function () { this.addEvents( 'save' ); var panels = Phlexible.PluginRegistry.get('userEditPanels'); this.items = [{ xtype: 'uxtabpanel', tabPosition: 'left', tabStripWidth: 150, activeTab: 0, border: true, deferredRender: false, items: panels }]; this.tbar = new Ext.Toolbar({ hidden: true, cls: 'p-users-disabled', items: [ '->', { iconCls: 'p-user-user_account-icon', text: this.strings.account_is_disabled, handler: function () { this.getComponent(0).setActiveTab(4); }, scope: this }] }); this.buttons = [ { text: this.strings.cancel, handler: this.close, scope: this }, { text: this.strings.save, iconCls: 'p-user-save-icon', handler: this.save, scope: this } ]; Phlexible.users.UserWindow.superclass.initComponent.call(this); }, show: function (user) { this.user = user; if (user.get('username')) { this.setTitle(this.strings.user + ' "' + user.get('username') + '"'); } else { this.setTitle(this.strings.new_user); } Phlexible.users.UserWindow.superclass.show.call(this); this.getComponent(0).items.each(function(p) { if (typeof p.loadUser === 'function') { p.loadUser(user); } }); if (!user.get('enabled')) { this.getTopToolbar().show(); } }, save: function () { var data = {}; var valid = true; this.getComponent(0).items.each(function(p) { if (typeof p.isValid === 'function' && typeof p.getData === 'function') { if (p.isValid()) { Ext.apply(data, p.getData()); } else { valid = false; } } }); if (!valid) { return; } var url, method; if (this.user.get('uid')) { url = Phlexible.Router.generate('users_users_update', {userId: this.user.get('uid')}); method = 'PUT'; } else { url = Phlexible.Router.generate('users_users_create'); method = 'POST'; } Ext.Ajax.request({ url: url, method: method, params: data, success: this.onSaveSuccess, scope: this }); }, onSaveSuccess: function (response) { var data = Ext.decode(response.responseText); if (data.success) { this.uid = data.uid; Phlexible.success(data.msg); this.fireEvent('save', this.uid); this.close(); } else { Ext.Msg.alert('Failure', data.msg); } } });
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.7.21 "undefined" == typeof WeakMap && !function () { var e = Object.defineProperty, t = Date.now() % 1e9, n = function () { this.name = "__st" + (1e9 * Math.random() >>> 0) + (t++ + "__") }; n.prototype = { set: function (t, n) { var r = t[this.name]; return r && r[0] === t ? r[1] = n : e(t, this.name, {value: [t, n], writable: !0}), this }, get: function (e) { var t; return (t = e[this.name]) && t[0] === e ? t[1] : void 0 }, "delete": function (e) { var t = e[this.name]; return t && t[0] === e ? (t[0] = t[1] = void 0, !0) : !1 }, has: function (e) { var t = e[this.name]; return t ? t[0] === e : !1 } }, window.WeakMap = n }(), window.ShadowDOMPolyfill = {}, function (e) { "use strict"; function t() { if ("undefined" != typeof chrome && chrome.app && chrome.app.runtime)return !1; if (navigator.getDeviceStorage)return !1; try { var e = new Function("return true;"); return e() } catch (t) { return !1 } } function n(e) { if (!e)throw new Error("Assertion failed") } function r(e, t) { for (var n = k(t), r = 0; r < n.length; r++) { var o = n[r]; A(e, o, F(t, o)) } return e } function o(e, t) { for (var n = k(t), r = 0; r < n.length; r++) { var o = n[r]; switch (o) { case"arguments": case"caller": case"length": case"name": case"prototype": case"toString": continue } A(e, o, F(t, o)) } return e } function i(e, t) { for (var n = 0; n < t.length; n++)if (t[n] in e)return t[n] } function a(e, t, n) { B.value = n, A(e, t, B) } function s(e, t) { var n = e.__proto__ || Object.getPrototypeOf(e); if (U)try { k(n) } catch (r) { n = n.__proto__ } var o = R.get(n); if (o)return o; var i = s(n), a = E(i); return v(n, a, t), a } function c(e, t) { m(e, t, !0) } function u(e, t) { m(t, e, !1) } function l(e) { return /^on[a-z]+$/.test(e) } function p(e) { return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e) } function d(e) { return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e) : function () { return this.__impl4cf1e782hg__[e] } } function f(e) { return I && p(e) ? new Function("v", "this.__impl4cf1e782hg__." + e + " = v") : function (t) { this.__impl4cf1e782hg__[e] = t } } function h(e) { return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e + ".apply(this.__impl4cf1e782hg__, arguments)") : function () { return this.__impl4cf1e782hg__[e].apply(this.__impl4cf1e782hg__, arguments) } } function w(e, t) { try { return Object.getOwnPropertyDescriptor(e, t) } catch (n) { return q } } function m(t, n, r, o) { for (var i = k(t), a = 0; a < i.length; a++) { var s = i[a]; if ("polymerBlackList_" !== s && !(s in n || t.polymerBlackList_ && t.polymerBlackList_[s])) { U && t.__lookupGetter__(s); var c, u, p = w(t, s); if ("function" != typeof p.value) { var m = l(s); c = m ? e.getEventHandlerGetter(s) : d(s), (p.writable || p.set || V) && (u = m ? e.getEventHandlerSetter(s) : f(s)); var g = V || p.configurable; A(n, s, {get: c, set: u, configurable: g, enumerable: p.enumerable}) } else r && (n[s] = h(s)) } } } function g(e, t, n) { if (null != e) { var r = e.prototype; v(r, t, n), o(t, e) } } function v(e, t, r) { var o = t.prototype; n(void 0 === R.get(e)), R.set(e, t), P.set(o, e), c(e, o), r && u(o, r), a(o, "constructor", t), t.prototype = o } function b(e, t) { return R.get(t.prototype) === e } function y(e) { var t = Object.getPrototypeOf(e), n = s(t), r = E(n); return v(t, r, e), r } function E(e) { function t(t) { e.call(this, t) } var n = Object.create(e.prototype); return n.constructor = t, t.prototype = n, t } function S(e) { return e && e.__impl4cf1e782hg__ } function M(e) { return !S(e) } function T(e) { if (null === e)return null; n(M(e)); var t = e.__wrapper8e3dd93a60__; return null != t ? t : e.__wrapper8e3dd93a60__ = new (s(e, e))(e) } function O(e) { return null === e ? null : (n(S(e)), e.__impl4cf1e782hg__) } function N(e) { return e.__impl4cf1e782hg__ } function j(e, t) { t.__impl4cf1e782hg__ = e, e.__wrapper8e3dd93a60__ = t } function L(e) { return e && S(e) ? O(e) : e } function _(e) { return e && !S(e) ? T(e) : e } function D(e, t) { null !== t && (n(M(e)), n(void 0 === t || S(t)), e.__wrapper8e3dd93a60__ = t) } function C(e, t, n) { G.get = n, A(e.prototype, t, G) } function H(e, t) { C(e, t, function () { return T(this.__impl4cf1e782hg__[t]) }) } function x(e, t) { e.forEach(function (e) { t.forEach(function (t) { e.prototype[t] = function () { var e = _(this); return e[t].apply(e, arguments) } }) }) } var R = new WeakMap, P = new WeakMap, W = Object.create(null), I = t(), A = Object.defineProperty, k = Object.getOwnPropertyNames, F = Object.getOwnPropertyDescriptor, B = { value: void 0, configurable: !0, enumerable: !1, writable: !0 }; k(window); var U = /Firefox/.test(navigator.userAgent), q = { get: function () { }, set: function (e) { }, configurable: !0, enumerable: !0 }, V = function () { var e = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType"); return e && !e.get && !e.set }(), G = {get: void 0, configurable: !0, enumerable: !0}; e.addForwardingProperties = c, e.assert = n, e.constructorTable = R, e.defineGetter = C, e.defineWrapGetter = H, e.forwardMethodsToWrapper = x, e.isIdentifierName = p, e.isWrapper = S, e.isWrapperFor = b, e.mixin = r, e.nativePrototypeTable = P, e.oneOf = i, e.registerObject = y, e.registerWrapper = g, e.rewrap = D, e.setWrapper = j, e.unsafeUnwrap = N, e.unwrap = O, e.unwrapIfNeeded = L, e.wrap = T, e.wrapIfNeeded = _, e.wrappers = W }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t, n) { return {index: e, removed: t, addedCount: n} } function n() { } var r = 0, o = 1, i = 2, a = 3; n.prototype = { calcEditDistances: function (e, t, n, r, o, i) { for (var a = i - o + 1, s = n - t + 1, c = new Array(a), u = 0; a > u; u++)c[u] = new Array(s), c[u][0] = u; for (var l = 0; s > l; l++)c[0][l] = l; for (var u = 1; a > u; u++)for (var l = 1; s > l; l++)if (this.equals(e[t + l - 1], r[o + u - 1]))c[u][l] = c[u - 1][l - 1]; else { var p = c[u - 1][l] + 1, d = c[u][l - 1] + 1; c[u][l] = d > p ? p : d } return c }, spliceOperationsFromEditDistances: function (e) { for (var t = e.length - 1, n = e[0].length - 1, s = e[t][n], c = []; t > 0 || n > 0;)if (0 != t)if (0 != n) { var u, l = e[t - 1][n - 1], p = e[t - 1][n], d = e[t][n - 1]; u = d > p ? l > p ? p : l : l > d ? d : l, u == l ? (l == s ? c.push(r) : (c.push(o), s = l), t--, n--) : u == p ? (c.push(a), t--, s = p) : (c.push(i), n--, s = d) } else c.push(a), t--; else c.push(i), n--; return c.reverse(), c }, calcSplices: function (e, n, s, c, u, l) { var p = 0, d = 0, f = Math.min(s - n, l - u); if (0 == n && 0 == u && (p = this.sharedPrefix(e, c, f)), s == e.length && l == c.length && (d = this.sharedSuffix(e, c, f - p)), n += p, u += p, s -= d, l -= d, s - n == 0 && l - u == 0)return []; if (n == s) { for (var h = t(n, [], 0); l > u;)h.removed.push(c[u++]); return [h] } if (u == l)return [t(n, [], s - n)]; for (var w = this.spliceOperationsFromEditDistances(this.calcEditDistances(e, n, s, c, u, l)), h = void 0, m = [], g = n, v = u, b = 0; b < w.length; b++)switch (w[b]) { case r: h && (m.push(h), h = void 0), g++, v++; break; case o: h || (h = t(g, [], 0)), h.addedCount++, g++, h.removed.push(c[v]), v++; break; case i: h || (h = t(g, [], 0)), h.addedCount++, g++; break; case a: h || (h = t(g, [], 0)), h.removed.push(c[v]), v++ } return h && m.push(h), m }, sharedPrefix: function (e, t, n) { for (var r = 0; n > r; r++)if (!this.equals(e[r], t[r]))return r; return n }, sharedSuffix: function (e, t, n) { for (var r = e.length, o = t.length, i = 0; n > i && this.equals(e[--r], t[--o]);)i++; return i }, calculateSplices: function (e, t) { return this.calcSplices(e, 0, e.length, t, 0, t.length) }, equals: function (e, t) { return e === t } }, e.ArraySplice = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t() { a = !1; var e = i.slice(0); i = []; for (var t = 0; t < e.length; t++)(0, e[t])() } function n(e) { i.push(e), a || (a = !0, r(t, 0)) } var r, o = window.MutationObserver, i = [], a = !1; if (o) { var s = 1, c = new o(t), u = document.createTextNode(s); c.observe(u, {characterData: !0}), r = function () { s = (s + 1) % 2, u.data = s } } else r = window.setTimeout; e.setEndOfMicrotask = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { e.scheduled_ || (e.scheduled_ = !0, h.push(e), w || (l(n), w = !0)) } function n() { for (w = !1; h.length;) { var e = h; h = [], e.sort(function (e, t) { return e.uid_ - t.uid_ }); for (var t = 0; t < e.length; t++) { var n = e[t]; n.scheduled_ = !1; var r = n.takeRecords(); i(n), r.length && n.callback_(r, n) } } } function r(e, t) { this.type = e, this.target = t, this.addedNodes = new d.NodeList, this.removedNodes = new d.NodeList, this.previousSibling = null, this.nextSibling = null, this.attributeName = null, this.attributeNamespace = null, this.oldValue = null } function o(e, t) { for (; e; e = e.parentNode) { var n = f.get(e); if (n)for (var r = 0; r < n.length; r++) { var o = n[r]; o.options.subtree && o.addTransientObserver(t) } } } function i(e) { for (var t = 0; t < e.nodes_.length; t++) { var n = e.nodes_[t], r = f.get(n); if (!r)return; for (var o = 0; o < r.length; o++) { var i = r[o]; i.observer === e && i.removeTransientObservers() } } } function a(e, n, o) { for (var i = Object.create(null), a = Object.create(null), s = e; s; s = s.parentNode) { var c = f.get(s); if (c)for (var u = 0; u < c.length; u++) { var l = c[u], p = l.options; if ((s === e || p.subtree) && ("attributes" !== n || p.attributes) && ("attributes" !== n || !p.attributeFilter || null === o.namespace && -1 !== p.attributeFilter.indexOf(o.name)) && ("characterData" !== n || p.characterData) && ("childList" !== n || p.childList)) { var d = l.observer; i[d.uid_] = d, ("attributes" === n && p.attributeOldValue || "characterData" === n && p.characterDataOldValue) && (a[d.uid_] = o.oldValue) } } } for (var h in i) { var d = i[h], w = new r(n, e); "name" in o && "namespace" in o && (w.attributeName = o.name, w.attributeNamespace = o.namespace), o.addedNodes && (w.addedNodes = o.addedNodes), o.removedNodes && (w.removedNodes = o.removedNodes), o.previousSibling && (w.previousSibling = o.previousSibling), o.nextSibling && (w.nextSibling = o.nextSibling), void 0 !== a[h] && (w.oldValue = a[h]), t(d), d.records_.push(w) } } function s(e) { if (this.childList = !!e.childList, this.subtree = !!e.subtree, "attributes" in e || !("attributeOldValue" in e || "attributeFilter" in e) ? this.attributes = !!e.attributes : this.attributes = !0, "characterDataOldValue" in e && !("characterData" in e) ? this.characterData = !0 : this.characterData = !!e.characterData, !this.attributes && (e.attributeOldValue || "attributeFilter" in e) || !this.characterData && e.characterDataOldValue)throw new TypeError; if (this.characterData = !!e.characterData, this.attributeOldValue = !!e.attributeOldValue, this.characterDataOldValue = !!e.characterDataOldValue, "attributeFilter" in e) { if (null == e.attributeFilter || "object" != typeof e.attributeFilter)throw new TypeError; this.attributeFilter = m.call(e.attributeFilter) } else this.attributeFilter = null } function c(e) { this.callback_ = e, this.nodes_ = [], this.records_ = [], this.uid_ = ++g, this.scheduled_ = !1 } function u(e, t, n) { this.observer = e, this.target = t, this.options = n, this.transientObservedNodes = [] } var l = e.setEndOfMicrotask, p = e.wrapIfNeeded, d = e.wrappers, f = new WeakMap, h = [], w = !1, m = Array.prototype.slice, g = 0; c.prototype = { constructor: c, observe: function (e, t) { e = p(e); var n, r = new s(t), o = f.get(e); o || f.set(e, o = []); for (var i = 0; i < o.length; i++)o[i].observer === this && (n = o[i], n.removeTransientObservers(), n.options = r); n || (n = new u(this, e, r), o.push(n), this.nodes_.push(e)) }, disconnect: function () { this.nodes_.forEach(function (e) { for (var t = f.get(e), n = 0; n < t.length; n++) { var r = t[n]; if (r.observer === this) { t.splice(n, 1); break } } }, this), this.records_ = [] }, takeRecords: function () { var e = this.records_; return this.records_ = [], e } }, u.prototype = { addTransientObserver: function (e) { if (e !== this.target) { t(this.observer), this.transientObservedNodes.push(e); var n = f.get(e); n || f.set(e, n = []), n.push(this) } }, removeTransientObservers: function () { var e = this.transientObservedNodes; this.transientObservedNodes = []; for (var t = 0; t < e.length; t++)for (var n = e[t], r = f.get(n), o = 0; o < r.length; o++)if (r[o] === this) { r.splice(o, 1); break } } }, e.enqueueMutation = a, e.registerTransientObservers = o, e.wrappers.MutationObserver = c, e.wrappers.MutationRecord = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { this.root = e, this.parent = t } function n(e, t) { if (e.treeScope_ !== t) { e.treeScope_ = t; for (var r = e.shadowRoot; r; r = r.olderShadowRoot)r.treeScope_.parent = t; for (var o = e.firstChild; o; o = o.nextSibling)n(o, t) } } function r(n) { if (n instanceof e.wrappers.Window, n.treeScope_)return n.treeScope_; var o, i = n.parentNode; return o = i ? r(i) : new t(n, null), n.treeScope_ = o } t.prototype = { get renderer() { return this.root instanceof e.wrappers.ShadowRoot ? e.getRendererForHost(this.root.host) : null }, contains: function (e) { for (; e; e = e.parent)if (e === this)return !0; return !1 } }, e.TreeScope = t, e.getTreeScope = r, e.setTreeScope = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e instanceof G.ShadowRoot } function n(e) { return A(e).root } function r(e, r) { var s = [], c = e; for (s.push(c); c;) { var u = a(c); if (u && u.length > 0) { for (var l = 0; l < u.length; l++) { var d = u[l]; if (i(d)) { var f = n(d), h = f.olderShadowRoot; h && s.push(h) } s.push(d) } c = u[u.length - 1] } else if (t(c)) { if (p(e, c) && o(r))break; c = c.host, s.push(c) } else c = c.parentNode, c && s.push(c) } return s } function o(e) { if (!e)return !1; switch (e.type) { case"abort": case"error": case"select": case"change": case"load": case"reset": case"resize": case"scroll": case"selectstart": return !0 } return !1 } function i(e) { return e instanceof HTMLShadowElement } function a(t) { return e.getDestinationInsertionPoints(t) } function s(e, t) { if (0 === e.length)return t; t instanceof G.Window && (t = t.document); for (var n = A(t), r = e[0], o = A(r), i = u(n, o), a = 0; a < e.length; a++) { var s = e[a]; if (A(s) === i)return s } return e[e.length - 1] } function c(e) { for (var t = []; e; e = e.parent)t.push(e); return t } function u(e, t) { for (var n = c(e), r = c(t), o = null; n.length > 0 && r.length > 0;) { var i = n.pop(), a = r.pop(); if (i !== a)break; o = i } return o } function l(e, t, n) { t instanceof G.Window && (t = t.document); var o, i = A(t), a = A(n), s = r(n, e), o = u(i, a); o || (o = a.root); for (var c = o; c; c = c.parent)for (var l = 0; l < s.length; l++) { var p = s[l]; if (A(p) === c)return p } return null } function p(e, t) { return A(e) === A(t) } function d(e) { if (!X.get(e) && (X.set(e, !0), h(V(e), V(e.target)), W)) { var t = W; throw W = null, t } } function f(e) { switch (e.type) { case"load": case"beforeunload": case"unload": return !0 } return !1 } function h(t, n) { if (K.get(t))throw new Error("InvalidStateError"); K.set(t, !0), e.renderAllPending(); var o, i, a; if (f(t) && !t.bubbles) { var s = n; s instanceof G.Document && (a = s.defaultView) && (i = s, o = []) } if (!o)if (n instanceof G.Window)a = n, o = []; else if (o = r(n, t), !f(t)) { var s = o[o.length - 1]; s instanceof G.Document && (a = s.defaultView) } return ne.set(t, o), w(t, o, a, i) && m(t, o, a, i) && g(t, o, a, i), J.set(t, re), $["delete"](t, null), K["delete"](t), t.defaultPrevented } function w(e, t, n, r) { var o = oe; if (n && !v(n, e, o, t, r))return !1; for (var i = t.length - 1; i > 0; i--)if (!v(t[i], e, o, t, r))return !1; return !0 } function m(e, t, n, r) { var o = ie, i = t[0] || n; return v(i, e, o, t, r) } function g(e, t, n, r) { for (var o = ae, i = 1; i < t.length; i++)if (!v(t[i], e, o, t, r))return; n && t.length > 0 && v(n, e, o, t, r) } function v(e, t, n, r, o) { var i = z.get(e); if (!i)return !0; var a = o || s(r, e); if (a === e) { if (n === oe)return !0; n === ae && (n = ie) } else if (n === ae && !t.bubbles)return !0; if ("relatedTarget" in t) { var c = q(t), u = c.relatedTarget; if (u) { if (u instanceof Object && u.addEventListener) { var p = V(u), d = l(t, e, p); if (d === a)return !0 } else d = null; Z.set(t, d) } } J.set(t, n); var f = t.type, h = !1; Y.set(t, a), $.set(t, e), i.depth++; for (var w = 0, m = i.length; m > w; w++) { var g = i[w]; if (g.removed)h = !0; else if (!(g.type !== f || !g.capture && n === oe || g.capture && n === ae))try { if ("function" == typeof g.handler ? g.handler.call(e, t) : g.handler.handleEvent(t), ee.get(t))return !1 } catch (v) { W || (W = v) } } if (i.depth--, h && 0 === i.depth) { var b = i.slice(); i.length = 0; for (var w = 0; w < b.length; w++)b[w].removed || i.push(b[w]) } return !Q.get(t) } function b(e, t, n) { this.type = e, this.handler = t, this.capture = Boolean(n) } function y(e, t) { if (!(e instanceof se))return V(T(se, "Event", e, t)); var n = e; return be || "beforeunload" !== n.type || this instanceof O ? void B(n, this) : new O(n) } function E(e) { return e && e.relatedTarget ? Object.create(e, {relatedTarget: {value: q(e.relatedTarget)}}) : e } function S(e, t, n) { var r = window[e], o = function (t, n) { return t instanceof r ? void B(t, this) : V(T(r, e, t, n)) }; if (o.prototype = Object.create(t.prototype), n && k(o.prototype, n), r)try { F(r, o, new r("temp")) } catch (i) { F(r, o, document.createEvent(e)) } return o } function M(e, t) { return function () { arguments[t] = q(arguments[t]); var n = q(this); n[e].apply(n, arguments) } } function T(e, t, n, r) { if (ge)return new e(n, E(r)); var o = q(document.createEvent(t)), i = me[t], a = [n]; return Object.keys(i).forEach(function (e) { var t = null != r && e in r ? r[e] : i[e]; "relatedTarget" === e && (t = q(t)), a.push(t) }), o["init" + t].apply(o, a), o } function O(e) { y.call(this, e) } function N(e) { return "function" == typeof e ? !0 : e && e.handleEvent } function j(e) { switch (e) { case"DOMAttrModified": case"DOMAttributeNameChanged": case"DOMCharacterDataModified": case"DOMElementNameChanged": case"DOMNodeInserted": case"DOMNodeInsertedIntoDocument": case"DOMNodeRemoved": case"DOMNodeRemovedFromDocument": case"DOMSubtreeModified": return !0 } return !1 } function L(e) { B(e, this) } function _(e) { return e instanceof G.ShadowRoot && (e = e.host), q(e) } function D(e, t) { var n = z.get(e); if (n)for (var r = 0; r < n.length; r++)if (!n[r].removed && n[r].type === t)return !0; return !1 } function C(e, t) { for (var n = q(e); n; n = n.parentNode)if (D(V(n), t))return !0; return !1 } function H(e) { I(e, Ee) } function x(t, n, o, i) { e.renderAllPending(); var a = V(Se.call(U(n), o, i)); if (!a)return null; var c = r(a, null), u = c.lastIndexOf(t); return -1 == u ? null : (c = c.slice(0, u), s(c, t)) } function R(e) { return function () { var t = te.get(this); return t && t[e] && t[e].value || null } } function P(e) { var t = e.slice(2); return function (n) { var r = te.get(this); r || (r = Object.create(null), te.set(this, r)); var o = r[e]; if (o && this.removeEventListener(t, o.wrapped, !1), "function" == typeof n) { var i = function (t) { var r = n.call(this, t); r === !1 ? t.preventDefault() : "onbeforeunload" === e && "string" == typeof r && (t.returnValue = r) }; this.addEventListener(t, i, !1), r[e] = {value: n, wrapped: i} } } } var W, I = e.forwardMethodsToWrapper, A = e.getTreeScope, k = e.mixin, F = e.registerWrapper, B = e.setWrapper, U = e.unsafeUnwrap, q = e.unwrap, V = e.wrap, G = e.wrappers, z = (new WeakMap, new WeakMap), X = new WeakMap, K = new WeakMap, Y = new WeakMap, $ = new WeakMap, Z = new WeakMap, J = new WeakMap, Q = new WeakMap, ee = new WeakMap, te = new WeakMap, ne = new WeakMap, re = 0, oe = 1, ie = 2, ae = 3; b.prototype = { equals: function (e) { return this.handler === e.handler && this.type === e.type && this.capture === e.capture }, get removed() { return null === this.handler }, remove: function () { this.handler = null } }; var se = window.Event; se.prototype.polymerBlackList_ = {returnValue: !0, keyLocation: !0}, y.prototype = { get target() { return Y.get(this) }, get currentTarget() { return $.get(this) }, get eventPhase() { return J.get(this) }, get path() { var e = ne.get(this); return e ? e.slice() : [] }, stopPropagation: function () { Q.set(this, !0) }, stopImmediatePropagation: function () { Q.set(this, !0), ee.set(this, !0) } }; var ce = function () { var e = document.createEvent("Event"); return e.initEvent("test", !0, !0), e.preventDefault(), e.defaultPrevented }(); ce || (y.prototype.preventDefault = function () { this.cancelable && (U(this).preventDefault(), Object.defineProperty(this, "defaultPrevented", { get: function () { return !0 }, configurable: !0 })) }), F(se, y, document.createEvent("Event")); var ue = S("UIEvent", y), le = S("CustomEvent", y), pe = { get relatedTarget() { var e = Z.get(this); return void 0 !== e ? e : V(q(this).relatedTarget) } }, de = k({initMouseEvent: M("initMouseEvent", 14)}, pe), fe = k({initFocusEvent: M("initFocusEvent", 5)}, pe), he = S("MouseEvent", ue, de), we = S("FocusEvent", ue, fe), me = Object.create(null), ge = function () { try { new window.FocusEvent("focus") } catch (e) { return !1 } return !0 }(); if (!ge) { var ve = function (e, t, n) { if (n) { var r = me[n]; t = k(k({}, r), t) } me[e] = t }; ve("Event", { bubbles: !1, cancelable: !1 }), ve("CustomEvent", {detail: null}, "Event"), ve("UIEvent", { view: null, detail: 0 }, "Event"), ve("MouseEvent", { screenX: 0, screenY: 0, clientX: 0, clientY: 0, ctrlKey: !1, altKey: !1, shiftKey: !1, metaKey: !1, button: 0, relatedTarget: null }, "UIEvent"), ve("FocusEvent", {relatedTarget: null}, "UIEvent") } var be = window.BeforeUnloadEvent; O.prototype = Object.create(y.prototype), k(O.prototype, { get returnValue() { return U(this).returnValue }, set returnValue(e) { U(this).returnValue = e } }), be && F(be, O); var ye = window.EventTarget, Ee = ["addEventListener", "removeEventListener", "dispatchEvent"]; [Node, Window].forEach(function (e) { var t = e.prototype; Ee.forEach(function (e) { Object.defineProperty(t, e + "_", {value: t[e]}) }) }), L.prototype = { addEventListener: function (e, t, n) { if (N(t) && !j(e)) { var r = new b(e, t, n), o = z.get(this); if (o) { for (var i = 0; i < o.length; i++)if (r.equals(o[i]))return } else o = [], o.depth = 0, z.set(this, o); o.push(r); var a = _(this); a.addEventListener_(e, d, !0) } }, removeEventListener: function (e, t, n) { n = Boolean(n); var r = z.get(this); if (r) { for (var o = 0, i = !1, a = 0; a < r.length; a++)r[a].type === e && r[a].capture === n && (o++, r[a].handler === t && (i = !0, r[a].remove())); if (i && 1 === o) { var s = _(this); s.removeEventListener_(e, d, !0) } } }, dispatchEvent: function (t) { var n = q(t), r = n.type; X.set(n, !1), e.renderAllPending(); var o; C(this, r) || (o = function () { }, this.addEventListener(r, o, !0)); try { return q(this).dispatchEvent_(n) } finally { o && this.removeEventListener(r, o, !0) } } }, ye && F(ye, L); var Se = document.elementFromPoint; e.elementFromPoint = x, e.getEventHandlerGetter = R, e.getEventHandlerSetter = P, e.wrapEventTargetMethods = H, e.wrappers.BeforeUnloadEvent = O, e.wrappers.CustomEvent = le, e.wrappers.Event = y, e.wrappers.EventTarget = L, e.wrappers.FocusEvent = we, e.wrappers.MouseEvent = he, e.wrappers.UIEvent = ue }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { Object.defineProperty(e, t, w) } function n(e) { u(e, this) } function r() { this.length = 0, t(this, "length") } function o(e) { for (var t = new r, o = 0; o < e.length; o++)t[o] = new n(e[o]); return t.length = o, t } function i(e) { a.call(this, e) } var a = e.wrappers.UIEvent, s = e.mixin, c = e.registerWrapper, u = e.setWrapper, l = e.unsafeUnwrap, p = e.wrap, d = window.TouchEvent; if (d) { var f; try { f = document.createEvent("TouchEvent") } catch (h) { return } var w = {enumerable: !1}; n.prototype = { get target() { return p(l(this).target) } }; var m = {configurable: !0, enumerable: !0, get: null}; ["clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce"].forEach(function (e) { m.get = function () { return l(this)[e] }, Object.defineProperty(n.prototype, e, m) }), r.prototype = { item: function (e) { return this[e] } }, i.prototype = Object.create(a.prototype), s(i.prototype, { get touches() { return o(l(this).touches) }, get targetTouches() { return o(l(this).targetTouches) }, get changedTouches() { return o(l(this).changedTouches) }, initTouchEvent: function () { throw new Error("Not implemented") } }), c(d, i, f), e.wrappers.Touch = n, e.wrappers.TouchEvent = i, e.wrappers.TouchList = r } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { Object.defineProperty(e, t, s) } function n() { this.length = 0, t(this, "length") } function r(e) { if (null == e)return e; for (var t = new n, r = 0, o = e.length; o > r; r++)t[r] = a(e[r]); return t.length = o, t } function o(e, t) { e.prototype[t] = function () { return r(i(this)[t].apply(i(this), arguments)) } } var i = e.unsafeUnwrap, a = e.wrap, s = {enumerable: !1}; n.prototype = { item: function (e) { return this[e] } }, t(n.prototype, "item"), e.wrappers.NodeList = n, e.addWrapNodeListMethod = o, e.wrapNodeList = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; e.wrapHTMLCollection = e.wrapNodeList, e.wrappers.HTMLCollection = e.wrappers.NodeList }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { N(e instanceof S) } function n(e) { var t = new T; return t[0] = e, t.length = 1, t } function r(e, t, n) { L(t, "childList", {removedNodes: n, previousSibling: e.previousSibling, nextSibling: e.nextSibling}) } function o(e, t) { L(e, "childList", {removedNodes: t}) } function i(e, t, r, o) { if (e instanceof DocumentFragment) { var i = s(e); B = !0; for (var a = i.length - 1; a >= 0; a--)e.removeChild(i[a]), i[a].parentNode_ = t; B = !1; for (var a = 0; a < i.length; a++)i[a].previousSibling_ = i[a - 1] || r, i[a].nextSibling_ = i[a + 1] || o; return r && (r.nextSibling_ = i[0]), o && (o.previousSibling_ = i[i.length - 1]), i } var i = n(e), c = e.parentNode; return c && c.removeChild(e), e.parentNode_ = t, e.previousSibling_ = r, e.nextSibling_ = o, r && (r.nextSibling_ = e), o && (o.previousSibling_ = e), i } function a(e) { if (e instanceof DocumentFragment)return s(e); var t = n(e), o = e.parentNode; return o && r(e, o, t), t } function s(e) { for (var t = new T, n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r; return t.length = n, o(e, t), t } function c(e) { return e } function u(e, t) { R(e, t), e.nodeIsInserted_() } function l(e, t) { for (var n = _(t), r = 0; r < e.length; r++)u(e[r], n) } function p(e) { R(e, new O(e, null)) } function d(e) { for (var t = 0; t < e.length; t++)p(e[t]) } function f(e, t) { var n = e.nodeType === S.DOCUMENT_NODE ? e : e.ownerDocument; n !== t.ownerDocument && n.adoptNode(t) } function h(t, n) { if (n.length) { var r = t.ownerDocument; if (r !== n[0].ownerDocument)for (var o = 0; o < n.length; o++)e.adoptNodeNoRemove(n[o], r) } } function w(e, t) { h(e, t); var n = t.length; if (1 === n)return W(t[0]); for (var r = W(e.ownerDocument.createDocumentFragment()), o = 0; n > o; o++)r.appendChild(W(t[o])); return r } function m(e) { if (void 0 !== e.firstChild_)for (var t = e.firstChild_; t;) { var n = t; t = t.nextSibling_, n.parentNode_ = n.previousSibling_ = n.nextSibling_ = void 0 } e.firstChild_ = e.lastChild_ = void 0 } function g(e) { if (e.invalidateShadowRenderer()) { for (var t = e.firstChild; t;) { N(t.parentNode === e); var n = t.nextSibling, r = W(t), o = r.parentNode; o && Y.call(o, r), t.previousSibling_ = t.nextSibling_ = t.parentNode_ = null, t = n } e.firstChild_ = e.lastChild_ = null } else for (var n, i = W(e), a = i.firstChild; a;)n = a.nextSibling, Y.call(i, a), a = n } function v(e) { var t = e.parentNode; return t && t.invalidateShadowRenderer() } function b(e) { for (var t, n = 0; n < e.length; n++)t = e[n], t.parentNode.removeChild(t) } function y(e, t, n) { var r; if (r = A(n ? U.call(n, P(e), !1) : q.call(P(e), !1)), t) { for (var o = e.firstChild; o; o = o.nextSibling)r.appendChild(y(o, !0, n)); if (e instanceof F.HTMLTemplateElement)for (var i = r.content, o = e.content.firstChild; o; o = o.nextSibling)i.appendChild(y(o, !0, n)) } return r } function E(e, t) { if (!t || _(e) !== _(t))return !1; for (var n = t; n; n = n.parentNode)if (n === e)return !0; return !1 } function S(e) { N(e instanceof V), M.call(this, e), this.parentNode_ = void 0, this.firstChild_ = void 0, this.lastChild_ = void 0, this.nextSibling_ = void 0, this.previousSibling_ = void 0, this.treeScope_ = void 0 } var M = e.wrappers.EventTarget, T = e.wrappers.NodeList, O = e.TreeScope, N = e.assert, j = e.defineWrapGetter, L = e.enqueueMutation, _ = e.getTreeScope, D = e.isWrapper, C = e.mixin, H = e.registerTransientObservers, x = e.registerWrapper, R = e.setTreeScope, P = e.unsafeUnwrap, W = e.unwrap, I = e.unwrapIfNeeded, A = e.wrap, k = e.wrapIfNeeded, F = e.wrappers, B = !1, U = document.importNode, q = window.Node.prototype.cloneNode, V = window.Node, G = window.DocumentFragment, z = (V.prototype.appendChild, V.prototype.compareDocumentPosition), X = V.prototype.isEqualNode, K = V.prototype.insertBefore, Y = V.prototype.removeChild, $ = V.prototype.replaceChild, Z = /Trident|Edge/.test(navigator.userAgent), J = Z ? function (e, t) { try { Y.call(e, t) } catch (n) { if (!(e instanceof G))throw n } } : function (e, t) { Y.call(e, t) }; S.prototype = Object.create(M.prototype), C(S.prototype, { appendChild: function (e) { return this.insertBefore(e, null) }, insertBefore: function (e, n) { t(e); var r; n ? D(n) ? r = W(n) : (r = n, n = A(r)) : (n = null, r = null), n && N(n.parentNode === this); var o, s = n ? n.previousSibling : this.lastChild, c = !this.invalidateShadowRenderer() && !v(e); if (o = c ? a(e) : i(e, this, s, n), c)f(this, e), m(this), K.call(P(this), W(e), r); else { s || (this.firstChild_ = o[0]), n || (this.lastChild_ = o[o.length - 1], void 0 === this.firstChild_ && (this.firstChild_ = this.firstChild)); var u = r ? r.parentNode : P(this); u ? K.call(u, w(this, o), r) : h(this, o) } return L(this, "childList", {addedNodes: o, nextSibling: n, previousSibling: s}), l(o, this), e }, removeChild: function (e) { if (t(e), e.parentNode !== this) { for (var r = !1, o = (this.childNodes, this.firstChild); o; o = o.nextSibling)if (o === e) { r = !0; break } if (!r)throw new Error("NotFoundError") } var i = W(e), a = e.nextSibling, s = e.previousSibling; if (this.invalidateShadowRenderer()) { var c = this.firstChild, u = this.lastChild, l = i.parentNode; l && J(l, i), c === e && (this.firstChild_ = a), u === e && (this.lastChild_ = s), s && (s.nextSibling_ = a), a && (a.previousSibling_ = s), e.previousSibling_ = e.nextSibling_ = e.parentNode_ = void 0 } else m(this), J(P(this), i); return B || L(this, "childList", {removedNodes: n(e), nextSibling: a, previousSibling: s}), H(this, e), e }, replaceChild: function (e, r) { t(e); var o; if (D(r) ? o = W(r) : (o = r, r = A(o)), r.parentNode !== this)throw new Error("NotFoundError"); var s, c = r.nextSibling, u = r.previousSibling, d = !this.invalidateShadowRenderer() && !v(e); return d ? s = a(e) : (c === e && (c = e.nextSibling), s = i(e, this, u, c)), d ? (f(this, e), m(this), $.call(P(this), W(e), o)) : (this.firstChild === r && (this.firstChild_ = s[0]), this.lastChild === r && (this.lastChild_ = s[s.length - 1]), r.previousSibling_ = r.nextSibling_ = r.parentNode_ = void 0, o.parentNode && $.call(o.parentNode, w(this, s), o)), L(this, "childList", { addedNodes: s, removedNodes: n(r), nextSibling: c, previousSibling: u }), p(r), l(s, this), r }, nodeIsInserted_: function () { for (var e = this.firstChild; e; e = e.nextSibling)e.nodeIsInserted_() }, hasChildNodes: function () { return null !== this.firstChild }, get parentNode() { return void 0 !== this.parentNode_ ? this.parentNode_ : A(P(this).parentNode) }, get firstChild() { return void 0 !== this.firstChild_ ? this.firstChild_ : A(P(this).firstChild) }, get lastChild() { return void 0 !== this.lastChild_ ? this.lastChild_ : A(P(this).lastChild) }, get nextSibling() { return void 0 !== this.nextSibling_ ? this.nextSibling_ : A(P(this).nextSibling) }, get previousSibling() { return void 0 !== this.previousSibling_ ? this.previousSibling_ : A(P(this).previousSibling) }, get parentElement() { for (var e = this.parentNode; e && e.nodeType !== S.ELEMENT_NODE;)e = e.parentNode; return e }, get textContent() { for (var e = "", t = this.firstChild; t; t = t.nextSibling)t.nodeType != S.COMMENT_NODE && (e += t.textContent); return e }, set textContent(e) { null == e && (e = ""); var t = c(this.childNodes); if (this.invalidateShadowRenderer()) { if (g(this), "" !== e) { var n = P(this).ownerDocument.createTextNode(e); this.appendChild(n) } } else m(this), P(this).textContent = e; var r = c(this.childNodes); L(this, "childList", {addedNodes: r, removedNodes: t}), d(t), l(r, this) }, get childNodes() { for (var e = new T, t = 0, n = this.firstChild; n; n = n.nextSibling)e[t++] = n; return e.length = t, e }, cloneNode: function (e) { return y(this, e) }, contains: function (e) { return E(this, k(e)) }, compareDocumentPosition: function (e) { return z.call(P(this), I(e)) }, isEqualNode: function (e) { return X.call(P(this), I(e)) }, normalize: function () { for (var e, t, n = c(this.childNodes), r = [], o = "", i = 0; i < n.length; i++)t = n[i], t.nodeType === S.TEXT_NODE ? e || t.data.length ? e ? (o += t.data, r.push(t)) : e = t : this.removeChild(t) : (e && r.length && (e.data += o, b(r)), r = [], o = "", e = null, t.childNodes.length && t.normalize()); e && r.length && (e.data += o, b(r)) } }), j(S, "ownerDocument"), x(V, S, document.createDocumentFragment()), delete S.prototype.querySelector, delete S.prototype.querySelectorAll, S.prototype = C(Object.create(M.prototype), S.prototype), e.cloneNode = y, e.nodeWasAdded = u, e.nodeWasRemoved = p, e.nodesWereAdded = l, e.nodesWereRemoved = d, e.originalInsertBefore = K, e.originalRemoveChild = Y, e.snapshotNodeList = c, e.wrappers.Node = S }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t, n, r, o) { for (var i = null, a = null, s = 0, c = t.length; c > s; s++)i = b(t[s]), !o && (a = g(i).root) && a instanceof e.wrappers.ShadowRoot || (r[n++] = i); return n } function n(e) { return String(e).replace(/\/deep\/|::shadow|>>>/g, " ") } function r(e) { return String(e).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " ") } function o(e, t) { for (var n, r = e.firstElementChild; r;) { if (r.matches(t))return r; if (n = o(r, t))return n; r = r.nextElementSibling } return null } function i(e, t) { return e.matches(t) } function a(e, t, n) { var r = e.localName; return r === t || r === n && e.namespaceURI === D } function s() { return !0 } function c(e, t, n) { return e.localName === n } function u(e, t) { return e.namespaceURI === t } function l(e, t, n) { return e.namespaceURI === t && e.localName === n } function p(e, t, n, r, o, i) { for (var a = e.firstElementChild; a;)r(a, o, i) && (n[t++] = a), t = p(a, t, n, r, o, i), a = a.nextElementSibling; return t } function d(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, null); if (c instanceof L)s = M.call(c, i); else { if (!(c instanceof _))return p(this, r, o, n, i, null); s = S.call(c, i) } return t(s, r, o, a) } function f(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a); if (c instanceof L)s = O.call(c, i, a); else { if (!(c instanceof _))return p(this, r, o, n, i, a); s = T.call(c, i, a) } return t(s, r, o, !1) } function h(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a); if (c instanceof L)s = j.call(c, i, a); else { if (!(c instanceof _))return p(this, r, o, n, i, a); s = N.call(c, i, a) } return t(s, r, o, !1) } var w = e.wrappers.HTMLCollection, m = e.wrappers.NodeList, g = e.getTreeScope, v = e.unsafeUnwrap, b = e.wrap, y = document.querySelector, E = document.documentElement.querySelector, S = document.querySelectorAll, M = document.documentElement.querySelectorAll, T = document.getElementsByTagName, O = document.documentElement.getElementsByTagName, N = document.getElementsByTagNameNS, j = document.documentElement.getElementsByTagNameNS, L = window.Element, _ = window.HTMLDocument || window.Document, D = "http://www.w3.org/1999/xhtml", C = { querySelector: function (t) { var r = n(t), i = r !== t; t = r; var a, s = v(this), c = g(this).root; if (c instanceof e.wrappers.ShadowRoot)return o(this, t); if (s instanceof L)a = b(E.call(s, t)); else { if (!(s instanceof _))return o(this, t); a = b(y.call(s, t)) } return a && !i && (c = g(a).root) && c instanceof e.wrappers.ShadowRoot ? o(this, t) : a }, querySelectorAll: function (e) { var t = n(e), r = t !== e; e = t; var o = new m; return o.length = d.call(this, i, 0, o, e, r), o } }, H = { matches: function (t) { return t = r(t), e.originalMatches.call(v(this), t) } }, x = { getElementsByTagName: function (e) { var t = new w, n = "*" === e ? s : a; return t.length = f.call(this, n, 0, t, e, e.toLowerCase()), t }, getElementsByClassName: function (e) { return this.querySelectorAll("." + e) }, getElementsByTagNameNS: function (e, t) { var n = new w, r = null; return r = "*" === e ? "*" === t ? s : c : "*" === t ? u : l, n.length = h.call(this, r, 0, n, e || null, t), n } }; e.GetElementsByInterface = x, e.SelectorsInterface = C, e.MatchesInterface = H }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.nextSibling; return e } function n(e) { for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.previousSibling; return e } var r = e.wrappers.NodeList, o = { get firstElementChild() { return t(this.firstChild) }, get lastElementChild() { return n(this.lastChild) }, get childElementCount() { for (var e = 0, t = this.firstElementChild; t; t = t.nextElementSibling)e++; return e }, get children() { for (var e = new r, t = 0, n = this.firstElementChild; n; n = n.nextElementSibling)e[t++] = n; return e.length = t, e }, remove: function () { var e = this.parentNode; e && e.removeChild(this) } }, i = { get nextElementSibling() { return t(this.nextSibling) }, get previousElementSibling() { return n(this.previousSibling) } }, a = { getElementById: function (e) { return /[ \t\n\r\f]/.test(e) ? null : this.querySelector('[id="' + e + '"]') } }; e.ChildNodeInterface = i, e.NonElementParentNodeInterface = a, e.ParentNodeInterface = o }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } var n = e.ChildNodeInterface, r = e.wrappers.Node, o = e.enqueueMutation, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = window.CharacterData; t.prototype = Object.create(r.prototype), i(t.prototype, { get nodeValue() { return this.data }, set nodeValue(e) { this.data = e }, get textContent() { return this.data }, set textContent(e) { this.data = e }, get data() { return s(this).data }, set data(e) { var t = s(this).data; o(this, "characterData", {oldValue: t}), s(this).data = e } }), i(t.prototype, n), a(c, t, document.createTextNode("")), e.wrappers.CharacterData = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e >>> 0 } function n(e) { r.call(this, e) } var r = e.wrappers.CharacterData, o = (e.enqueueMutation, e.mixin), i = e.registerWrapper, a = window.Text; n.prototype = Object.create(r.prototype), o(n.prototype, { splitText: function (e) { e = t(e); var n = this.data; if (e > n.length)throw new Error("IndexSizeError"); var r = n.slice(0, e), o = n.slice(e); this.data = r; var i = this.ownerDocument.createTextNode(o); return this.parentNode && this.parentNode.insertBefore(i, this.nextSibling), i } }), i(a, n, document.createTextNode("")), e.wrappers.Text = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return i(e).getAttribute("class") } function n(e, t) { a(e, "attributes", {name: "class", namespace: null, oldValue: t}) } function r(t) { e.invalidateRendererBasedOnAttribute(t, "class") } function o(e, o, i) { var a = e.ownerElement_; if (null == a)return o.apply(e, i); var s = t(a), c = o.apply(e, i); return t(a) !== s && (n(a, s), r(a)), c } if (!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH."); var i = e.unsafeUnwrap, a = e.enqueueMutation, s = DOMTokenList.prototype.add; DOMTokenList.prototype.add = function () { o(this, s, arguments) }; var c = DOMTokenList.prototype.remove; DOMTokenList.prototype.remove = function () { o(this, c, arguments) }; var u = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function () { return o(this, u, arguments) } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t, n) { var r = t.parentNode; if (r && r.shadowRoot) { var o = e.getRendererForHost(r); o.dependsOnAttribute(n) && o.invalidate() } } function n(e, t, n) { l(e, "attributes", {name: t, namespace: null, oldValue: n}) } function r(e) { a.call(this, e) } var o = e.ChildNodeInterface, i = e.GetElementsByInterface, a = e.wrappers.Node, s = e.ParentNodeInterface, c = e.SelectorsInterface, u = e.MatchesInterface, l = (e.addWrapNodeListMethod, e.enqueueMutation), p = e.mixin, d = (e.oneOf, e.registerWrapper), f = e.unsafeUnwrap, h = e.wrappers, w = window.Element, m = ["matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector"].filter(function (e) { return w.prototype[e] }), g = m[0], v = w.prototype[g], b = new WeakMap; r.prototype = Object.create(a.prototype), p(r.prototype, { createShadowRoot: function () { var t = new h.ShadowRoot(this); f(this).polymerShadowRoot_ = t; var n = e.getRendererForHost(this); return n.invalidate(), t }, get shadowRoot() { return f(this).polymerShadowRoot_ || null }, setAttribute: function (e, r) { var o = f(this).getAttribute(e); f(this).setAttribute(e, r), n(this, e, o), t(this, e) }, removeAttribute: function (e) { var r = f(this).getAttribute(e); f(this).removeAttribute(e), n(this, e, r), t(this, e) }, get classList() { var e = b.get(this); if (!e) { if (e = f(this).classList, !e)return; e.ownerElement_ = this, b.set(this, e) } return e }, get className() { return f(this).className }, set className(e) { this.setAttribute("class", e) }, get id() { return f(this).id }, set id(e) { this.setAttribute("id", e) } }), m.forEach(function (e) { "matches" !== e && (r.prototype[e] = function (e) { return this.matches(e) }) }), w.prototype.webkitCreateShadowRoot && (r.prototype.webkitCreateShadowRoot = r.prototype.createShadowRoot), p(r.prototype, o), p(r.prototype, i), p(r.prototype, s), p(r.prototype, c), p(r.prototype, u), d(w, r, document.createElementNS(null, "x")), e.invalidateRendererBasedOnAttribute = t, e.matchesNames = m, e.originalMatches = v, e.wrappers.Element = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { switch (e) { case"&": return "&amp;"; case"<": return "&lt;"; case">": return "&gt;"; case'"': return "&quot;"; case" ": return "&nbsp;" } } function n(e) { return e.replace(j, t) } function r(e) { return e.replace(L, t) } function o(e) { for (var t = {}, n = 0; n < e.length; n++)t[e[n]] = !0; return t } function i(e) { if (e.namespaceURI !== C)return !0; var t = e.ownerDocument.doctype; return t && t.publicId && t.systemId } function a(e, t) { switch (e.nodeType) { case Node.ELEMENT_NODE: for (var o, a = e.tagName.toLowerCase(), c = "<" + a, u = e.attributes, l = 0; o = u[l]; l++)c += " " + o.name + '="' + n(o.value) + '"'; return _[a] ? (i(e) && (c += "/"), c + ">") : c + ">" + s(e) + "</" + a + ">"; case Node.TEXT_NODE: var p = e.data; return t && D[t.localName] ? p : r(p); case Node.COMMENT_NODE: return "<!--" + e.data + "-->"; default: throw console.error(e), new Error("not implemented") } } function s(e) { e instanceof N.HTMLTemplateElement && (e = e.content); for (var t = "", n = e.firstChild; n; n = n.nextSibling)t += a(n, e); return t } function c(e, t, n) { var r = n || "div"; e.textContent = ""; var o = T(e.ownerDocument.createElement(r)); o.innerHTML = t; for (var i; i = o.firstChild;)e.appendChild(O(i)) } function u(e) { w.call(this, e) } function l(e, t) { var n = T(e.cloneNode(!1)); n.innerHTML = t; for (var r, o = T(document.createDocumentFragment()); r = n.firstChild;)o.appendChild(r); return O(o) } function p(t) { return function () { return e.renderAllPending(), M(this)[t] } } function d(e) { m(u, e, p(e)) } function f(t) { Object.defineProperty(u.prototype, t, { get: p(t), set: function (n) { e.renderAllPending(), M(this)[t] = n }, configurable: !0, enumerable: !0 }) } function h(t) { Object.defineProperty(u.prototype, t, { value: function () { return e.renderAllPending(), M(this)[t].apply(M(this), arguments) }, configurable: !0, enumerable: !0 }) } var w = e.wrappers.Element, m = e.defineGetter, g = e.enqueueMutation, v = e.mixin, b = e.nodesWereAdded, y = e.nodesWereRemoved, E = e.registerWrapper, S = e.snapshotNodeList, M = e.unsafeUnwrap, T = e.unwrap, O = e.wrap, N = e.wrappers, j = /[&\u00A0"]/g, L = /[&\u00A0<>]/g, _ = o(["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]), D = o(["style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript"]), C = "http://www.w3.org/1999/xhtml", H = /MSIE/.test(navigator.userAgent), x = window.HTMLElement, R = window.HTMLTemplateElement; u.prototype = Object.create(w.prototype), v(u.prototype, { get innerHTML() { return s(this) }, set innerHTML(e) { if (H && D[this.localName])return void(this.textContent = e); var t = S(this.childNodes); this.invalidateShadowRenderer() ? this instanceof N.HTMLTemplateElement ? c(this.content, e) : c(this, e, this.tagName) : !R && this instanceof N.HTMLTemplateElement ? c(this.content, e) : M(this).innerHTML = e; var n = S(this.childNodes); g(this, "childList", {addedNodes: n, removedNodes: t}), y(t), b(n, this) }, get outerHTML() { return a(this, this.parentNode) }, set outerHTML(e) { var t = this.parentNode; if (t) { t.invalidateShadowRenderer(); var n = l(t, e); t.replaceChild(n, this) } }, insertAdjacentHTML: function (e, t) { var n, r; switch (String(e).toLowerCase()) { case"beforebegin": n = this.parentNode, r = this; break; case"afterend": n = this.parentNode, r = this.nextSibling; break; case"afterbegin": n = this, r = this.firstChild; break; case"beforeend": n = this, r = null; break; default: return } var o = l(n, t); n.insertBefore(o, r) }, get hidden() { return this.hasAttribute("hidden") }, set hidden(e) { e ? this.setAttribute("hidden", "") : this.removeAttribute("hidden") } }), ["clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth"].forEach(d), ["scrollLeft", "scrollTop"].forEach(f), ["focus", "getBoundingClientRect", "getClientRects", "scrollIntoView"].forEach(h), E(x, u, document.createElement("b")), e.wrappers.HTMLElement = u, e.getInnerHTML = s, e.setInnerHTML = c }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.HTMLCanvasElement; t.prototype = Object.create(n.prototype), r(t.prototype, { getContext: function () { var e = i(this).getContext.apply(i(this), arguments); return e && a(e) } }), o(s, t, document.createElement("canvas")), e.wrappers.HTMLCanvasElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = window.HTMLContentElement; t.prototype = Object.create(n.prototype), r(t.prototype, { constructor: t, get select() { return this.getAttribute("select") }, set select(e) { this.setAttribute("select", e) }, setAttribute: function (e, t) { n.prototype.setAttribute.call(this, e, t), "select" === String(e).toLowerCase() && this.invalidateShadowRenderer(!0) } }), i && o(i, t), e.wrappers.HTMLContentElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = window.HTMLFormElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get elements() { return i(a(this).elements) } }), o(s, t, document.createElement("form")), e.wrappers.HTMLFormElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } function n(e, t) { if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function."); var o = i(document.createElement("img")); r.call(this, o), a(o, this), void 0 !== e && (o.width = e), void 0 !== t && (o.height = t) } var r = e.wrappers.HTMLElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLImageElement; t.prototype = Object.create(r.prototype), o(s, t, document.createElement("img")), n.prototype = t.prototype, e.wrappers.HTMLImageElement = t, e.wrappers.Image = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = (e.mixin, e.wrappers.NodeList, e.registerWrapper), o = window.HTMLShadowElement; t.prototype = Object.create(n.prototype), t.prototype.constructor = t, o && r(o, t), e.wrappers.HTMLShadowElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { if (!e.defaultView)return e; var t = p.get(e); if (!t) { for (t = e.implementation.createHTMLDocument(""); t.lastChild;)t.removeChild(t.lastChild); p.set(e, t) } return t } function n(e) { for (var n, r = t(e.ownerDocument), o = c(r.createDocumentFragment()); n = e.firstChild;)o.appendChild(n); return o } function r(e) { if (o.call(this, e), !d) { var t = n(e); l.set(this, u(t)) } } var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.wrap, l = new WeakMap, p = new WeakMap, d = window.HTMLTemplateElement; r.prototype = Object.create(o.prototype), i(r.prototype, { constructor: r, get content() { return d ? u(s(this).content) : l.get(this) } }), d && a(d, r), e.wrappers.HTMLTemplateElement = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.registerWrapper, o = window.HTMLMediaElement; o && (t.prototype = Object.create(n.prototype), r(o, t, document.createElement("audio")), e.wrappers.HTMLMediaElement = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } function n(e) { if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function."); var t = i(document.createElement("audio")); r.call(this, t), a(t, this), t.setAttribute("preload", "auto"), void 0 !== e && t.setAttribute("src", e) } var r = e.wrappers.HTMLMediaElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLAudioElement; s && (t.prototype = Object.create(r.prototype), o(s, t, document.createElement("audio")), n.prototype = t.prototype, e.wrappers.HTMLAudioElement = t, e.wrappers.Audio = n) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e.replace(/\s+/g, " ").trim() } function n(e) { o.call(this, e) } function r(e, t, n, i) { if (!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function."); var a = c(document.createElement("option")); o.call(this, a), s(a, this), void 0 !== e && (a.text = e), void 0 !== t && a.setAttribute("value", t), n === !0 && a.setAttribute("selected", ""), a.selected = i === !0 } var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.rewrap, c = e.unwrap, u = e.wrap, l = window.HTMLOptionElement; n.prototype = Object.create(o.prototype), i(n.prototype, { get text() { return t(this.textContent) }, set text(e) { this.textContent = t(String(e)) }, get form() { return u(c(this).form) } }), a(l, n, document.createElement("option")), r.prototype = n.prototype, e.wrappers.HTMLOptionElement = n, e.wrappers.Option = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = window.HTMLSelectElement; t.prototype = Object.create(n.prototype), r(t.prototype, { add: function (e, t) { "object" == typeof t && (t = i(t)), i(this).add(i(e), t) }, remove: function (e) { return void 0 === e ? void n.prototype.remove.call(this) : ("object" == typeof e && (e = i(e)), void i(this).remove(e)) }, get form() { return a(i(this).form) } }), o(s, t, document.createElement("select")), e.wrappers.HTMLSelectElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = e.wrapHTMLCollection, c = window.HTMLTableElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get caption() { return a(i(this).caption) }, createCaption: function () { return a(i(this).createCaption()) }, get tHead() { return a(i(this).tHead) }, createTHead: function () { return a(i(this).createTHead()) }, createTFoot: function () { return a(i(this).createTFoot()) }, get tFoot() { return a(i(this).tFoot) }, get tBodies() { return s(i(this).tBodies) }, createTBody: function () { return a(i(this).createTBody()) }, get rows() { return s(i(this).rows) }, insertRow: function (e) { return a(i(this).insertRow(e)) } }), o(c, t, document.createElement("table")), e.wrappers.HTMLTableElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableSectionElement; t.prototype = Object.create(n.prototype), r(t.prototype, { constructor: t, get rows() { return i(a(this).rows) }, insertRow: function (e) { return s(a(this).insertRow(e)) } }), o(c, t, document.createElement("thead")), e.wrappers.HTMLTableSectionElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableRowElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get cells() { return i(a(this).cells) }, insertCell: function (e) { return s(a(this).insertCell(e)) } }), o(c, t, document.createElement("tr")), e.wrappers.HTMLTableRowElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { switch (e.localName) { case"content": return new n(e); case"shadow": return new o(e); case"template": return new i(e) } r.call(this, e) } var n = e.wrappers.HTMLContentElement, r = e.wrappers.HTMLElement, o = e.wrappers.HTMLShadowElement, i = e.wrappers.HTMLTemplateElement, a = (e.mixin, e.registerWrapper), s = window.HTMLUnknownElement; t.prototype = Object.create(r.prototype), a(s, t), e.wrappers.HTMLUnknownElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.Element, r = e.wrappers.HTMLElement, o = e.registerWrapper, i = (e.defineWrapGetter, e.unsafeUnwrap), a = e.wrap, s = e.mixin, c = "http://www.w3.org/2000/svg", u = window.SVGElement, l = document.createElementNS(c, "title"); if (!("classList" in l)) { var p = Object.getOwnPropertyDescriptor(n.prototype, "classList"); Object.defineProperty(r.prototype, "classList", p), delete n.prototype.classList } t.prototype = Object.create(n.prototype), s(t.prototype, { get ownerSVGElement() { return a(i(this).ownerSVGElement) } }), o(u, t, document.createElementNS(c, "title")), e.wrappers.SVGElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { d.call(this, e) } var n = e.mixin, r = e.registerWrapper, o = e.unwrap, i = e.wrap, a = window.SVGUseElement, s = "http://www.w3.org/2000/svg", c = i(document.createElementNS(s, "g")), u = document.createElementNS(s, "use"), l = c.constructor, p = Object.getPrototypeOf(l.prototype), d = p.constructor; t.prototype = Object.create(p), "instanceRoot" in u && n(t.prototype, { get instanceRoot() { return i(o(this).instanceRoot) }, get animatedInstanceRoot() { return i(o(this).animatedInstanceRoot) } }), r(a, t, u), e.wrappers.SVGUseElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.EventTarget, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.SVGElementInstance; s && (t.prototype = Object.create(n.prototype), r(t.prototype, { get correspondingElement() { return a(i(this).correspondingElement) }, get correspondingUseElement() { return a(i(this).correspondingUseElement) }, get parentNode() { return a(i(this).parentNode) }, get childNodes() { throw new Error("Not implemented") }, get firstChild() { return a(i(this).firstChild) }, get lastChild() { return a(i(this).lastChild) }, get previousSibling() { return a(i(this).previousSibling) }, get nextSibling() { return a(i(this).nextSibling) } }), o(s, t), e.wrappers.SVGElementInstance = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { o(e, this) } var n = e.mixin, r = e.registerWrapper, o = e.setWrapper, i = e.unsafeUnwrap, a = e.unwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.CanvasRenderingContext2D; n(t.prototype, { get canvas() { return c(i(this).canvas) }, drawImage: function () { arguments[0] = s(arguments[0]), i(this).drawImage.apply(i(this), arguments) }, createPattern: function () { return arguments[0] = a(arguments[0]), i(this).createPattern.apply(i(this), arguments) } }), r(u, t, document.createElement("canvas").getContext("2d")), e.wrappers.CanvasRenderingContext2D = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { i(e, this) } var n = e.addForwardingProperties, r = e.mixin, o = e.registerWrapper, i = e.setWrapper, a = e.unsafeUnwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.WebGLRenderingContext; if (u) { r(t.prototype, { get canvas() { return c(a(this).canvas) }, texImage2D: function () { arguments[5] = s(arguments[5]), a(this).texImage2D.apply(a(this), arguments) }, texSubImage2D: function () { arguments[6] = s(arguments[6]), a(this).texSubImage2D.apply(a(this), arguments) } }); var l = Object.getPrototypeOf(u.prototype); l !== Object.prototype && n(l, t.prototype); var p = /WebKit/.test(navigator.userAgent) ? {drawingBufferHeight: null, drawingBufferWidth: null} : {}; o(u, t, p), e.wrappers.WebGLRenderingContext = t } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.Node, r = e.GetElementsByInterface, o = e.NonElementParentNodeInterface, i = e.ParentNodeInterface, a = e.SelectorsInterface, s = e.mixin, c = e.registerObject, u = e.registerWrapper, l = window.DocumentFragment; t.prototype = Object.create(n.prototype), s(t.prototype, i), s(t.prototype, a), s(t.prototype, r), s(t.prototype, o), u(l, t, document.createDocumentFragment()), e.wrappers.DocumentFragment = t; var p = c(document.createComment("")); e.wrappers.Comment = p }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = p(l(e).ownerDocument.createDocumentFragment()); n.call(this, t), c(t, this); var o = e.shadowRoot; h.set(this, o), this.treeScope_ = new r(this, a(o || e)), f.set(this, e) } var n = e.wrappers.DocumentFragment, r = e.TreeScope, o = e.elementFromPoint, i = e.getInnerHTML, a = e.getTreeScope, s = e.mixin, c = e.rewrap, u = e.setInnerHTML, l = e.unsafeUnwrap, p = e.unwrap, d = e.wrap, f = new WeakMap, h = new WeakMap; t.prototype = Object.create(n.prototype), s(t.prototype, { constructor: t, get innerHTML() { return i(this) }, set innerHTML(e) { u(this, e), this.invalidateShadowRenderer() }, get olderShadowRoot() { return h.get(this) || null }, get host() { return f.get(this) || null }, invalidateShadowRenderer: function () { return f.get(this).invalidateShadowRenderer() }, elementFromPoint: function (e, t) { return o(this, this.ownerDocument, e, t) }, getSelection: function () { return document.getSelection() }, get activeElement() { var e = p(this).ownerDocument.activeElement; if (!e || !e.nodeType)return null; for (var t = d(e); !this.contains(t);) { for (; t.parentNode;)t = t.parentNode; if (!t.host)return null; t = t.host } return t } }), e.wrappers.ShadowRoot = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = p(e).root; return t instanceof f ? t.host : null } function n(t, n) { if (t.shadowRoot) { n = Math.min(t.childNodes.length - 1, n); var r = t.childNodes[n]; if (r) { var o = e.getDestinationInsertionPoints(r); if (o.length > 0) { var i = o[0].parentNode; i.nodeType == Node.ELEMENT_NODE && (t = i) } } } return t } function r(e) { return e = l(e), t(e) || e } function o(e) { a(e, this) } var i = e.registerWrapper, a = e.setWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.unwrapIfNeeded, l = e.wrap, p = e.getTreeScope, d = window.Range, f = e.wrappers.ShadowRoot; o.prototype = { get startContainer() { return r(s(this).startContainer) }, get endContainer() { return r(s(this).endContainer) }, get commonAncestorContainer() { return r(s(this).commonAncestorContainer) }, setStart: function (e, t) { e = n(e, t), s(this).setStart(u(e), t) }, setEnd: function (e, t) { e = n(e, t), s(this).setEnd(u(e), t) }, setStartBefore: function (e) { s(this).setStartBefore(u(e)) }, setStartAfter: function (e) { s(this).setStartAfter(u(e)) }, setEndBefore: function (e) { s(this).setEndBefore(u(e)) }, setEndAfter: function (e) { s(this).setEndAfter(u(e)) }, selectNode: function (e) { s(this).selectNode(u(e)) }, selectNodeContents: function (e) { s(this).selectNodeContents(u(e)) }, compareBoundaryPoints: function (e, t) { return s(this).compareBoundaryPoints(e, c(t)) }, extractContents: function () { return l(s(this).extractContents()) }, cloneContents: function () { return l(s(this).cloneContents()) }, insertNode: function (e) { s(this).insertNode(u(e)) }, surroundContents: function (e) { s(this).surroundContents(u(e)) }, cloneRange: function () { return l(s(this).cloneRange()) }, isPointInRange: function (e, t) { return s(this).isPointInRange(u(e), t) }, comparePoint: function (e, t) { return s(this).comparePoint(u(e), t) }, intersectsNode: function (e) { return s(this).intersectsNode(u(e)) }, toString: function () { return s(this).toString() } }, d.prototype.createContextualFragment && (o.prototype.createContextualFragment = function (e) { return l(s(this).createContextualFragment(e)) }), i(window.Range, o, document.createRange()), e.wrappers.Range = o }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { e.previousSibling_ = e.previousSibling, e.nextSibling_ = e.nextSibling, e.parentNode_ = e.parentNode } function n(n, o, i) { var a = x(n), s = x(o), c = i ? x(i) : null; if (r(o), t(o), i)n.firstChild === i && (n.firstChild_ = i), i.previousSibling_ = i.previousSibling; else { n.lastChild_ = n.lastChild, n.lastChild === n.firstChild && (n.firstChild_ = n.firstChild); var u = R(a.lastChild); u && (u.nextSibling_ = u.nextSibling) } e.originalInsertBefore.call(a, s, c) } function r(n) { var r = x(n), o = r.parentNode; if (o) { var i = R(o); t(n), n.previousSibling && (n.previousSibling.nextSibling_ = n), n.nextSibling && (n.nextSibling.previousSibling_ = n), i.lastChild === n && (i.lastChild_ = n), i.firstChild === n && (i.firstChild_ = n), e.originalRemoveChild.call(o, r) } } function o(e) { W.set(e, []) } function i(e) { var t = W.get(e); return t || W.set(e, t = []), t } function a(e) { for (var t = [], n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r; return t } function s() { for (var e = 0; e < F.length; e++) { var t = F[e], n = t.parentRenderer; n && n.dirty || t.render() } F = [] } function c() { T = null, s() } function u(e) { var t = A.get(e); return t || (t = new f(e), A.set(e, t)), t } function l(e) { var t = D(e).root; return t instanceof _ ? t : null } function p(e) { return u(e.host) } function d(e) { this.skip = !1, this.node = e, this.childNodes = [] } function f(e) { this.host = e, this.dirty = !1, this.invalidateAttributes(), this.associateNode(e) } function h(e) { for (var t = [], n = e.firstChild; n; n = n.nextSibling)E(n) ? t.push.apply(t, i(n)) : t.push(n); return t } function w(e) { if (e instanceof j)return e; if (e instanceof N)return null; for (var t = e.firstChild; t; t = t.nextSibling) { var n = w(t); if (n)return n } return null } function m(e, t) { i(t).push(e); var n = I.get(e); n ? n.push(t) : I.set(e, [t]) } function g(e) { return I.get(e) } function v(e) { I.set(e, void 0) } function b(e, t) { var n = t.getAttribute("select"); if (!n)return !0; if (n = n.trim(), !n)return !0; if (!(e instanceof O))return !1; if (!U.test(n))return !1; try { return e.matches(n) } catch (r) { return !1 } } function y(e, t) { var n = g(t); return n && n[n.length - 1] === e } function E(e) { return e instanceof N || e instanceof j } function S(e) { return e.shadowRoot } function M(e) { for (var t = [], n = e.shadowRoot; n; n = n.olderShadowRoot)t.push(n); return t } var T, O = e.wrappers.Element, N = e.wrappers.HTMLContentElement, j = e.wrappers.HTMLShadowElement, L = e.wrappers.Node, _ = e.wrappers.ShadowRoot, D = (e.assert, e.getTreeScope), C = (e.mixin, e.oneOf), H = e.unsafeUnwrap, x = e.unwrap, R = e.wrap, P = e.ArraySplice, W = new WeakMap, I = new WeakMap, A = new WeakMap, k = C(window, ["requestAnimationFrame", "mozRequestAnimationFrame", "webkitRequestAnimationFrame", "setTimeout"]), F = [], B = new P; B.equals = function (e, t) { return x(e.node) === t }, d.prototype = { append: function (e) { var t = new d(e); return this.childNodes.push(t), t }, sync: function (e) { if (!this.skip) { for (var t = this.node, o = this.childNodes, i = a(x(t)), s = e || new WeakMap, c = B.calculateSplices(o, i), u = 0, l = 0, p = 0, d = 0; d < c.length; d++) { for (var f = c[d]; p < f.index; p++)l++, o[u++].sync(s); for (var h = f.removed.length, w = 0; h > w; w++) { var m = R(i[l++]); s.get(m) || r(m) } for (var g = f.addedCount, v = i[l] && R(i[l]), w = 0; g > w; w++) { var b = o[u++], y = b.node; n(t, y, v), s.set(y, !0), b.sync(s) } p += g } for (var d = p; d < o.length; d++)o[d].sync(s) } } }, f.prototype = { render: function (e) { if (this.dirty) { this.invalidateAttributes(); var t = this.host; this.distribution(t); var n = e || new d(t); this.buildRenderTree(n, t); var r = !e; r && n.sync(), this.dirty = !1 } }, get parentRenderer() { return D(this.host).renderer }, invalidate: function () { if (!this.dirty) { this.dirty = !0; var e = this.parentRenderer; if (e && e.invalidate(), F.push(this), T)return; T = window[k](c, 0) } }, distribution: function (e) { this.resetAllSubtrees(e), this.distributionResolution(e) }, resetAll: function (e) { E(e) ? o(e) : v(e), this.resetAllSubtrees(e) }, resetAllSubtrees: function (e) { for (var t = e.firstChild; t; t = t.nextSibling)this.resetAll(t); e.shadowRoot && this.resetAll(e.shadowRoot), e.olderShadowRoot && this.resetAll(e.olderShadowRoot) }, distributionResolution: function (e) { if (S(e)) { for (var t = e, n = h(t), r = M(t), o = 0; o < r.length; o++)this.poolDistribution(r[o], n); for (var o = r.length - 1; o >= 0; o--) { var i = r[o], a = w(i); if (a) { var s = i.olderShadowRoot; s && (n = h(s)); for (var c = 0; c < n.length; c++)m(n[c], a) } this.distributionResolution(i) } } for (var u = e.firstChild; u; u = u.nextSibling)this.distributionResolution(u) }, poolDistribution: function (e, t) { if (!(e instanceof j))if (e instanceof N) { var n = e; this.updateDependentAttributes(n.getAttribute("select")); for (var r = !1, o = 0; o < t.length; o++) { var e = t[o]; e && b(e, n) && (m(e, n), t[o] = void 0, r = !0) } if (!r)for (var i = n.firstChild; i; i = i.nextSibling)m(i, n) } else for (var i = e.firstChild; i; i = i.nextSibling)this.poolDistribution(i, t) }, buildRenderTree: function (e, t) { for (var n = this.compose(t), r = 0; r < n.length; r++) { var o = n[r], i = e.append(o); this.buildRenderTree(i, o) } if (S(t)) { var a = u(t); a.dirty = !1 } }, compose: function (e) { for (var t = [], n = e.shadowRoot || e, r = n.firstChild; r; r = r.nextSibling)if (E(r)) { this.associateNode(n); for (var o = i(r), a = 0; a < o.length; a++) { var s = o[a]; y(r, s) && t.push(s) } } else t.push(r); return t }, invalidateAttributes: function () { this.attributes = Object.create(null) }, updateDependentAttributes: function (e) { if (e) { var t = this.attributes; /\.\w+/.test(e) && (t["class"] = !0), /#\w+/.test(e) && (t.id = !0), e.replace(/\[\s*([^\s=\|~\]]+)/g, function (e, n) { t[n] = !0 }) } }, dependsOnAttribute: function (e) { return this.attributes[e] }, associateNode: function (e) { H(e).polymerShadowRenderer_ = this } }; var U = /^(:not\()?[*.#[a-zA-Z_|]/; L.prototype.invalidateShadowRenderer = function (e) { var t = H(this).polymerShadowRenderer_; return t ? (t.invalidate(), !0) : !1 }, N.prototype.getDistributedNodes = j.prototype.getDistributedNodes = function () { return s(), i(this) }, O.prototype.getDestinationInsertionPoints = function () { return s(), g(this) || [] }, N.prototype.nodeIsInserted_ = j.prototype.nodeIsInserted_ = function () { this.invalidateShadowRenderer(); var e, t = l(this); t && (e = p(t)), H(this).polymerShadowRenderer_ = e, e && e.invalidate() }, e.getRendererForHost = u, e.getShadowTrees = M, e.renderAllPending = s, e.getDestinationInsertionPoints = g, e.visual = { insertBefore: n, remove: r } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t) { if (window[t]) { r(!e.wrappers[t]); var c = function (e) { n.call(this, e) }; c.prototype = Object.create(n.prototype), o(c.prototype, { get form() { return s(a(this).form) } }), i(window[t], c, document.createElement(t.slice(4, -7))), e.wrappers[t] = c } } var n = e.wrappers.HTMLElement, r = e.assert, o = e.mixin, i = e.registerWrapper, a = e.unwrap, s = e.wrap, c = ["HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement"]; c.forEach(t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r(e, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrap, a = e.unwrapIfNeeded, s = e.wrap, c = window.Selection; t.prototype = { get anchorNode() { return s(o(this).anchorNode) }, get focusNode() { return s(o(this).focusNode) }, addRange: function (e) { o(this).addRange(a(e)) }, collapse: function (e, t) { o(this).collapse(a(e), t) }, containsNode: function (e, t) { return o(this).containsNode(a(e), t) }, getRangeAt: function (e) { return s(o(this).getRangeAt(e)) }, removeRange: function (e) { o(this).removeRange(i(e)) }, selectAllChildren: function (e) { o(this).selectAllChildren(e instanceof ShadowRoot ? o(e.host) : a(e)) }, toString: function () { return o(this).toString() } }, c.prototype.extend && (t.prototype.extend = function (e, t) { o(this).extend(a(e), t) }), n(window.Selection, t, window.getSelection()), e.wrappers.Selection = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r(e, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrapIfNeeded, a = e.wrap, s = window.TreeWalker; t.prototype = { get root() { return a(o(this).root) }, get currentNode() { return a(o(this).currentNode) }, set currentNode(e) { o(this).currentNode = i(e) }, get filter() { return o(this).filter }, parentNode: function () { return a(o(this).parentNode()) }, firstChild: function () { return a(o(this).firstChild()) }, lastChild: function () { return a(o(this).lastChild()) }, previousSibling: function () { return a(o(this).previousSibling()) }, previousNode: function () { return a(o(this).previousNode()) }, nextNode: function () { return a(o(this).nextNode()) } }, n(s, t), e.wrappers.TreeWalker = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { l.call(this, e), this.treeScope_ = new m(this, null) } function n(e) { var n = document[e]; t.prototype[e] = function () { return D(n.apply(L(this), arguments)) } } function r(e, t) { x.call(L(t), _(e)), o(e, t) } function o(e, t) { e.shadowRoot && t.adoptNode(e.shadowRoot), e instanceof w && i(e, t); for (var n = e.firstChild; n; n = n.nextSibling)o(n, t) } function i(e, t) { var n = e.olderShadowRoot; n && t.adoptNode(n) } function a(e) { j(e, this) } function s(e, t) { var n = document.implementation[t]; e.prototype[t] = function () { return D(n.apply(L(this), arguments)) } } function c(e, t) { var n = document.implementation[t]; e.prototype[t] = function () { return n.apply(L(this), arguments) } } var u = e.GetElementsByInterface, l = e.wrappers.Node, p = e.ParentNodeInterface, d = e.NonElementParentNodeInterface, f = e.wrappers.Selection, h = e.SelectorsInterface, w = e.wrappers.ShadowRoot, m = e.TreeScope, g = e.cloneNode, v = e.defineGetter, b = e.defineWrapGetter, y = e.elementFromPoint, E = e.forwardMethodsToWrapper, S = e.matchesNames, M = e.mixin, T = e.registerWrapper, O = e.renderAllPending, N = e.rewrap, j = e.setWrapper, L = e.unsafeUnwrap, _ = e.unwrap, D = e.wrap, C = e.wrapEventTargetMethods, H = (e.wrapNodeList, new WeakMap); t.prototype = Object.create(l.prototype), b(t, "documentElement"), b(t, "body"), b(t, "head"), v(t, "activeElement", function () { var e = _(this).activeElement; if (!e || !e.nodeType)return null; for (var t = D(e); !this.contains(t);) { for (; t.parentNode;)t = t.parentNode; if (!t.host)return null; t = t.host } return t }), ["createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode"].forEach(n); var x = document.adoptNode, R = document.getSelection; M(t.prototype, { adoptNode: function (e) { return e.parentNode && e.parentNode.removeChild(e), r(e, this), e }, elementFromPoint: function (e, t) { return y(this, this, e, t) }, importNode: function (e, t) { return g(e, t, L(this)) }, getSelection: function () { return O(), new f(R.call(_(this))) }, getElementsByName: function (e) { return h.querySelectorAll.call(this, "[name=" + JSON.stringify(String(e)) + "]") } }); var P = document.createTreeWalker, W = e.wrappers.TreeWalker; if (t.prototype.createTreeWalker = function (e, t, n, r) { var o = null; return n && (n.acceptNode && "function" == typeof n.acceptNode ? o = { acceptNode: function (e) { return n.acceptNode(D(e)) } } : "function" == typeof n && (o = function (e) { return n(D(e)) })), new W(P.call(_(this), _(e), t, o, r)) }, document.registerElement) { var I = document.registerElement; t.prototype.registerElement = function (t, n) { function r(e) { return e ? void j(e, this) : i ? document.createElement(i, t) : document.createElement(t) } var o, i; if (void 0 !== n && (o = n.prototype, i = n["extends"]), o || (o = Object.create(HTMLElement.prototype)), e.nativePrototypeTable.get(o))throw new Error("NotSupportedError"); for (var a, s = Object.getPrototypeOf(o), c = []; s && !(a = e.nativePrototypeTable.get(s));)c.push(s), s = Object.getPrototypeOf(s); if (!a)throw new Error("NotSupportedError"); for (var u = Object.create(a), l = c.length - 1; l >= 0; l--)u = Object.create(u); ["createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback"].forEach(function (e) { var t = o[e]; t && (u[e] = function () { D(this) instanceof r || N(this), t.apply(D(this), arguments) }) }); var p = {prototype: u}; i && (p["extends"] = i), r.prototype = o, r.prototype.constructor = r, e.constructorTable.set(u, r), e.nativePrototypeTable.set(o, u); I.call(_(this), t, p); return r }, E([window.HTMLDocument || window.Document], ["registerElement"]) } E([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement], ["appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild"]), E([window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement], S), E([window.HTMLDocument || window.Document], ["adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection"]), M(t.prototype, u), M(t.prototype, p), M(t.prototype, h), M(t.prototype, d), M(t.prototype, { get implementation() { var e = H.get(this); return e ? e : (e = new a(_(this).implementation), H.set(this, e), e) }, get defaultView() { return D(_(this).defaultView) } }), T(window.Document, t, document.implementation.createHTMLDocument("")), window.HTMLDocument && T(window.HTMLDocument, t), C([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement]); var A = document.implementation.createDocument; a.prototype.createDocument = function () { return arguments[2] = _(arguments[2]), D(A.apply(L(this), arguments)) }, s(a, "createDocumentType"), s(a, "createHTMLDocument"), c(a, "hasFeature"), T(window.DOMImplementation, a), E([window.DOMImplementation], ["createDocument", "createDocumentType", "createHTMLDocument", "hasFeature"]), e.adoptNodeNoRemove = r, e.wrappers.DOMImplementation = a, e.wrappers.Document = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.EventTarget, r = e.wrappers.Selection, o = e.mixin, i = e.registerWrapper, a = e.renderAllPending, s = e.unwrap, c = e.unwrapIfNeeded, u = e.wrap, l = window.Window, p = window.getComputedStyle, d = window.getDefaultComputedStyle, f = window.getSelection; t.prototype = Object.create(n.prototype), l.prototype.getComputedStyle = function (e, t) { return u(this || window).getComputedStyle(c(e), t) }, d && (l.prototype.getDefaultComputedStyle = function (e, t) { return u(this || window).getDefaultComputedStyle(c(e), t) }), l.prototype.getSelection = function () { return u(this || window).getSelection() }, delete window.getComputedStyle, delete window.getDefaultComputedStyle, delete window.getSelection, ["addEventListener", "removeEventListener", "dispatchEvent"].forEach(function (e) { l.prototype[e] = function () { var t = u(this || window); return t[e].apply(t, arguments) }, delete window[e] }), o(t.prototype, { getComputedStyle: function (e, t) { return a(), p.call(s(this), c(e), t) }, getSelection: function () { return a(), new r(f.call(s(this))) }, get document() { return u(s(this).document) } }), d && (t.prototype.getDefaultComputedStyle = function (e, t) { return a(), d.call(s(this), c(e), t) }), i(l, t, window), e.wrappers.Window = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; var t = e.unwrap, n = window.DataTransfer || window.Clipboard, r = n.prototype.setDragImage; r && (n.prototype.setDragImage = function (e, n, o) { r.call(this, t(e), n, o) }) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t; t = e instanceof i ? e : new i(e && o(e)), r(t, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unwrap, i = window.FormData; i && (n(i, t, new i), e.wrappers.FormData = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; var t = e.unwrapIfNeeded, n = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function (e) { return n.call(this, t(e)) } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = n[e], r = window[t]; if (r) { var o = document.createElement(e), i = o.constructor; window[t] = i } } var n = (e.isWrapperFor, { a: "HTMLAnchorElement", area: "HTMLAreaElement", audio: "HTMLAudioElement", base: "HTMLBaseElement", body: "HTMLBodyElement", br: "HTMLBRElement", button: "HTMLButtonElement", canvas: "HTMLCanvasElement", caption: "HTMLTableCaptionElement", col: "HTMLTableColElement", content: "HTMLContentElement", data: "HTMLDataElement", datalist: "HTMLDataListElement", del: "HTMLModElement", dir: "HTMLDirectoryElement", div: "HTMLDivElement", dl: "HTMLDListElement", embed: "HTMLEmbedElement", fieldset: "HTMLFieldSetElement", font: "HTMLFontElement", form: "HTMLFormElement", frame: "HTMLFrameElement", frameset: "HTMLFrameSetElement", h1: "HTMLHeadingElement", head: "HTMLHeadElement", hr: "HTMLHRElement", html: "HTMLHtmlElement", iframe: "HTMLIFrameElement", img: "HTMLImageElement", input: "HTMLInputElement", keygen: "HTMLKeygenElement", label: "HTMLLabelElement", legend: "HTMLLegendElement", li: "HTMLLIElement", link: "HTMLLinkElement", map: "HTMLMapElement", marquee: "HTMLMarqueeElement", menu: "HTMLMenuElement", menuitem: "HTMLMenuItemElement", meta: "HTMLMetaElement", meter: "HTMLMeterElement", object: "HTMLObjectElement", ol: "HTMLOListElement", optgroup: "HTMLOptGroupElement", option: "HTMLOptionElement", output: "HTMLOutputElement", p: "HTMLParagraphElement", param: "HTMLParamElement", pre: "HTMLPreElement", progress: "HTMLProgressElement", q: "HTMLQuoteElement", script: "HTMLScriptElement", select: "HTMLSelectElement", shadow: "HTMLShadowElement", source: "HTMLSourceElement", span: "HTMLSpanElement", style: "HTMLStyleElement", table: "HTMLTableElement", tbody: "HTMLTableSectionElement", template: "HTMLTemplateElement", textarea: "HTMLTextAreaElement", thead: "HTMLTableSectionElement", time: "HTMLTimeElement", title: "HTMLTitleElement", tr: "HTMLTableRowElement", track: "HTMLTrackElement", ul: "HTMLUListElement", video: "HTMLVideoElement" }); Object.keys(n).forEach(t), Object.getOwnPropertyNames(e.wrappers).forEach(function (t) { window[t] = e.wrappers[t] }) }(window.ShadowDOMPolyfill);
/* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * 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 ALGOLIA_VERSION = '2.8.5'; /* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * 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. */ /* * Algolia Search library initialization * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service * @param methodOrOptions the hash of parameters for initialization. It can contains: * - method (optional) specify if the protocol used is http or https (http by default to make the first search query faster). * You need to use https is you are doing something else than just search queries. * - hosts (optional) the list of hosts that you have received for the service * - dsn (optional) set to true if your account has the Distributed Search Option * - dsnHost (optional) override the automatic computation of dsn hostname */ var AlgoliaSearch = function(applicationID, apiKey, methodOrOptions, resolveDNS, hosts) { var self = this; this.applicationID = applicationID; this.apiKey = apiKey; this.dsn = true; this.dsnHost = null; this.hosts = []; this.currentHostIndex = 0; this.requestTimeoutInMs = 2000; this.extraHeaders = []; this.jsonp = null; var method; var tld = 'net'; if (typeof methodOrOptions === 'string') { // Old initialization method = methodOrOptions; } else { // Take all option from the hash var options = methodOrOptions || {}; if (!this._isUndefined(options.method)) { method = options.method; } if (!this._isUndefined(options.tld)) { tld = options.tld; } if (!this._isUndefined(options.dsn)) { this.dsn = options.dsn; } if (!this._isUndefined(options.hosts)) { hosts = options.hosts; } if (!this._isUndefined(options.dsnHost)) { this.dsnHost = options.dsnHost; } if (!this._isUndefined(options.requestTimeoutInMs)) { this.requestTimeoutInMs = +options.requestTimeoutInMs; } if (!this._isUndefined(options.jsonp)) { this.jsonp = options.jsonp; } } // If hosts is undefined, initialize it with applicationID if (this._isUndefined(hosts)) { hosts = [ this.applicationID + '-1.algolia.' + tld, this.applicationID + '-2.algolia.' + tld, this.applicationID + '-3.algolia.' + tld ]; } // detect is we use http or https this.host_protocol = 'http://'; if (this._isUndefined(method) || method === null) { this.host_protocol = ('https:' == document.location.protocol ? 'https' : 'http') + '://'; } else if (method === 'https' || method === 'HTTPS') { this.host_protocol = 'https://'; } // Add hosts in random order for (var i = 0; i < hosts.length; ++i) { if (Math.random() > 0.5) { this.hosts.reverse(); } this.hosts.push(this.host_protocol + hosts[i]); } if (Math.random() > 0.5) { this.hosts.reverse(); } // then add Distributed Search Network host if there is one if (this.dsn || this.dsnHost != null) { if (this.dsnHost) { this.hosts.unshift(this.host_protocol + this.dsnHost); } else { this.hosts.unshift(this.host_protocol + this.applicationID + '-dsn.algolia.' + tld); } } }; function AlgoliaExplainResults(hit, titleAttribute, otherAttributes) { function _getHitExplanationForOneAttr_recurse(obj, foundWords) { var res = []; if (typeof obj === 'object' && 'matchedWords' in obj && 'value' in obj) { var match = false; for (var j = 0; j < obj.matchedWords.length; ++j) { var word = obj.matchedWords[j]; if (!(word in foundWords)) { foundWords[word] = 1; match = true; } } if (match) { res.push(obj.value); } } else if (Object.prototype.toString.call(obj) === '[object Array]') { for (var i = 0; i < obj.length; ++i) { var array = _getHitExplanationForOneAttr_recurse(obj[i], foundWords); res = res.concat(array); } } else if (typeof obj === 'object') { for (var prop in obj) { if (obj.hasOwnProperty(prop)){ res = res.concat(_getHitExplanationForOneAttr_recurse(obj[prop], foundWords)); } } } return res; } function _getHitExplanationForOneAttr(hit, foundWords, attr) { var base = hit._highlightResult || hit; if (attr.indexOf('.') === -1) { if (attr in base) { return _getHitExplanationForOneAttr_recurse(base[attr], foundWords); } return []; } var array = attr.split('.'); var obj = base; for (var i = 0; i < array.length; ++i) { if (Object.prototype.toString.call(obj) === '[object Array]') { var res = []; for (var j = 0; j < obj.length; ++j) { res = res.concat(_getHitExplanationForOneAttr(obj[j], foundWords, array.slice(i).join('.'))); } return res; } if (array[i] in obj) { obj = obj[array[i]]; } else { return []; } } return _getHitExplanationForOneAttr_recurse(obj, foundWords); } var res = {}; var foundWords = {}; var title = _getHitExplanationForOneAttr(hit, foundWords, titleAttribute); res.title = (title.length > 0) ? title[0] : ''; res.subtitles = []; if (typeof otherAttributes !== 'undefined') { for (var i = 0; i < otherAttributes.length; ++i) { var attr = _getHitExplanationForOneAttr(hit, foundWords, otherAttributes[i]); for (var j = 0; j < attr.length; ++j) { res.subtitles.push({ attr: otherAttributes[i], value: attr[j] }); } } } return res; } window.AlgoliaSearch = AlgoliaSearch; AlgoliaSearch.prototype = { /* * Delete an index * * @param indexName the name of index to delete * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ deleteIndex: function(indexName, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexName), callback: callback }); }, /** * Move an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ moveIndex: function(srcIndexName, dstIndexName, callback) { var postObj = {operation: 'move', destination: dstIndexName}; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, callback: callback }); }, /** * Copy an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ copyIndex: function(srcIndexName, dstIndexName, callback) { var postObj = {operation: 'copy', destination: dstIndexName}; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, callback: callback }); }, /** * Return last log entries. * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry). * @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ getLogs: function(callback, offset, length) { if (this._isUndefined(offset)) { offset = 0; } if (this._isUndefined(length)) { length = 10; } this._jsonRequest({ method: 'GET', url: '/1/logs?offset=' + offset + '&length=' + length, callback: callback }); }, /* * List all existing indexes (paginated) * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with index list or error description if success is false. * @param page The page to retrieve, starting at 0. */ listIndexes: function(callback, page) { var params = page ? '?page=' + page : ''; this._jsonRequest({ method: 'GET', url: '/1/indexes' + params, callback: callback }); }, /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ initIndex: function(indexName) { return new this.Index(this, indexName); }, /* * List all existing user keys with their associated ACLs * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ listUserKeys: function(callback) { this._jsonRequest({ method: 'GET', url: '/1/keys', callback: callback }); }, /* * Get ACL of a user key * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ getUserKeyACL: function(key, callback) { this._jsonRequest({ method: 'GET', url: '/1/keys/' + key, callback: callback }); }, /* * Delete an existing user key * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ deleteUserKey: function(key, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/keys/' + key, callback: callback }); }, /* * Add an existing user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKey: function(acls, callback) { var aclsObject = {}; aclsObject.acl = acls; this._jsonRequest({ method: 'POST', url: '/1/keys', body: aclsObject, callback: callback }); }, /* * Add an existing user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. * @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; aclsObject.validity = validity; aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour; aclsObject.maxHitsPerQuery = maxHitsPerQuery; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + indexObj.indexName + '/keys', body: aclsObject, callback: callback }); }, /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ setSecurityTags: function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.tagFilters = tags; }, /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ setUserToken: function(userToken) { this.userToken = userToken; }, /* * Initialize a new batch of search queries */ startQueriesBatch: function() { this.batch = []; }, /* * Add a search query in the batch * * @param query the full text query * @param args (optional) if set, contains an object with query parameters: * - attributes: an array of object attribute names to retrieve * (if not set all attributes are retrieve) * - attributesToHighlight: an array of object attribute names to highlight * (if not set indexed attributes are highlighted) * - minWordSizefor1Typo: the minimum number of characters to accept one typo. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters to accept two typos. * Defaults to 7. * - getRankingInfo: if set, the result hits will contain ranking information in * _rankingInfo attribute * - page: (pagination parameter) page to retrieve (zero base). Defaults to 0. * - hitsPerPage: (pagination parameter) number of hits per page. Defaults to 10. */ addQueryInBatch: function(indexName, query, args) { var params = 'query=' + encodeURIComponent(query); if (!this._isUndefined(args) && args !== null) { params = this._getSearchParams(args, params); } this.batch.push({ indexName: indexName, params: params }); }, /* * Clear all queries in cache */ clearCache: function() { this.cache = {}; }, /* * Launch the batch of queries using XMLHttpRequest. * (Optimized for browser using a POST query to minimize number of OPTIONS queries) * * @param callback the function that will receive results * @param delay (optional) if set, wait for this delay (in ms) and only send the batch if there was no other in the meantime. */ sendQueriesBatch: function(callback, delay) { var as = this; var params = {requests: []}; for (var i = 0; i < as.batch.length; ++i) { params.requests.push(as.batch[i]); } window.clearTimeout(as.onDelayTrigger); if (!this._isUndefined(delay) && delay !== null && delay > 0) { var onDelayTrigger = window.setTimeout( function() { as._sendQueriesBatch(params, callback); }, delay); as.onDelayTrigger = onDelayTrigger; } else { this._sendQueriesBatch(params, callback); } }, /** * Set the number of milliseconds a request can take before automatically being terminated. * * @param {Number} milliseconds */ setRequestTimeout: function(milliseconds) { if (milliseconds) { this.requestTimeoutInMs = parseInt(milliseconds, 10); } }, /* * Index class constructor. * You should not use this method directly but use initIndex() function */ Index: function(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; }, /** * Add an extra field to the HTTP request * * @param key the header field name * @param value the header field value */ setExtraHeader: function(key, value) { this.extraHeaders.push({ key: key, value: value}); }, _sendQueriesBatch: function(params, callback) { if (this.jsonp === null) { var self = this; this._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/*/queries', body: params, callback: function(success, content) { if (!success) { // retry first with JSONP self.jsonp = true; self._sendQueriesBatch(params, callback); } else { self.jsonp = false; callback && callback(success, content); } } }); } else if (this.jsonp) { var jsonpParams = ''; for (var i = 0; i < params.requests.length; ++i) { var q = '/1/indexes/' + encodeURIComponent(params.requests[i].indexName) + '?' + params.requests[i].params; jsonpParams += i + '=' + encodeURIComponent(q) + '&'; } var pObj = {params: jsonpParams}; this._jsonRequest({ cache: this.cache, method: 'GET', url: '/1/indexes/*', body: pObj, callback: callback }); } else { this._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/*/queries', body: params, callback: callback}); } }, /* * Wrapper that try all hosts to maximize the quality of service */ _jsonRequest: function(opts) { var self = this; var callback = opts.callback; var cache = null; var cacheID = opts.url; if (!this._isUndefined(opts.body)) { cacheID = opts.url + '_body_' + JSON.stringify(opts.body); } if (!this._isUndefined(opts.cache)) { cache = opts.cache; if (!this._isUndefined(cache[cacheID])) { if (!this._isUndefined(callback)) { setTimeout(function () { callback(true, cache[cacheID]); }, 1); } return; } } opts.successiveRetryCount = 0; var impl = function() { if (opts.successiveRetryCount >= self.hosts.length) { if (!self._isUndefined(callback)) { opts.successiveRetryCount = 0; callback(false, { message: 'Cannot connect the Algolia\'s Search API. Please send an email to [email protected] to report the issue.' }); } return; } opts.callback = function(retry, success, res, body) { if (!success && !self._isUndefined(body)) { window.console && console.log('Error: ' + body.message); } if (success && !self._isUndefined(opts.cache)) { cache[cacheID] = body; } if (!success && retry) { self.currentHostIndex = ++self.currentHostIndex % self.hosts.length; opts.successiveRetryCount += 1; impl(); } else { opts.successiveRetryCount = 0; if (!self._isUndefined(callback)) { callback(success, body); } } }; opts.hostname = self.hosts[self.currentHostIndex]; self._jsonRequestByHost(opts); }; impl(); }, _jsonRequestByHost: function(opts) { var self = this; var url = opts.hostname + opts.url; if (this.jsonp) { this._makeJsonpRequestByHost(url, opts); } else { this._makeXmlHttpRequestByHost(url, opts); } }, /** * Make a JSONP request * * @param url request url (includes endpoint and path) * @param opts all request options */ _makeJsonpRequestByHost: function(url, opts) { ////////////////// ////////////////// ///// ///// DISABLED FOR SECURITY PURPOSE ///// ////////////////// ////////////////// opts.callback(true, false, null, { 'message': 'JSONP not allowed.' }); return; // if (opts.method !== 'GET') { // opts.callback(true, false, null, { 'message': 'Method ' + opts.method + ' ' + url + ' is not supported by JSONP.' }); // return; // } // this.jsonpCounter = this.jsonpCounter || 0; // this.jsonpCounter += 1; // var head = document.getElementsByTagName('head')[0]; // var script = document.createElement('script'); // var cb = 'algoliaJSONP_' + this.jsonpCounter; // var done = false; // var ontimeout = null; // window[cb] = function(data) { // opts.callback(false, true, null, data); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // script.type = 'text/javascript'; // script.src = url + '?callback=' + cb + '&X-Algolia-Application-Id=' + this.applicationID + '&X-Algolia-API-Key=' + this.apiKey; // if (this.tagFilters) { // script.src += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters); // } // if (this.userToken) { // script.src += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken); // } // for (var i = 0; i < this.extraHeaders.length; ++i) { // script.src += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value; // } // if (opts.body && opts.body.params) { // script.src += '&' + opts.body.params; // } // ontimeout = setTimeout(function() { // script.onload = script.onreadystatechange = script.onerror = null; // window[cb] = function(data) { // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // opts.callback(true, false, null, { 'message': 'Timeout - Failed to load JSONP script.' }); // head.removeChild(script); // clearTimeout(ontimeout); // ontimeout = null; // }, this.requestTimeoutInMs); // script.onload = script.onreadystatechange = function() { // clearTimeout(ontimeout); // ontimeout = null; // if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { // done = true; // if (typeof window[cb + '_loaded'] === 'undefined') { // opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' }); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // } else { // try { delete window[cb + '_loaded']; } catch (e) { window[cb + '_loaded'] = undefined; } // } // script.onload = script.onreadystatechange = null; // Handle memory leak in IE // head.removeChild(script); // } // }; // script.onerror = function() { // clearTimeout(ontimeout); // ontimeout = null; // opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' }); // head.removeChild(script); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // head.appendChild(script); }, /** * Make a XmlHttpRequest * * @param url request url (includes endpoint and path) * @param opts all request opts */ _makeXmlHttpRequestByHost: function(url, opts) { var self = this; var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : {}; var body = null; var ontimeout = null; if (!this._isUndefined(opts.body)) { body = JSON.stringify(opts.body); } url += ((url.indexOf('?') == -1) ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey; url += '&X-Algolia-Application-Id=' + this.applicationID; if (this.userToken) { url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken); } if (this.tagFilters) { url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters); } for (var i = 0; i < this.extraHeaders.length; ++i) { url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value; } if ('withCredentials' in xmlHttp) { xmlHttp.open(opts.method, url, true); xmlHttp.timeout = this.requestTimeoutInMs * (opts.successiveRetryCount + 1); if (body !== null) { /* This content type is specified to follow CORS 'simple header' directive */ xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } } else if (typeof XDomainRequest !== 'undefined') { // Handle IE8/IE9 // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xmlHttp = new XDomainRequest(); xmlHttp.open(opts.method, url); } else { // very old browser, not supported opts.callback(false, false, null, { 'message': 'CORS not supported' }); return; } ontimeout = setTimeout(function() { xmlHttp.abort(); // Prevent Internet Explorer 9, JScript Error c00c023f if (xmlHttp.aborted === true) { stopLoadAnimation(); return; } opts.callback(true, false, null, { 'message': 'Timeout - Could not connect to endpoint ' + url } ); clearTimeout(ontimeout); ontimeout = null; }, this.requestTimeoutInMs * (opts.successiveRetryCount + 1)); xmlHttp.onload = function(event) { clearTimeout(ontimeout); ontimeout = null; if (!self._isUndefined(event) && event.target !== null) { var retry = (event.target.status === 0 || event.target.status === 503); var success = false; var response = null; if (typeof XDomainRequest !== 'undefined') { // Handle CORS requests IE8/IE9 response = event.target.responseText; success = (response && response.length > 0); } else { response = event.target.response; success = (event.target.status === 200 || event.target.status === 201); } opts.callback(retry, success, event.target, response ? JSON.parse(response) : null); } else { opts.callback(false, true, event, JSON.parse(xmlHttp.responseText)); } }; xmlHttp.ontimeout = function(event) { // stop the network call but rely on ontimeout to call opt.callback }; xmlHttp.onerror = function(event) { clearTimeout(ontimeout); ontimeout = null; opts.callback(true, false, null, { 'message': 'Could not connect to host', 'error': event } ); }; xmlHttp.send(body); }, /* * Transform search param object in query string */ _getSearchParams: function(args, params) { if (this._isUndefined(args) || args === null) { return params; } for (var key in args) { if (key !== null && args.hasOwnProperty(key)) { params += (params.length === 0) ? '?' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? JSON.stringify(args[key]) : args[key]); } } return params; }, _isUndefined: function(obj) { return obj === void 0; }, /// internal attributes applicationID: null, apiKey: null, tagFilters: null, userToken: null, hosts: [], cache: {}, extraHeaders: [] }; /* * Contains all the functions related to one index * You should use AlgoliaSearch.initIndex(indexName) to retrieve this object */ AlgoliaSearch.prototype.Index.prototype = { /* * Clear all queries in cache */ clearCache: function() { this.cache = {}; }, /* * Add an object in this index * * @param content contains the javascript object to add inside the index * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID * @param objectID (optional) an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) */ addObject: function(content, callback, objectID) { var indexObj = this; if (this.as._isUndefined(objectID)) { this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName), body: content, callback: callback }); } else { this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), body: content, callback: callback }); } }, /* * Add several objects * * @param objects contains an array of objects to add * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ addObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'addObject', body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the object to retrieve or the error message if a failure occured * @param attributes (optional) if set, contains the array of attribute names to retrieve */ getObject: function(objectID, callback, attributes) { var indexObj = this; var params = ''; if (!this.as._isUndefined(attributes)) { params = '?attributes='; for (var i = 0; i < attributes.length; ++i) { if (i !== 0) { params += ','; } params += attributes[i]; } } if (this.as.jsonp === null) { this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, callback: callback }); } else { var pObj = {params: params}; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), callback: callback, body: pObj}); } }, /* * Update partially an object (only update attributes passed in argument) * * @param partialObject contains the javascript attributes to override, the * object must contains an objectID attribute * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID */ partialUpdateObject: function(partialObject, callback) { var indexObj = this; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial', body: partialObject, callback: callback }); }, /* * Partially Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ partialUpdateObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'partialUpdateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Override the content of object * * @param object contains the javascript object to save, the object must contains an objectID attribute * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ saveObject: function(object, callback) { var indexObj = this; this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID), body: object, callback: callback }); }, /* * Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ saveObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'updateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Delete an object from the index * * @param objectID the unique identifier of object to delete * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID */ deleteObject: function(objectID, callback) { if (objectID === null || objectID.length === 0) { callback(false, { message: 'empty objectID'}); return; } var indexObj = this; this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), callback: callback }); }, /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param query the full text query * @param callback the result callback with two arguments: * success: boolean set to true if the request was successfull. If false, the content contains the error. * content: the server answer that contains the list of results. * @param args (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use a string array encoding (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query. * Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Attributes are separated with a comma (for example `"category,author"` ). * You can also use a JSON string array encoding (for example ["category","author"]). * Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should be considered as optional when found in the query. * The list of words is comma separated. * - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best * one is kept and others are removed. * @param delay (optional) if set, wait for this delay (in ms) and only send the query if there was no other in the meantime. */ search: function(query, callback, args, delay) { var indexObj = this; var params = 'query=' + encodeURIComponent(query); if (!this.as._isUndefined(args) && args !== null) { params = this.as._getSearchParams(args, params); } window.clearTimeout(indexObj.onDelayTrigger); if (!this.as._isUndefined(delay) && delay !== null && delay > 0) { var onDelayTrigger = window.setTimeout( function() { indexObj._search(params, callback); }, delay); indexObj.onDelayTrigger = onDelayTrigger; } else { this._search(params, callback); } }, /* * Browse all index content * * @param page Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 * @param hitsPerPage: Pagination parameter used to select the number of hits per page. Defaults to 1000. */ browse: function(page, callback, hitsPerPage) { var indexObj = this; var params = '?page=' + page; if (!this.as._isUndefined(hitsPerPage)) { params += '&hitsPerPage=' + hitsPerPage; } this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse' + params, callback: callback }); }, /* * Get a Typeahead.js adapter * @param searchParams contains an object with query parameters (see search for details) */ ttAdapter: function(params) { var self = this; return function(query, cb) { self.search(query, function(success, content) { if (success) { cb(content.hits); } }, params); }; }, /* * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param callback the result callback with with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains the list of results */ waitTask: function(taskID, callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID, callback: function(success, body) { if (success) { if (body.status === 'published') { callback(true, body); } else { setTimeout(function() { indexObj.waitTask(taskID, callback); }, 100); } } else { callback(false, body); } }}); }, /* * This function deletes the index content. Settings and index specific API keys are kept untouched. * * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the settings object or the error message if a failure occured */ clearIndex: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear', callback: callback }); }, /* * Get settings of this index * * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the settings object or the error message if a failure occured */ getSettings: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings', callback: callback }); }, /* * Set settings for this index * * @param settigns the settings object that can contains : * - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3). * - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7). * - hitsPerPage: (integer) the number of hits per page (default = 10). * - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects. * If set to null, all attributes are retrieved. * - attributesToHighlight: (array of strings) default list of attributes to highlight. * If set to null, all indexed attributes are highlighted. * - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number of words to return (syntax is attributeName:nbWords). * By default no snippet is computed. If set to null, no snippet is computed. * - attributesToIndex: (array of strings) the list of fields you want to index. * If set to null, all textual and numerical attributes of your objects are indexed, but you should update it to get optimal results. * This parameter has two important uses: * - Limit the attributes to index: For example if you store a binary image in base64, you want to store it and be able to * retrieve it but you don't want to search in the base64 string. * - Control part of the ranking*: (see the ranking parameter for full explanation) Matches in attributes at the beginning of * the list will be considered more important than matches in attributes further down the list. * In one attribute, matching text at the beginning of the attribute will be considered more important than text after, you can disable * this behavior if you add your attribute inside `unordered(AttributeName)`, for example attributesToIndex: ["title", "unordered(text)"]. * - attributesForFaceting: (array of strings) The list of fields you want to use for faceting. * All strings in the attribute selected for faceting are extracted and added as a facet. If set to null, no attribute is used for faceting. * - attributeForDistinct: (string) The attribute name used for the Distinct feature. This feature is similar to the SQL "distinct" keyword: when enabled * in query with the distinct=1 parameter, all hits containing a duplicate value for this attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best one is kept and others are removed. * - ranking: (array of strings) controls the way results are sorted. * We have six available criteria: * - typo: sort according to number of typos, * - geo: sort according to decreassing distance when performing a geo-location based search, * - proximity: sort according to the proximity of query words in hits, * - attribute: sort according to the order of attributes defined by attributesToIndex, * - exact: * - if the user query contains one word: sort objects having an attribute that is exactly the query word before others. * For example if you search for the "V" TV show, you want to find it with the "V" query and avoid to have all popular TV * show starting by the v letter before it. * - if the user query contains multiple words: sort according to the number of words that matched exactly (and not as a prefix). * - custom: sort according to a user defined formula set in **customRanking** attribute. * The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"] * - customRanking: (array of strings) lets you specify part of the ranking. * The syntax of this condition is an array of strings containing attributes prefixed by asc (ascending order) or desc (descending order) operator. * For example `"customRanking" => ["desc(population)", "asc(name)"]` * - queryType: Select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - highlightPreTag: (string) Specify the string that is inserted before the highlighted parts in the query result (default to "<em>"). * - highlightPostTag: (string) Specify the string that is inserted after the highlighted parts in the query result (default to "</em>"). * - optionalWords: (array of strings) Specify a list of words that should be considered as optional when found in the query. * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer or the error message if a failure occured */ setSettings: function(settings, callback) { var indexObj = this; this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings', body: settings, callback: callback }); }, /* * List all existing user keys associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ listUserKeys: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', callback: callback }); }, /* * Get ACL of a user key associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ getUserKeyACL: function(key, callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, callback: callback }); }, /* * Delete an existing user key associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ deleteUserKey: function(key, callback) { var indexObj = this; this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, callback: callback }); }, /* * Add an existing user key associated to this index * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKey: function(acls, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', body: aclsObject, callback: callback }); }, /* * Add an existing user key associated to this index * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. * @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; aclsObject.validity = validity; aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour; aclsObject.maxHitsPerQuery = maxHitsPerQuery; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', body: aclsObject, callback: callback }); }, /// /// Internal methods only after this line /// _search: function(params, callback) { var pObj = {params: params}; if (this.as.jsonp === null) { var self = this; this.as._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: pObj, callback: function(success, content) { if (!success) { // retry first with JSONP self.as.jsonp = true; self._search(params, callback); } else { self.as.jsonp = false; callback && callback(success, content); } } }); } else if (this.as.jsonp) { this.as._jsonRequest({ cache: this.cache, method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: pObj, callback: callback }); } else { this.as._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: pObj, callback: callback}); } }, // internal attributes as: null, indexName: null, cache: {}, typeAheadArgs: null, typeAheadValueOption: null, emptyConstructor: function() {} }; /* * Copyright (c) 2014 Algolia * http://www.algolia.com/ * * 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($) { var extend = function(out) { out = out || {}; for (var i = 1; i < arguments.length; i++) { if (!arguments[i]) { continue; } for (var key in arguments[i]) { if (arguments[i].hasOwnProperty(key)) { out[key] = arguments[i][key]; } } } return out; }; /** * Algolia Search Helper providing faceting and disjunctive faceting * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets */ window.AlgoliaSearchHelper = function(client, index, options) { /// Default options var defaults = { facets: [], // list of facets to compute disjunctiveFacets: [], // list of disjunctive facets to compute hitsPerPage: 20 // number of hits per page }; this.init(client, index, extend({}, defaults, options)); }; AlgoliaSearchHelper.prototype = { /** * Initialize a new AlgoliaSearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets * @return {AlgoliaSearchHelper} */ init: function(client, index, options) { this.client = client; this.index = index; this.options = options; this.page = 0; this.refinements = {}; this.disjunctiveRefinements = {}; this.extraQueries = []; }, /** * Perform a query * @param {string} q the user query * @param {function} searchCallback the result callback called with two arguments: * success: boolean set to true if the request was successfull * content: the query answer with an extra 'disjunctiveFacets' attribute */ search: function(q, searchCallback, searchParams) { this.q = q; this.searchCallback = searchCallback; this.searchParams = searchParams || {}; this.page = this.page || 0; this.refinements = this.refinements || {}; this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this._search(); }, /** * Remove all refinements (disjunctive + conjunctive) */ clearRefinements: function() { this.disjunctiveRefinements = {}; this.refinements = {}; }, /** * Ensure a facet refinement exists * @param {string} facet the facet to refine * @param {string} value the associated value */ addDisjunctiveRefine: function(facet, value) { this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; this.disjunctiveRefinements[facet][value] = true; }, /** * Ensure a facet refinement does not exist * @param {string} facet the facet to refine * @param {string} value the associated value */ removeDisjunctiveRefine: function(facet, value) { this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; try { delete this.disjunctiveRefinements[facet][value]; } catch (e) { this.disjunctiveRefinements[facet][value] = undefined; // IE compat } }, /** * Ensure a facet refinement exists * @param {string} facet the facet to refine * @param {string} value the associated value */ addRefine: function(facet, value) { var refinement = facet + ':' + value; this.refinements = this.refinements || {}; this.refinements[refinement] = true; }, /** * Ensure a facet refinement does not exist * @param {string} facet the facet to refine * @param {string} value the associated value */ removeRefine: function(facet, value) { var refinement = facet + ':' + value; this.refinements = this.refinements || {}; this.refinements[refinement] = false; }, /** * Toggle refinement state of a facet * @param {string} facet the facet to refine * @param {string} value the associated value * @return {boolean} true if the facet has been found */ toggleRefine: function(facet, value) { for (var i = 0; i < this.options.facets.length; ++i) { if (this.options.facets[i] == facet) { var refinement = facet + ':' + value; this.refinements[refinement] = !this.refinements[refinement]; this.page = 0; this._search(); return true; } } this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; for (var j = 0; j < this.options.disjunctiveFacets.length; ++j) { if (this.options.disjunctiveFacets[j] == facet) { this.disjunctiveRefinements[facet][value] = !this.disjunctiveRefinements[facet][value]; this.page = 0; this._search(); return true; } } return false; }, /** * Check the refinement state of a facet * @param {string} facet the facet * @param {string} value the associated value * @return {boolean} true if refined */ isRefined: function(facet, value) { var refinement = facet + ':' + value; if (this.refinements[refinement]) { return true; } if (this.disjunctiveRefinements[facet] && this.disjunctiveRefinements[facet][value]) { return true; } return false; }, /** * Go to next page */ nextPage: function() { this._gotoPage(this.page + 1); }, /** * Go to previous page */ previousPage: function() { if (this.page > 0) { this._gotoPage(this.page - 1); } }, /** * Goto a page * @param {integer} page The page number */ gotoPage: function(page) { this._gotoPage(page); }, /** * Configure the page but do not trigger a reload * @param {integer} page The page number */ setPage: function(page) { this.page = page; }, /** * Configure the underlying index name * @param {string} name the index name */ setIndex: function(name) { this.index = name; }, /** * Get the underlying configured index name */ getIndex: function() { return this.index; }, /** * Clear the extra queries added to the underlying batch of queries */ clearExtraQueries: function() { this.extraQueries = []; }, /** * Add an extra query to the underlying batch of queries. Once you add queries * to the batch, the 2nd parameter of the searchCallback will be an object with a `results` * attribute listing all search results. */ addExtraQuery: function(index, query, params) { this.extraQueries.push({ index: index, query: query, params: (params || {}) }); }, ///////////// PRIVATE /** * Goto a page * @param {integer} page The page number */ _gotoPage: function(page) { this.page = page; this._search(); }, /** * Perform the underlying queries */ _search: function() { this.client.startQueriesBatch(); this.client.addQueryInBatch(this.index, this.q, this._getHitsSearchParams()); var disjunctiveFacets = []; var unusedDisjunctiveFacets = {}; for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) { var facet = this.options.disjunctiveFacets[i]; if (this._hasDisjunctiveRefinements(facet)) { disjunctiveFacets.push(facet); } else { unusedDisjunctiveFacets[facet] = true; } } for (var i = 0; i < disjunctiveFacets.length; ++i) { this.client.addQueryInBatch(this.index, this.q, this._getDisjunctiveFacetSearchParams(disjunctiveFacets[i])); } for (var i = 0; i < this.extraQueries.length; ++i) { this.client.addQueryInBatch(this.extraQueries[i].index, this.extraQueries[i].query, this.extraQueries[i].params); } var self = this; this.client.sendQueriesBatch(function(success, content) { if (!success) { self.searchCallback(false, content); return; } var aggregatedAnswer = content.results[0]; aggregatedAnswer.disjunctiveFacets = aggregatedAnswer.disjunctiveFacets || {}; aggregatedAnswer.facetStats = aggregatedAnswer.facetStats || {}; for (var facet in unusedDisjunctiveFacets) { if (aggregatedAnswer.facets[facet] && !aggregatedAnswer.disjunctiveFacets[facet]) { aggregatedAnswer.disjunctiveFacets[facet] = aggregatedAnswer.facets[facet]; try { delete aggregatedAnswer.facets[facet]; } catch (e) { aggregatedAnswer.facets[facet] = undefined; // IE compat } } } for (var i = 0; i < disjunctiveFacets.length; ++i) { for (var facet in content.results[i + 1].facets) { aggregatedAnswer.disjunctiveFacets[facet] = content.results[i + 1].facets[facet]; if (self.disjunctiveRefinements[facet]) { for (var value in self.disjunctiveRefinements[facet]) { if (!aggregatedAnswer.disjunctiveFacets[facet][value] && self.disjunctiveRefinements[facet][value]) { aggregatedAnswer.disjunctiveFacets[facet][value] = 0; } } } } for (var stats in content.results[i + 1].facets_stats) { aggregatedAnswer.facetStats[stats] = content.results[i + 1].facets_stats[stats]; } } if (self.extraQueries.length === 0) { self.searchCallback(true, aggregatedAnswer); } else { var c = { results: [ aggregatedAnswer ] }; for (var i = 0; i < self.extraQueries.length; ++i) { c.results.push(content.results[1 + disjunctiveFacets.length + i]); } self.searchCallback(true, c); } }); }, /** * Build search parameters used to fetch hits * @return {hash} */ _getHitsSearchParams: function() { var facets = []; for (var i = 0; i < this.options.facets.length; ++i) { facets.push(this.options.facets[i]); } for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) { var facet = this.options.disjunctiveFacets[i]; if (!this._hasDisjunctiveRefinements(facet)) { facets.push(facet); } } return extend({}, { hitsPerPage: this.options.hitsPerPage, page: this.page, facets: facets, facetFilters: this._getFacetFilters() }, this.searchParams); }, /** * Build search parameters used to fetch a disjunctive facet * @param {string} facet the associated facet name * @return {hash} */ _getDisjunctiveFacetSearchParams: function(facet) { return extend({}, this.searchParams, { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], facets: facet, facetFilters: this._getFacetFilters(facet) }); }, /** * Test if there are some disjunctive refinements on the facet */ _hasDisjunctiveRefinements: function(facet) { for (var value in this.disjunctiveRefinements[facet]) { if (this.disjunctiveRefinements[facet][value]) { return true; } } return false; }, /** * Build facetFilters parameter based on current refinements * @param {string} facet if set, the current disjunctive facet * @return {hash} */ _getFacetFilters: function(facet) { var facetFilters = []; for (var refinement in this.refinements) { if (this.refinements[refinement]) { facetFilters.push(refinement); } } for (var disjunctiveRefinement in this.disjunctiveRefinements) { if (disjunctiveRefinement != facet) { var refinements = []; for (var value in this.disjunctiveRefinements[disjunctiveRefinement]) { if (this.disjunctiveRefinements[disjunctiveRefinement][value]) { refinements.push(disjunctiveRefinement + ':' + value); } } if (refinements.length > 0) { facetFilters.push(refinements); } } } return facetFilters; } }; })(); /* * Copyright (c) 2014 Algolia * http://www.algolia.com/ * * 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($) { /** * Algolia Places API * @param {string} Your application ID * @param {string} Your API Key */ window.AlgoliaPlaces = function(applicationID, apiKey) { this.init(applicationID, apiKey); }; AlgoliaPlaces.prototype = { /** * @param {string} Your application ID * @param {string} Your API Key */ init: function(applicationID, apiKey) { this.client = new AlgoliaSearch(applicationID, apiKey, 'http', true, ['places-1.algolia.io', 'places-2.algolia.io', 'places-3.algolia.io']); this.cache = {}; }, /** * Perform a query * @param {string} q the user query * @param {function} searchCallback the result callback called with two arguments: * success: boolean set to true if the request was successfull * content: the query answer with an extra 'disjunctiveFacets' attribute * @param {hash} the list of search parameters */ search: function(q, searchCallback, searchParams) { var indexObj = this; var params = 'query=' + encodeURIComponent(q); if (!this.client._isUndefined(searchParams) && searchParams != null) { params = this.client._getSearchParams(searchParams, params); } var pObj = {params: params, apiKey: this.client.apiKey, appID: this.client.applicationID}; this.client._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/places/query', body: pObj, callback: searchCallback, removeCustomHTTPHeaders: true }); } }; })();
'use strict'; angular.module('rvplusplus').directive('initFocus', function() { return { restrict: 'A', // only activate on element attribute link: function(scope, element, attrs) { element.focus(); } }; });
/** * @arliteam/arli v0.2.1 * https://github.com/arliteam/arli * * Copyright (c) Mohamed Elkebir (https://getsupercode.com) * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; exports.__esModule = true; /** * Test if a date string is in latin DMY format. * * Date format: DD/MM/YY[YY] DD.MM.YY[YY] DD-MM-YY[YY] DD MM YY[YY] * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 30/12/2000 | 30/12/99 * 30-12-2000 | 30-12-99 * 30.12.2000 | 30.12.99 * 30 12 2000 | 30 12 99 * * @param date A string of date to be tested */ exports.isDateDMY = function (date) { var pattern = /^(31|30|(?:0[1-9]|[1-2][0-9]))(\/|\.|-| )(12|11|10|0[1-9])(\2)(\d{4}|\d{2})$/; return pattern.test(date); }; /** * Test if a date string is in latin MDY format. * * Date format: MM/DD/YY[YY] MM.DD.YY[YY] MM-DD-YY[YY] MM DD YY[YY] * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 12/30/2000 | 12/30/99 * 12-30-2000 | 12-30-99 * 12.30.2000 | 12.30.99 * 12 30 2000 | 12 30 99 * * @param date A string of date to be tested */ exports.isDateMDY = function (date) { var pattern = /^(12|11|10|0[1-9])(\/|\.|-| )(31|30|(?:0[1-9]|[1-2][0-9]))(\2)(\d{4}|\d{2})$/; return pattern.test(date); }; /** * Test if a date string is in latin YMD format. * * Date format: YY[YY]/MM/DD YY[YY].MM.DD YY[YY]-MM-DD YY[YY] MM DD * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 2000/12/30 | 99/12/30 * 2000-12-30 | 99-12-30 * 2000.12.30 | 99.12.30 * 2000 12 30 | 99 12 30 * * @param date A string of date to be tested */ exports.isDateYMD = function (date) { var pattern = /^(\d{4}|\d{2})(\/|\.|-| )(12|11|10|0[1-9])(\2)(31|30|(?:0[1-9]|[1-2][0-9]))$/; return pattern.test(date); };
import external from '../../../externalModules.js'; import getNumberValues from './getNumberValues.js'; import parseImageId from '../parseImageId.js'; import dataSetCacheManager from '../dataSetCacheManager.js'; import getImagePixelModule from './getImagePixelModule.js'; import getOverlayPlaneModule from './getOverlayPlaneModule.js'; import getLUTs from './getLUTs.js'; import getModalityLUTOutputPixelRepresentation from './getModalityLUTOutputPixelRepresentation.js'; function metaDataProvider(type, imageId) { const { dicomParser } = external; const parsedImageId = parseImageId(imageId); const dataSet = dataSetCacheManager.get(parsedImageId.url); if (!dataSet) { return; } if (type === 'generalSeriesModule') { return { modality: dataSet.string('x00080060'), seriesInstanceUID: dataSet.string('x0020000e'), seriesNumber: dataSet.intString('x00200011'), studyInstanceUID: dataSet.string('x0020000d'), seriesDate: dicomParser.parseDA(dataSet.string('x00080021')), seriesTime: dicomParser.parseTM(dataSet.string('x00080031') || ''), }; } if (type === 'patientStudyModule') { return { patientAge: dataSet.intString('x00101010'), patientSize: dataSet.floatString('x00101020'), patientWeight: dataSet.floatString('x00101030'), }; } if (type === 'imagePlaneModule') { const imageOrientationPatient = getNumberValues(dataSet, 'x00200037', 6); const imagePositionPatient = getNumberValues(dataSet, 'x00200032', 3); const pixelSpacing = getNumberValues(dataSet, 'x00280030', 2); let columnPixelSpacing = null; let rowPixelSpacing = null; if (pixelSpacing) { rowPixelSpacing = pixelSpacing[0]; columnPixelSpacing = pixelSpacing[1]; } let rowCosines = null; let columnCosines = null; if (imageOrientationPatient) { rowCosines = [ parseFloat(imageOrientationPatient[0]), parseFloat(imageOrientationPatient[1]), parseFloat(imageOrientationPatient[2]), ]; columnCosines = [ parseFloat(imageOrientationPatient[3]), parseFloat(imageOrientationPatient[4]), parseFloat(imageOrientationPatient[5]), ]; } return { frameOfReferenceUID: dataSet.string('x00200052'), rows: dataSet.uint16('x00280010'), columns: dataSet.uint16('x00280011'), imageOrientationPatient, rowCosines, columnCosines, imagePositionPatient, sliceThickness: dataSet.floatString('x00180050'), sliceLocation: dataSet.floatString('x00201041'), pixelSpacing, rowPixelSpacing, columnPixelSpacing, }; } if (type === 'imagePixelModule') { return getImagePixelModule(dataSet); } if (type === 'modalityLutModule') { return { rescaleIntercept: dataSet.floatString('x00281052'), rescaleSlope: dataSet.floatString('x00281053'), rescaleType: dataSet.string('x00281054'), modalityLUTSequence: getLUTs( dataSet.uint16('x00280103'), dataSet.elements.x00283000 ), }; } if (type === 'voiLutModule') { const modalityLUTOutputPixelRepresentation = getModalityLUTOutputPixelRepresentation( dataSet ); return { windowCenter: getNumberValues(dataSet, 'x00281050', 1), windowWidth: getNumberValues(dataSet, 'x00281051', 1), voiLUTSequence: getLUTs( modalityLUTOutputPixelRepresentation, dataSet.elements.x00283010 ), }; } if (type === 'sopCommonModule') { return { sopClassUID: dataSet.string('x00080016'), sopInstanceUID: dataSet.string('x00080018'), }; } if (type === 'petIsotopeModule') { const radiopharmaceuticalInfo = dataSet.elements.x00540016; if (radiopharmaceuticalInfo === undefined) { return; } const firstRadiopharmaceuticalInfoDataSet = radiopharmaceuticalInfo.items[0].dataSet; return { radiopharmaceuticalInfo: { radiopharmaceuticalStartTime: dicomParser.parseTM( firstRadiopharmaceuticalInfoDataSet.string('x00181072') || '' ), radionuclideTotalDose: firstRadiopharmaceuticalInfoDataSet.floatString( 'x00181074' ), radionuclideHalfLife: firstRadiopharmaceuticalInfoDataSet.floatString( 'x00181075' ), }, }; } if (type === 'overlayPlaneModule') { return getOverlayPlaneModule(dataSet); } } export default metaDataProvider;
import Tablesaw from '../../dist/tablesaw'; console.log( "this should be the tablesaw object: ", Tablesaw );
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // // //= require_tree .
(function(){ ///////////////////////////////////////////////////////////////////////// // // // client/helpers/config.js // // // ///////////////////////////////////////////////////////////////////////// // Accounts.ui.config({ // 1 passwordSignupFields: 'USERNAME_ONLY' // 2 }); // ///////////////////////////////////////////////////////////////////////// }).call(this);
/** * Vector */ (function() { var global = this, nspace = global.Util, Exception = global.Exception, math = global.mathjs(); /** * * @type Vector * @param {Array} basis The basis vectors, ordered correctly, orthonormal and complete */ var Vector = nspace.Vector = function(basis) { if (!basis || ('length' in basis && basis.length === 0)) { throw new Exception.InvalidPreparation('Basis vector cannot be empty'); } // Set basis and init components with same length and value of 1 this.basis = basis; this.components = basis.map(function() { return 1; }); }; /** * Computes the inner product of two vectors, <v1|v2> * * @returns {mathjs} Scalar */ Vector.innerProduct = function(v1, v2) { var basis1 = v1.getBasis(), basis2 = v2.getBasis(); // Must have same basis lengths if (basis1.length !== basis2.length) { throw new Exception.InvalidPreparation('Basis must be same length'); } var comp1 = v1.getComponents(), comp2 = v2.getComponents(); var product = 0; // Essentially a foil operation, but this will support greater than two terms for (var i = 0; i < basis1.length; i++) { for (var j = 0; j < basis2.length; j++) { var comp = math.multiply(math.conj(comp1[i]), comp2[j]); var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]); product = math.add(product, math.multiply(comp, basis)); } } return product.get([0,0]); }; /** * Computes the outer product of two vectors, * (|v1x><v1x| + |v1y><v1y|)(|v2x> + |v2y>) * * @returns {undefined} */ Vector.outerProduct = function(v1, v2) { var basis1 = v1.getBasis(), basis2 = v2.getBasis(); // Must have same basis lengths if (basis1.length !== basis2.length) { throw new Exception.InvalidPreparation('Basis must be same length'); } var comp1 = v1.getComponents(), comp2 = v2.getComponents(); var product = new Vector(basis1); // Essentially a foil operation, but this will support greater than two terms for (var i = 0; i < basis1.length; i++) { var productComp = 0; for (var j = 0; j < basis2.length; j++) { var comp = math.multiply(math.conj(comp1[i]), comp2[j]); var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]); productComp = math.add(productComp, math.multiply(comp, basis)); } product.setComponent(i, productComp.get([0,0])); } return product; }; /** * */ Vector.prototype = { basis: null, components: null, /** * * @param {Number} index The basis vector index * @param {Mixed} value * @returns {Vector} */ setComponent: function(index, value) { if (index >= this.components.length) { throw new Exception.InvalidProperty('Invalid basis index'); } this.components[index] = value; return this; }, /** * * @param {Number} index The basis vector index * @returns {Number} */ getComponent: function(index) { if (index >= this.components.length) { throw new Exception.InvalidProperty('Invalid basis index'); } return this.components[index]; }, /** * * @param {Array} values * @returns {Vector} */ setComponents: function(values) { if (values.length !== this.components.length) { throw new Exception.InvalidProperty('Invalid'); } this.components = values; return this; }, /** * * @returns {Number[]} */ getComponents: function() { return this.components; }, /** * * @returns {mathjs} */ getBasis: function() { return this.basis; }, /** * Applies a scalar to the vector components, simulates applying a scalar to * vector mathematically * * @param {Number} scalar * @returns {Vector} */ scale: function(scalar) { this.components = this.components.map(function(component) { return math.multiply(scalar, component); }); return this; }, /** * Determines the magnitude of the vector, sqrt(x*x + y*y) * * @returns {mathjs} */ getMagnitude: function() { var magnitude = 0; for (var i = 0; i < this.components.length; i++) { var c = this.components[i]; magnitude = math.add(magnitude, math.multiply(math.conj(c),c)); } return math.sqrt(magnitude); }, /** * Multiplies the components by a scalar to that makes the magnitude 1 * * @returns {Vector} */ normalize: function() { var magSq = Vector.innerProduct(this, this); // Already normalized if (magSq === 1) { return this; } return this.scale(math.divide(1,math.sqrt(magSq))); }, /** * * @returns {Vector} */ clone: function() { var v = new Vector(this.getBasis()); v.setComponents(this.getComponents()); return v; }, /** * Returns a new vector that is just one basis dir, by index of the basis * set * * @param {Number} index * @returns {Vector} */ getBasisVector: function(index) { var v = this.clone(); // Set all other component values to zero other than the index v.setComponents(this.components.map(function(val, i) { return (i === index) ? val : 0; })); return v.normalize(); } }; })();
'use strict'; export default function routes($routeProvider) { 'ngInject'; $routeProvider.when('/new_component', { template: '<about></about>' }); $routeProvider.when('/new_component/:somethingToPrint', { template: '<about></about>' }); }
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'firehon', environment: environment, contentSecurityPolicy: { 'connect-src': "'self' wss://*.firebaseio.com" }, firebase: 'https://firehon.firebaseio.com/', baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
'use strict'; angular.module('springangularwayApp') .config(function ($stateProvider) { $stateProvider .state('configuration', { parent: 'admin', url: '/configuration', data: { roles: ['ROLE_ADMIN'], pageTitle: 'configuration.title' }, views: { 'content@': { templateUrl: 'scripts/app/admin/configuration/configuration.html', controller: 'ConfigurationController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('configuration'); return $translate.refresh(); }] } }); });
var path = require('path') var webpack = require('webpack') // Phaser webpack config var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/') var phaser = path.join(phaserModule, 'build/custom/phaser-split.js') var pixi = path.join(phaserModule, 'build/custom/pixi.js') var p2 = path.join(phaserModule, 'build/custom/p2.js') var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')) }) module.exports = { entry: { app: [ 'babel-polyfill', path.resolve(__dirname, 'src/main.js') ], vendor: ['pixi', 'p2', 'phaser', 'webfontloader', 'react'] }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: 'bundle.js' }, plugins: [ definePlugin, new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.optimize.UglifyJsPlugin({ drop_console: true, minimize: true, output: { comments: false } }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor'/* chunkName= */, filename: 'vendor.bundle.js'/* filename= */}) ], module: { rules: [ { test: /\.js$/, use: ['babel-loader'], include: path.join(__dirname, 'src') }, { test: /pixi\.js/, use: ['expose-loader?PIXI'] }, { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] }, { test: /p2\.js/, use: ['expose-loader?p2'] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['react', 'es2015']} } ] }, node: { fs: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { 'phaser': phaser, 'pixi': pixi, 'p2': p2 } } }
define([ 'base/Module', './show/Controller' ],function(Module, ShowController){ var mod = Module('HeaderModule', {autoStart: false}); var API = { showHeader: function() { var controller = new ShowController({ region: mod.kernel.headerRegion }); controller.showHeader(); } }; mod.on('start', function(){ API.showHeader(); }); });
export function pluralize(count, word) { return count === 1 ? word : word + 's'; } export function classNames(...args) { // based on https://github.com/JedWatson/classnames let classes = ''; args.forEach(arg => { if (arg) { const argType = typeof arg; if (argType === 'string' || argType === 'number') { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames(...arg); } else if (argType === 'object') { Object.keys(arg).forEach(key => { if (arg[key]) { classes += ' ' + key; } }); } } }); return classes.substr(1); } export function uuid() { let i, random; let uuid = ''; for (i = 0; i < 32; i++) { random = Math.random() * 16 | 0; if (i === 8 || i === 12 || i === 16 || i === 20) { uuid += '-'; } uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)) .toString(16); } return uuid; }
'use babel'; //showSearch import FoldNavigatorView from './fold-navigator-view'; import fuzzaldrinPlus from 'fuzzaldrin-plus'; import _ from 'lodash'; import { CompositeDisposable } from 'atom'; export default { config: { autofold: { title: 'Autofold on open', description: 'Autofold all folds when you open a document. config.cson key : autofold', type: 'boolean', default: false }, keepFolding: { title: 'Keep code folded.', description: 'Everytime you click on one of the fold navigator element all code folds will be folded before the selected fold opens. Usefull if you want to keep your code folded all the time. Note that if you are using ctrl-alt-cmd-up/down keys to navigate it will not close the folds. Also you can temporarily enable/disable this behaviour by holding down the option key while you click. config.cson key : keepFolding', type: 'boolean', default: false }, showLineNumbers: { title: 'Show line number.', description: 'Show line numbers in fold navigator. config.cson key : showLineNumbers', type: 'boolean', default: true }, indentationCharacter: { title: 'Indentation character.', description: 'The character used for indentation in the fold navigator panel. config.cson key : indentationCharacter', type: 'string', default: 'x' }, maxLineContentLength: { title: 'Maximum line length.', description: 'Fold Navigator will take the line on which the fold is on but if the line is longer than this many characters then it will truncate it. config.cson key : maxLineContentLength', type: 'integer', default: 60 }, minLineLength: { title: 'Minimum line length.', description: 'Sometimes the fold falls on line which contains very little information. Typically comments like /** are meaningless. If the line content is less then this many characters use the next line for the fold description. config.cson key : minLineLength', type: 'integer', default: 6 }, keepFoldingAllTime: { title: 'Keep code folded even on shortcuts.', description: 'It will fold all folds before opening a new one. config.cson key : keepFoldingAllTime', type: 'boolean', default: false }, autoScrollFoldNavigatorPanel: { title: 'Auto scroll fold navigator panel.', description: 'Scrolls the fold navigator panel to the active fold. config.cson key : autoScrollFoldNavigatorPanel', type: 'boolean', default: true }, unfoldAllSubfolds: { title: 'Unfold all subfolds.', description: 'When a fold is selected/active all subfolds will be unfolded as well. When you have lots of subfolds to open this can be sluggish. config.cson key : unfoldAllSubfolds', type: 'boolean', default: true }, maxFoldLevel: { title: 'Maximum fold level fold navigator will list.', description: 'It is possibly not much use listing every single fold. With this option you can limit the fold level depth we list on the panel hopefully giving you a better overview of the code. config.cson key : maxFoldLevel', type: 'integer', default: 10, }, whenMatchedUsePreviousLine: { title: 'Previous line should be used for description.', description: 'Comma separated values. If the content of the line matches any of these values the previous line is going to be used for the fold description. This is so that we avoid listing just a single bracket for example which would be pretty meaningless.', type: 'string', default: '{,{ ', }, log: { title: 'Turn on logging', description: 'It might help to sort out mysterious bugs.', type: 'boolean', default: false, }, }, activate(state) { //console.log(arguments.callee.name); /* this.settings = null; */ this.settings = null; this.iniSettings(); /* this.lines2fold = []; Key is the line number and the value is the line number of the last fold looped through in the document. currently the fold ending are not observed maybe I should change this in the future note that we will work with the line numbers displayed and not the actuall line number which can be 0 */ this.lines2fold = []; /* this.folds = []; array of row numbers where the folds are */ this.folds = []; /* this.visibleFolds = []; same as this.folds but limited by this.settings.maxFoldLevel */ this.visibleFolds = []; /* this.foldObjects = {}; we need this to be able to navigate levels an example bellow see this.parse it should really be a new Map(); { line: i, children: [], parent: parent, indentation: indentLevel, content: '', } */ this.foldObjects = {}; /* exactly the same as this.foldObjects but came later because of fuzzaldrin-plus which only seems to work with arrays as far as I can tell */ this.foldObjectsArray = []; /* this.foldLevels = {}; row numbers of the folds orgenised by level usefull for the commands which fold unfold levels */ this.foldLevels = {}; /* this.history = []; only used as a short term log so that we can navigate fold level down */ this.history = []; /* this.activeFold line number of the fold which we are on this is what gets highlighted on the fold navigator panel item */ this.activeFold = null; // subscriptions this.subscriptions = new CompositeDisposable(); this.onDidChangeCursorPositionSubscription = null; this.foldNavigatorView = new FoldNavigatorView(state.foldNavigatorViewState); // when active pane item changed parse code and change content of navigator panel atom.workspace.observeActivePaneItem((pane) => { this.observeActivePaneItem(pane) }); // parse content of editor each time it stopped changing atom.workspace.observeTextEditors((editor) => { this.observeTextEditors(editor) }); // attach onclick event to the fold navigator lines this.navigatorElementOnClick(); this.registerCommands(); /* this.panel = null; foldnavigator panel */ this.panel = null; this.addNavigatorPanel(); /* this.searchModal */ this.searchModal = null; this.searchModalElement = null; this.searchModalInput = null; this.searchModalItems = null; this.addSearchModal(); }, // observer text editors coming and going observeTextEditors(editor) { //console.log(arguments.callee.name); if (this.settings && this.settings.autofold && editor){ editor.foldAll(); } }, // every time the active pane changes this will get called observeActivePaneItem(pane) { //console.log(arguments.callee.name); var editor = atom.workspace.getActiveTextEditor(); var listener; var editorView; if (!editor) return; //dispose of previous subscription if (this.onDidChangeCursorPositionSubscription) { this.onDidChangeCursorPositionSubscription.dispose(); } // follow cursor in fold navigator register subscription so that we can remove it this.onDidChangeCursorPositionSubscription = editor.onDidChangeCursorPosition( _.debounce((event) => this.onDidChangeCursorPosition(event), 500) ); //dispose of previous subscription if (this.onDidStopChangingSubscription) { this.onDidStopChangingSubscription.dispose(); } // if document changed subscription this.onDidStopChangingSubscription = editor.onDidStopChanging( _.debounce((event) => this.parse(editor), 500) ); this.parse(editor); }, clearSearchModal() { if (!this.searchModal) return; this.searchModalItems.innerHTML = ''; this.searchModalInput.value = ''; }, alignEditorToSearch() { var selectedArr = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item-selected'); var selected = selectedArr[0]; var editor = atom.workspace.getActiveTextEditor(); if (selected && selected.dataset.row >= 0) { this.moveCursor(selected.dataset.row, false); } }, searchModalOnClick(event) { var row; var editor = atom.workspace.getActiveTextEditor(); var clicked = null; this.hideSearch(); if (event.target.matches('.fold-navigator-search-modal-item')) { clicked = event.target; } else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-search-modal-item')) { clicked = event.target.parentNode; } if (!clicked) return; row = clicked.dataset.row; //problem if (!row) return; this.moveCursor(row, false); }, addSearchModal() { this.searchModalElement = document.createElement('div'); this.searchModalElement.classList.add('fold-navigator-search-modal'); this.searchModalElement.classList.add('native-key-bindings'); this.searchModalInput = document.createElement('input'); this.searchModalItems = document.createElement('div'); this.searchModalElement.appendChild(this.searchModalInput); this.searchModalElement.appendChild(this.searchModalItems); this.searchModal = atom.workspace.addModalPanel({ item: this.searchModalElement, visible: false }); // on blur this.searchModalInput.addEventListener('blur', (event) => { // delay hiding because of the on click event won't fire otherwise WHAT an ugly way to solve it :) setTimeout(() => { this.hideSearch(); }, 200); }); // on click this.searchModalElement.addEventListener('click', (event) => { this.searchModalOnClick(event); }, true); // on input this.searchModalInput.addEventListener('input', () => { this.searchModalItems.innerHTML = ''; var query = this.searchModalInput.value; if (!query || query.length < 1) return; var filteredItems = fuzzaldrinPlus.filter(this.foldObjectsArray, query, { key: 'content' }); var html = ''; filteredItems.forEach((item, index) => { let selected = ' fold-navigator-search-modal-item-selected'; if (index > 0) { selected = ''; } //let html2add = '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>'; let indentHtml = ''; for (let j = 0; j < item.indentation; j++) { indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>'; } html += '<div class="fold-navigator-search-modal-item fold-navigator-item-indent-' + item.indentation + selected + '" data-row="' + item.line + '">' + indentHtml + item.content + '</div>'; }); this.searchModalItems.innerHTML = html; //var matches = fuzzaldrinPlus.match(displayName, this.searchModalInput.value); //filterQuery box from text input //items ?? // { key: @getFilterKey() } }); this.searchModalElement.addEventListener('keydown', (e) => { var sc = 'fold-navigator-search-modal-item-selected'; if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode == 13 || e.keyCode == 27) { var items = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item'); if (!items) return; // remove selected var selectedArr = this.searchModalItems.getElementsByClassName(sc); var selected = selectedArr[0]; if (selected) { selected.classList.remove(sc); } var first = items[0] ? items[0] : false; var last = items[items.length - 1] ? items[items.length - 1] : false; var next = null; if (e.keyCode === 38) { // up if (selected) { next = selected.previousElementSibling; } } else if (e.keyCode === 40) { // down if (selected) { next = selected.nextElementSibling; } } else if (e.keyCode === 27) { // esc this.hideSearch(); } else if (e.keyCode == 13) { // enter if (selected) { if (selected.dataset.row >= 0) { let editor = atom.workspace.getActiveTextEditor(); this.moveCursor(selected.dataset.row, false); this.hideSearch(); } } } // end of line or not selected if (!next) { if (e.keyCode === 38) next = last; else { next = first; } } if (next) { next.classList.add(sc); } } }); //var matches = fuzzaldrinPlus.match(displayName, filterQuery) }, hideSearch() { this.searchModal.hide(); let editor = atom.workspace.getActiveTextEditor(); if (editor) atom.views.getView(editor).focus(); }, showSearch() { if (!editor) return; this.searchModal.show(); this.searchModalInput.focus(); this.searchModalInput.select(); }, toggleSearch() { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (this.searchModal.isVisible()) { this.searchModal.hide(); atom.views.getView(editor).focus(); } else { this.searchModal.show(); this.searchModalInput.focus(); this.searchModalInput.select(); } }, onDidChangeCursorPosition(event) { //console.log(arguments.callee.name); this.selectRow(event.newBufferPosition.row); }, addNavigatorPanel() { //console.log(arguments.callee.name); var element = this.foldNavigatorView.getElement(); if (atom.config.get('tree-view.showOnRightSide')) { this.panel = atom.workspace.addLeftPanel({ item: element, visible: false }); } else { this.panel = atom.workspace.addRightPanel({ item: element, visible: false }); } }, iniSettings() { //console.log(arguments.callee.name); var editor = atom.workspace.getActiveTextEditor(); var languageSettings = null; if (editor) { let scope = editor.getGrammar().scopeName; languageSettings = atom.config.get('fold-navigator', { 'scope': [scope] }); } this.settings = atom.config.get('fold-navigator'); if (languageSettings){ Object.assign(this.settings, languageSettings); } // parse the comma separated string whenMatchedUsePreviousLine if(this.settings.whenMatchedUsePreviousLine && this.settings.whenMatchedUsePreviousLine.trim() != ''){ this.settings.whenMatchedUsePreviousLineArray = this.settings.whenMatchedUsePreviousLine.split(','); if(this.settings.whenMatchedUsePreviousLineArray.constructor !== Array){ this.settings.whenMatchedUsePreviousLineArray = null; } } }, registerCommands() { //"ctrl-alt-cmd-up": "fold-navigator:previousFoldAtCurrentLevel", //"ctrl-alt-cmd-down": "fold-navigator:nextFoldAtCurrentLevel", //"ctrl-alt-cmd-up": "fold-navigator:previousFold", //"ctrl-alt-cmd-down": "fold-navigator:nextFold", // //console.log(arguments.callee.name); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggle': () => this.toggle() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:open': () => this.open() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:close': () => this.close() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:previousFold': () => this.previousFold() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:nextFold': () => this.nextFold() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:moveLevelUp': () => this.moveLevelUp() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:moveLevelDown': () => this.moveLevelDown() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:nextFoldAtCurrentLevel': () => this.nextFoldAtCurrentLevel() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:previousFoldAtCurrentLevel': () => this.previousFoldAtCurrentLevel() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldSubfolds': () => this.unfoldSubfoldsPublic() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldActive': () => this.foldActivePublic() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel1': () => this.unfoldAtLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel2': () => this.unfoldAtLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel3': () => this.unfoldAtLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel4': () => this.unfoldAtLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel5': () => this.unfoldAtLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel1': () => this.foldAtLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel2': () => this.foldAtLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel3': () => this.foldAtLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel4': () => this.foldAtLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel5': () => this.foldAtLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel1': () => this.toggleFoldsLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel2': () => this.toggleFoldsLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel3': () => this.toggleFoldsLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel4': () => this.toggleFoldsLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel5': () => this.toggleFoldsLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleSearch': () => this.toggleSearch() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleActiveFold': () => this.toggleActiveFold() })); }, previousFold() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var folds = this.visibleFolds; if (!folds || folds.length === 0) return; //console.log(arguments.callee.name); this.clearHistory(); var fold = this.foldNavigatorView.getActiveFold(); var index = folds.indexOf(fold); var previous; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (index !== 0) { previous = folds[index - 1]; } else { previous = folds[folds.length - 1]; } if (previous || previous === 0) { this.moveCursor(previous); } }, nextFold() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } //console.log(arguments.callee.name); this.clearHistory(); var folds = this.visibleFolds; if (!folds || folds.length === 0) return; var fold = this.foldNavigatorView.getActiveFold(); var index = folds.indexOf(fold); var next; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (folds.length !== (index + 1)) { next = folds[index + 1]; } else { next = folds[0]; } if (next || next === 0) { this.moveCursor(next); } }, previousFoldAtCurrentLevel() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } //console.log(arguments.callee.name); this.clearHistory(); var fold = this.foldNavigatorView.getActiveFold(); var previous; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; var indentation = 0; if (fold || fold === 0) { indentation = editor.indentationForBufferRow(fold); } var level = this.getLevel(indentation); if (!level) return; var index = level.indexOf(fold); if (index !== 0) { previous = level[index - 1]; } else { previous = level[level.length - 1]; } if (previous || previous === 0) { this.moveCursor(previous); } }, nextFoldAtCurrentLevel() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } this.clearHistory(); //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var next; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; var indentation = 0; if (fold || fold === 0) { indentation = editor.indentationForBufferRow(fold); } var level = this.getLevel(indentation); if (!level) return; var index = level.indexOf(fold); if (level.length !== (index + 1)) { next = level[index + 1]; } else { next = level[0]; } if (next || next === 0) { this.moveCursor(next); } }, moveLevelUp() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var fold = this.foldNavigatorView.getActiveFold(); var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false; var editor = atom.workspace.getActiveTextEditor(); var parent; if (!editor || !foldObj) { return; } parent = this.getParentFold(foldObj); if ((parent || parent === 0) && parent !== 'root') { this.moveCursor(parent); this.addToHistory(fold); } }, moveLevelDown() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var fold = this.foldNavigatorView.getActiveFold(); var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false; var editor = atom.workspace.getActiveTextEditor(); var child; if (!editor || !foldObj || foldObj.children.length === 0) { return; } child = this.getLastFromHistory(); // check if the last item in history actually belongs to this parent if (!child && foldObj.children.indexOf(child) === -1) child = foldObj.children[0]; if (child) { this.moveCursor(child); } }, getParentFold(foldObj) { if (!foldObj) { return false; } // badly indented/formated code - there must be a parent so return the previous fold the next best chance of being the parent if (foldObj.parent === 'root' && foldObj.indentation > 0) { let index = this.folds.indexOf(foldObj.line); let prev = this.folds[index - 1]; if (prev || prev === 0) return prev; return false; } return foldObj.parent; }, addToHistory(fold) { var maxSize = 10; if (!this.history) { this.history = []; } else if (this.history.length > maxSize) { this.history.shift(); } this.history.push(fold); }, getLastFromHistory() { if (!this.history) { return undefined; } return this.history.pop(); }, clearHistory() { if (!this.history) return; this.history.length = 0; }, // gets all folds at indentation level getLevel(level) { //console.log(arguments.callee.name); return this.foldLevels[level]; }, parse(editor) { //console.log(arguments.callee.name); if (!editor) return; // initialize this.iniSettings(); this.clearSearchModal(); this.foldNavigatorView.clearContent(); this.clearHistory(); this.lines2fold = []; this.folds = []; this.visibleFolds = []; this.foldObjects = {}; this.foldObjectsArray = []; // we need this because fuzzaldrin-plus not able to find things in objects only in arrays or I do not know how this.foldLevels = {}; var numberOfRows = editor.getLastBufferRow(); var html = ""; var currentFold = null; var temporarilyLastParent = []; //loop through the lines of the active editor for (var i = 0; numberOfRows > i; i++) { if (editor.isFoldableAtBufferRow(i)) { let indentLevel = editor.indentationForBufferRow(i); let indentHtml = ""; let lineNumberSpan = ""; let lineContent = ""; let lineContentTrimmed = ""; let classList = "fold-navigator-item"; let id = ""; let gutter = '<span class="fold-navigator-gutter"></span>'; let content = ''; let parent; // add this line to folds this.folds.push(i); // add this line to foldLevels if (!this.foldLevels.hasOwnProperty(indentLevel)) { this.foldLevels[indentLevel] = []; } this.foldLevels[indentLevel].push(i); // chop array down - it can not be larger than the current indentLevel temporarilyLastParent.length = parseInt(indentLevel); parent = 'root'; if (temporarilyLastParent[indentLevel - 1] || temporarilyLastParent[indentLevel - 1] === 0) parent = temporarilyLastParent[indentLevel - 1]; if (this.foldObjects[parent]) { this.foldObjects[parent]['children'].push(i); } this.foldObjects[i] = { line: i, children: [], parent: parent, indentation: indentLevel, content: '', }; //temporarilyLastParent temporarilyLastParent[indentLevel] = i; for (let j = 0; j < indentLevel; j++) { indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>'; } lineContent = editor.lineTextForBufferRow(i); lineContentTrimmed = lineContent.trim(); // check if the content of the string matches one of those values when the previous line's content should be used instead // see issue here https://github.com/turigeza/fold-navigator/issues/12 if(this.settings.whenMatchedUsePreviousLineArray && this.settings.whenMatchedUsePreviousLineArray.indexOf(lineContentTrimmed) !== -1){ //&& i !== 0 lineContent = editor.lineTextForBufferRow(i - 1); }else if (lineContentTrimmed.length < this.settings.minLineLength) { // check if the line is longer than the minimum in the settings if not grab the next line instead lineContent = editor.lineTextForBufferRow(i + 1); } // default it to string seems to return undefined sometimes most likely only when the first row is { if(!lineContent){ lineContent = ''; } // check if line is too long if (lineContent.length > this.settings.maxLineContentLength) { lineContent = lineContent.substring(0, this.settings.maxLineContentLength) + '...'; } /* maybe in the future we should check for lines which are too short and grab the next row */ if (this.settings.showLineNumbers) { lineNumberSpan = '<span class="fold-navigator-line-number ">' + (i + 1) + '</span>'; } id = 'fold-navigator-item-' + i; classList += ' fold-navigator-item-' + i; classList += ' fold-navigator-item-indent-' + indentLevel; // escape html // add content to navigator if (indentLevel <= this.settings.maxFoldLevel) { currentFold = i; content = document.createElement('div'); content.appendChild(document.createTextNode(lineContent)); html += '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>'; this.foldObjects[i]['content'] = lineContent.trim(); this.foldObjectsArray.push(this.foldObjects[i]); this.visibleFolds.push(i); } } // add this fold to the line2fold lookup array this.lines2fold[i] = currentFold; } this.foldNavigatorView.setContent(html); this.selectRow(editor.getCursorBufferPosition().row); }, /* called every time onCursorChange */ selectRow(row) { //console.log(arguments.callee.name); var fold = this.lines2fold[row]; var line = this.foldNavigatorView.selectFold(fold); // autoscroll navigator panel if ((line) && !this.wasItOnClick && this.settings.autoScrollFoldNavigatorPanel) { line.scrollIntoViewIfNeeded(false); if(this.settings.log){ console.log(line); } } if (line) { this.wasItOnClick = false; } }, // not yet used idea stolen from tree view resizeStarted() { document.onmousemove = () => { this.resizePanel() }; document.onmouseup = () => { this.resizeStopped() }; }, // not yet used idea stolen from tree view resizeStopped() { document.offmousemove = () => { this.resizePanel() }; document.offmouseup = () => { this.resizeStopped() }; }, // not yet used idea stolen from tree view resizePanel(d) { var pageX = d.pageX; var which = d.which; if (which !== 1) { return this.resizeStopped(); } }, toggle() { return (this.panel.isVisible() ? this.panel.hide() : this.panel.show()); }, open() { var editor = atom.workspace.getActiveTextEditor(); return this.panel.show(); }, close() { return this.panel.hide(); }, moveCursor(row, wasItOnClick = false) { //console.log(arguments.callee.name); this.wasItOnClick = wasItOnClick; // setCursorBufferPosition dies if row is string row = parseInt(row); var editor = atom.workspace.getActiveTextEditor(); if (!editor || row < 0) return; //editor.unfoldBufferRow(row); if (this.settings.keepFoldingAllTime && !wasItOnClick) { editor.foldAll(); } this.unfoldSubfolds(row); editor.setCursorBufferPosition([row, 0]); editor.scrollToCursorPosition({ center: true }); }, navigatorElementOnClick() { //console.log(arguments.callee.name); var element = this.foldNavigatorView.getElement(); element.onclick = (event) => { var clicked = null; var row; var editor = atom.workspace.getActiveTextEditor(); if (event.target.matches('.fold-navigator-item')) { clicked = event.target; } else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-item')) { clicked = event.target.parentNode; } if (!clicked) return; row = clicked.dataset.row; //problem if (!row) return; if (editor && ((this.settings.keepFolding && !event.metaKey) || (!this.settings.keepFolding && event.metaKey))) { // fold all code before anything else sadly this triggers a lot of onDidChangeCursorPosition events editor.foldAll(); } this.moveCursor(row, true); }; }, foldActivePublic() { //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var editor = atom.workspace.getActiveTextEditor(); if ((!fold && fold !== 0) || !editor) return; editor.foldBufferRow(fold); }, unfoldSubfoldsPublic() { //console.log(arguments.callee.name); this.unfoldSubfolds(false, false, true); }, unfoldSubfolds(row = false, editor = false, force = false) { //console.log(arguments.callee.name); var fold = (row || row === 0) ? row : this.foldNavigatorView.getActiveFold(); if (!fold && fold !== 0) return; var foldObj = this.foldObjects[fold]; var editor = editor ? editor : atom.workspace.getActiveTextEditor(); if (!foldObj || !editor) return; editor.unfoldBufferRow(fold); if (!this.settings.unfoldAllSubfolds && !force) return; if (foldObj.children.length > 0) { foldObj.children.forEach( (value) => { this.unfoldSubfolds(value, editor) } ); } }, toggleActiveFold() { //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var editor = atom.workspace.getActiveTextEditor(); if ((!fold && fold !== 0) || !editor) return; if (editor.isFoldedAtBufferRow(fold)) { this.unfoldSubfolds(fold, editor, true); } else { editor.foldBufferRow(fold); } }, unfoldAtLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (lev) { lev.forEach((fold) => { editor.unfoldBufferRow(fold); }); editor.scrollToCursorPosition({ center: true }); } }, foldAtLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (lev) { lev.forEach((fold) => { editor.foldBufferRow(fold); }); editor.scrollToCursorPosition({ center: true }); } }, toggleFoldsLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (!lev) return; var first = lev[0]; if (!first && first !== 0) return; if (editor.isFoldedAtBufferRow(first)) { this.unfoldAtLevel(level); } else { this.foldAtLevel(level); } }, unfoldAtLevel1() { this.unfoldAtLevel(1); }, unfoldAtLevel2() { this.unfoldAtLevel(2); }, unfoldAtLevel3() { this.unfoldAtLevel(3); }, unfoldAtLevel4() { this.unfoldAtLevel(4); }, unfoldAtLevel5() { this.unfoldAtLevel(5); }, foldAtLevel1() { this.foldAtLevel(1); }, foldAtLevel2() { this.foldAtLevel(2); }, foldAtLevel3() { this.foldAtLevel(3); }, foldAtLevel4() { this.foldAtLevel(4); }, foldAtLevel5() { this.foldAtLevel(5); }, toggleFoldsLevel1() { this.toggleFoldsLevel(1); }, toggleFoldsLevel2() { this.toggleFoldsLevel(2); }, toggleFoldsLevel3() { this.toggleFoldsLevel(3); }, toggleFoldsLevel4() { this.toggleFoldsLevel(4); }, toggleFoldsLevel5() { this.toggleFoldsLevel(5); }, startTime() { this.time = new Date(); }, showTime(text) { console.log(text); console.log(new Date() - this.time); }, deactivate() { //console.log(arguments.callee.name); this.panel.destroy(); this.subscriptions.dispose(); this.foldNavigatorView.destroy(); if (this.onDidChangeCursorPositionSubscription) { this.onDidChangeCursorPositionSubscription.dispose(); } if (this.onDidStopChangingSubscription) { this.onDidStopChangingSubscription.dispose(); } //delete(this.searchModalElement); //delete(this.searchModalItems); //delete(this.searchModalInput); if (this.searchModal) { this.searchModal.destroy(); } }, /* we don't need this */ serialize() {} };
/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); const vscode_1 = require("vscode"); const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol"); const c2p = require("./codeConverter"); const p2c = require("./protocolConverter"); const Is = require("./utils/is"); const async_1 = require("./utils/async"); const UUID = require("./utils/uuid"); const progressPart_1 = require("./progressPart"); __export(require("vscode-languageserver-protocol")); class ConsoleLogger { error(message) { console.error(message); } warn(message) { console.warn(message); } info(message) { console.info(message); } log(message) { console.log(message); } } function createConnection(input, output, errorHandler, closeHandler) { let logger = new ConsoleLogger(); let connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger); connection.onError((data) => { errorHandler(data[0], data[1], data[2]); }); connection.onClose(closeHandler); let result = { listen: () => connection.listen(), sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params), onRequest: (type, handler) => connection.onRequest(Is.string(type) ? type : type.method, handler), sendNotification: (type, params) => connection.sendNotification(Is.string(type) ? type : type.method, params), onNotification: (type, handler) => connection.onNotification(Is.string(type) ? type : type.method, handler), onProgress: connection.onProgress, sendProgress: connection.sendProgress, trace: (value, tracer, sendNotificationOrTraceOptions) => { const defaultTraceOptions = { sendNotification: false, traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text }; if (sendNotificationOrTraceOptions === void 0) { connection.trace(value, tracer, defaultTraceOptions); } else if (Is.boolean(sendNotificationOrTraceOptions)) { connection.trace(value, tracer, sendNotificationOrTraceOptions); } else { connection.trace(value, tracer, sendNotificationOrTraceOptions); } }, initialize: (params) => connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params), shutdown: () => connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined), exit: () => connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type), onLogMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, handler), onShowMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, handler), onTelemetry: (handler) => connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, handler), didChangeConfiguration: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, params), didChangeWatchedFiles: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, params), didOpenTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, params), didChangeTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params), didCloseTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, params), didSaveTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, params), onDiagnostics: (handler) => connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, handler), dispose: () => connection.dispose() }; return result; } /** * An action to be performed when the connection is producing errors. */ var ErrorAction; (function (ErrorAction) { /** * Continue running the server. */ ErrorAction[ErrorAction["Continue"] = 1] = "Continue"; /** * Shutdown the server. */ ErrorAction[ErrorAction["Shutdown"] = 2] = "Shutdown"; })(ErrorAction = exports.ErrorAction || (exports.ErrorAction = {})); /** * An action to be performed when the connection to a server got closed. */ var CloseAction; (function (CloseAction) { /** * Don't restart the server. The connection stays closed. */ CloseAction[CloseAction["DoNotRestart"] = 1] = "DoNotRestart"; /** * Restart the server. */ CloseAction[CloseAction["Restart"] = 2] = "Restart"; })(CloseAction = exports.CloseAction || (exports.CloseAction = {})); class DefaultErrorHandler { constructor(name) { this.name = name; this.restarts = []; } error(_error, _message, count) { if (count && count <= 3) { return ErrorAction.Continue; } return ErrorAction.Shutdown; } closed() { this.restarts.push(Date.now()); if (this.restarts.length < 5) { return CloseAction.Restart; } else { let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; if (diff <= 3 * 60 * 1000) { vscode_1.window.showErrorMessage(`The ${this.name} server crashed 5 times in the last 3 minutes. The server will not be restarted.`); return CloseAction.DoNotRestart; } else { this.restarts.shift(); return CloseAction.Restart; } } } } var RevealOutputChannelOn; (function (RevealOutputChannelOn) { RevealOutputChannelOn[RevealOutputChannelOn["Info"] = 1] = "Info"; RevealOutputChannelOn[RevealOutputChannelOn["Warn"] = 2] = "Warn"; RevealOutputChannelOn[RevealOutputChannelOn["Error"] = 3] = "Error"; RevealOutputChannelOn[RevealOutputChannelOn["Never"] = 4] = "Never"; })(RevealOutputChannelOn = exports.RevealOutputChannelOn || (exports.RevealOutputChannelOn = {})); var State; (function (State) { State[State["Stopped"] = 1] = "Stopped"; State[State["Starting"] = 3] = "Starting"; State[State["Running"] = 2] = "Running"; })(State = exports.State || (exports.State = {})); var ClientState; (function (ClientState) { ClientState[ClientState["Initial"] = 0] = "Initial"; ClientState[ClientState["Starting"] = 1] = "Starting"; ClientState[ClientState["StartFailed"] = 2] = "StartFailed"; ClientState[ClientState["Running"] = 3] = "Running"; ClientState[ClientState["Stopping"] = 4] = "Stopping"; ClientState[ClientState["Stopped"] = 5] = "Stopped"; })(ClientState || (ClientState = {})); const SupportedSymbolKinds = [ vscode_languageserver_protocol_1.SymbolKind.File, vscode_languageserver_protocol_1.SymbolKind.Module, vscode_languageserver_protocol_1.SymbolKind.Namespace, vscode_languageserver_protocol_1.SymbolKind.Package, vscode_languageserver_protocol_1.SymbolKind.Class, vscode_languageserver_protocol_1.SymbolKind.Method, vscode_languageserver_protocol_1.SymbolKind.Property, vscode_languageserver_protocol_1.SymbolKind.Field, vscode_languageserver_protocol_1.SymbolKind.Constructor, vscode_languageserver_protocol_1.SymbolKind.Enum, vscode_languageserver_protocol_1.SymbolKind.Interface, vscode_languageserver_protocol_1.SymbolKind.Function, vscode_languageserver_protocol_1.SymbolKind.Variable, vscode_languageserver_protocol_1.SymbolKind.Constant, vscode_languageserver_protocol_1.SymbolKind.String, vscode_languageserver_protocol_1.SymbolKind.Number, vscode_languageserver_protocol_1.SymbolKind.Boolean, vscode_languageserver_protocol_1.SymbolKind.Array, vscode_languageserver_protocol_1.SymbolKind.Object, vscode_languageserver_protocol_1.SymbolKind.Key, vscode_languageserver_protocol_1.SymbolKind.Null, vscode_languageserver_protocol_1.SymbolKind.EnumMember, vscode_languageserver_protocol_1.SymbolKind.Struct, vscode_languageserver_protocol_1.SymbolKind.Event, vscode_languageserver_protocol_1.SymbolKind.Operator, vscode_languageserver_protocol_1.SymbolKind.TypeParameter ]; const SupportedCompletionItemKinds = [ vscode_languageserver_protocol_1.CompletionItemKind.Text, vscode_languageserver_protocol_1.CompletionItemKind.Method, vscode_languageserver_protocol_1.CompletionItemKind.Function, vscode_languageserver_protocol_1.CompletionItemKind.Constructor, vscode_languageserver_protocol_1.CompletionItemKind.Field, vscode_languageserver_protocol_1.CompletionItemKind.Variable, vscode_languageserver_protocol_1.CompletionItemKind.Class, vscode_languageserver_protocol_1.CompletionItemKind.Interface, vscode_languageserver_protocol_1.CompletionItemKind.Module, vscode_languageserver_protocol_1.CompletionItemKind.Property, vscode_languageserver_protocol_1.CompletionItemKind.Unit, vscode_languageserver_protocol_1.CompletionItemKind.Value, vscode_languageserver_protocol_1.CompletionItemKind.Enum, vscode_languageserver_protocol_1.CompletionItemKind.Keyword, vscode_languageserver_protocol_1.CompletionItemKind.Snippet, vscode_languageserver_protocol_1.CompletionItemKind.Color, vscode_languageserver_protocol_1.CompletionItemKind.File, vscode_languageserver_protocol_1.CompletionItemKind.Reference, vscode_languageserver_protocol_1.CompletionItemKind.Folder, vscode_languageserver_protocol_1.CompletionItemKind.EnumMember, vscode_languageserver_protocol_1.CompletionItemKind.Constant, vscode_languageserver_protocol_1.CompletionItemKind.Struct, vscode_languageserver_protocol_1.CompletionItemKind.Event, vscode_languageserver_protocol_1.CompletionItemKind.Operator, vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter ]; function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } var DynamicFeature; (function (DynamicFeature) { function is(value) { let candidate = value; return candidate && Is.func(candidate.register) && Is.func(candidate.unregister) && Is.func(candidate.dispose) && candidate.messages !== void 0; } DynamicFeature.is = is; })(DynamicFeature || (DynamicFeature = {})); class DocumentNotifiactions { constructor(_client, _event, _type, _middleware, _createParams, _selectorFilter) { this._client = _client; this._event = _event; this._type = _type; this._middleware = _middleware; this._createParams = _createParams; this._selectorFilter = _selectorFilter; this._selectors = new Map(); } static textDocumentFilter(selectors, textDocument) { for (const selector of selectors) { if (vscode_1.languages.match(selector, textDocument)) { return true; } } return false; } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = this._event(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(data) { if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) { if (this._middleware) { this._middleware(data, (data) => this._client.sendNotification(this._type, this._createParams(data))); } else { this._client.sendNotification(this._type, this._createParams(data)); } this.notificationSent(data); } } notificationSent(_data) { } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } getProvider(document) { for (const selector of this._selectors.values()) { if (vscode_1.languages.match(selector, document)) { return { send: (data) => { this.callback(data); } }; } } throw new Error(`No provider available for the given text document`); } } class DidOpenTextDocumentFeature extends DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(message, data) { super.register(message, data); if (!data.registerOptions.documentSelector) { return; } let documentSelector = data.registerOptions.documentSelector; vscode_1.workspace.textDocuments.forEach((textDocument) => { let uri = textDocument.uri.toString(); if (this._syncedDocuments.has(uri)) { return; } if (vscode_1.languages.match(documentSelector, textDocument)) { let middleware = this._client.clientOptions.middleware; let didOpen = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; if (middleware.didOpen) { middleware.didOpen(textDocument, didOpen); } else { didOpen(textDocument); } this._syncedDocuments.set(uri, textDocument); } }); } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.set(textDocument.uri.toString(), textDocument); } } class DidCloseTextDocumentFeature extends DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.delete(textDocument.uri.toString()); } unregister(id) { let selector = this._selectors.get(id); // The super call removed the selector from the map // of selectors. super.unregister(id); let selectors = this._selectors.values(); this._syncedDocuments.forEach((textDocument) => { if (vscode_1.languages.match(selector, textDocument) && !this._selectorFilter(selectors, textDocument)) { let middleware = this._client.clientOptions.middleware; let didClose = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; this._syncedDocuments.delete(textDocument.uri.toString()); if (middleware.didClose) { middleware.didClose(textDocument, didClose); } else { didClose(textDocument); } } }); } } class DidChangeTextDocumentFeature { constructor(_client) { this._client = _client; this._changeData = new Map(); this._forcingDelivery = false; } get messages() { return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change }) }); } } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this); } this._changeData.set(data.id, { documentSelector: data.registerOptions.documentSelector, syncKind: data.registerOptions.syncKind }); } callback(event) { // Text document changes are send for dirty changes as well. We don't // have dirty / undirty events in the LSP so we ignore content changes // with length zero. if (event.contentChanges.length === 0) { return; } for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, event.document)) { let middleware = this._client.clientOptions.middleware; if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) { let params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event); if (middleware.didChange) { middleware.didChange(event, () => this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params)); } else { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); } } else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { let didChange = (event) => { if (this._changeDelayer) { if (this._changeDelayer.uri !== event.document.uri.toString()) { // Use this force delivery to track boolean state. Otherwise we might call two times. this.forceDelivery(); this._changeDelayer.uri = event.document.uri.toString(); } this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }); } else { this._changeDelayer = { uri: event.document.uri.toString(), delayer: new async_1.Delayer(200) }; this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }, -1); } }; if (middleware.didChange) { middleware.didChange(event, didChange); } else { didChange(event); } } } } } unregister(id) { this._changeData.delete(id); if (this._changeData.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._changeDelayer = undefined; this._forcingDelivery = false; this._changeData.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } forceDelivery() { if (this._forcingDelivery || !this._changeDelayer) { return; } try { this._forcingDelivery = true; this._changeDelayer.delayer.forceDelivery(); } finally { this._forcingDelivery = false; } } getProvider(document) { for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, document)) { return { send: (event) => { this.callback(event); } }; } } throw new Error(`No provider available for the given text document`); } } class WillSaveFeature extends DocumentNotifiactions { constructor(client) { super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, client.clientOptions.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (selectors, willSaveEvent) => DocumentNotifiactions.textDocumentFilter(selectors, willSaveEvent.document)); } get messages() { return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } } class WillSaveWaitUntilFeature { constructor(_client) { this._client = _client; this._selectors = new Map(); } get messages() { return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSaveWaitUntil = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(event) { if (DocumentNotifiactions.textDocumentFilter(this._selectors.values(), event.document)) { let middleware = this._client.clientOptions.middleware; let willSaveWaitUntil = (event) => { return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then((edits) => { let vEdits = this._client.protocol2CodeConverter.asTextEdits(edits); return vEdits === void 0 ? [] : vEdits; }); }; event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event)); } } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } } class DidSaveTextDocumentFeature extends DocumentNotifiactions { constructor(client) { super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, client.clientOptions.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), DocumentNotifiactions.textDocumentFilter); } get messages() { return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').didSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { includeText: !!textDocumentSyncOptions.save.includeText }) }); } } register(method, data) { this._includeText = !!data.registerOptions.includeText; super.register(method, data); } } class FileSystemWatcherFeature { constructor(_client, _notifyFileEvent) { this._client = _client; this._notifyFileEvent = _notifyFileEvent; this._watchers = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true; } initialize(_capabilities, _documentSelector) { } register(_method, data) { if (!Array.isArray(data.registerOptions.watchers)) { return; } let disposeables = []; for (let watcher of data.registerOptions.watchers) { if (!Is.string(watcher.globPattern)) { continue; } let watchCreate = true, watchChange = true, watchDelete = true; if (watcher.kind !== void 0 && watcher.kind !== null) { watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0; watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0; watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0; } let fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(watcher.globPattern, !watchCreate, !watchChange, !watchDelete); this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete); disposeables.push(fileSystemWatcher); } this._watchers.set(data.id, disposeables); } registerRaw(id, fileSystemWatchers) { let disposeables = []; for (let fileSystemWatcher of fileSystemWatchers) { this.hookListeners(fileSystemWatcher, true, true, true, disposeables); } this._watchers.set(id, disposeables); } hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) { if (watchCreate) { fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Created }), null, listeners); } if (watchChange) { fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Changed }), null, listeners); } if (watchDelete) { fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Deleted }), null, listeners); } } unregister(id) { let disposeables = this._watchers.get(id); if (disposeables) { for (let disposable of disposeables) { disposable.dispose(); } } } dispose() { this._watchers.forEach((disposeables) => { for (let disposable of disposeables) { disposable.dispose(); } }); this._watchers.clear(); } } class TextDocumentFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._registrations = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wrong feature. Requested ${message.method} but reached feature ${this.messages.method}`); } if (!data.registerOptions.documentSelector) { return; } let registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((value) => { value.disposable.dispose(); }); this._registrations.clear(); } getRegistration(documentSelector, capability) { if (!capability) { return [undefined, undefined]; } else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) { const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid(); const selector = capability.documentSelector || documentSelector; if (selector) { return [id, Object.assign({}, capability, { documentSelector: selector })]; } } else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) { if (!documentSelector) { return [undefined, undefined]; } let options = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); return [UUID.generateUuid(), options]; } return [undefined, undefined]; } getRegistrationOptions(documentSelector, capability) { if (!documentSelector || !capability) { return undefined; } return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); } getProvider(textDocument) { for (const registration of this._registrations.values()) { let selector = registration.data.registerOptions.documentSelector; if (selector !== null && vscode_1.languages.match(selector, textDocument)) { return registration.provider; } } throw new Error(`The feature has no registration for the provided text document ${textDocument.uri.toString()}`); } } exports.TextDocumentFeature = TextDocumentFeature; class WorkspaceFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._registrations = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wron feature. Requested ${message.method} but reached feature ${this.messages.method}`); } const registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((registration) => { registration.disposable.dispose(); }); this._registrations.clear(); } getProviders() { const result = []; for (const registration of this._registrations.values()) { result.push(registration.provider); } return result; } } class CompletionItemFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CompletionRequest.type); } fillClientCapabilities(capabilites) { let completion = ensure(ensure(capabilites, 'textDocument'), 'completion'); completion.dynamicRegistration = true; completion.contextSupport = true; completion.completionItem = { snippetSupport: true, commitCharactersSupport: true, documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText], deprecatedSupport: true, preselectSupport: true, tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] } }; completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const triggerCharacters = options.triggerCharacters || []; const provider = { provideCompletionItems: (document, position, token, context) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const provideCompletionItems = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document, position, context), token).then(client.protocol2CodeConverter.asCompletionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, error); return Promise.resolve([]); }); }; return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token); }, resolveCompletionItem: options.resolveProvider ? (item, token) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const resolveCompletionItem = (item, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item), token).then(client.protocol2CodeConverter.asCompletionItem, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, error); return Promise.resolve(item); }); }; return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); } : undefined }; return [vscode_1.languages.registerCompletionItemProvider(options.documentSelector, provider, ...triggerCharacters), provider]; } } class HoverFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.HoverRequest.type); } fillClientCapabilities(capabilites) { const hoverCapability = (ensure(ensure(capabilites, 'textDocument'), 'hover')); hoverCapability.dynamicRegistration = true; hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText]; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideHover: (document, position, token) => { const client = this._client; const provideHover = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asHover, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token); } }; return [vscode_1.languages.registerHoverProvider(options.documentSelector, provider), provider]; } } class SignatureHelpFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type); } fillClientCapabilities(capabilites) { let config = ensure(ensure(capabilites, 'textDocument'), 'signatureHelp'); config.dynamicRegistration = true; config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] }; config.signatureInformation.parameterInformation = { labelOffsetSupport: true }; config.contextSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideSignatureHelp: (document, position, token, context) => { const client = this._client; const providerSignatureHelp = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document, position, context), token).then(client.protocol2CodeConverter.asSignatureHelp, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) : providerSignatureHelp(document, position, context, token); } }; let disposable; if (options.retriggerCharacters === undefined) { const triggerCharacters = options.triggerCharacters || []; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, ...triggerCharacters); } else { const metaData = { triggerCharacters: options.triggerCharacters || [], retriggerCharacters: options.retriggerCharacters || [] }; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, metaData); } return [disposable, provider]; } } class DefinitionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DefinitionRequest.type); } fillClientCapabilities(capabilites) { let definitionSupport = ensure(ensure(capabilites, 'textDocument'), 'definition'); definitionSupport.dynamicRegistration = true; definitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDefinition: (document, position, token) => { const client = this._client; const provideDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token); } }; return [vscode_1.languages.registerDefinitionProvider(options.documentSelector, provider), provider]; } } class ReferencesFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.ReferencesRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'references').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideReferences: (document, position, options, token) => { const client = this._client; const _providerReferences = (document, position, options, token) => { return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document, position, options), token).then(client.protocol2CodeConverter.asReferences, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideReferences ? middleware.provideReferences(document, position, options, token, _providerReferences) : _providerReferences(document, position, options, token); } }; return [vscode_1.languages.registerReferenceProvider(options.documentSelector, provider), provider]; } } class DocumentHighlightFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'documentHighlight').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentHighlights: (document, position, token) => { const client = this._client; const _provideDocumentHighlights = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDocumentHighlights, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document, position, token); } }; return [vscode_1.languages.registerDocumentHighlightProvider(options.documentSelector, provider), provider]; } } class DocumentSymbolFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentSymbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; symbolCapabilities.hierarchicalDocumentSymbolSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentSymbols: (document, token) => { const client = this._client; const _provideDocumentSymbols = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document), token).then((data) => { if (data === null) { return undefined; } if (data.length === 0) { return []; } else { let element = data[0]; if (vscode_languageserver_protocol_1.DocumentSymbol.is(element)) { return client.protocol2CodeConverter.asDocumentSymbols(data); } else { return client.protocol2CodeConverter.asSymbolInformations(data); } } }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) : _provideDocumentSymbols(document, token); } }; return [vscode_1.languages.registerDocumentSymbolProvider(options.documentSelector, provider), provider]; } } class WorkspaceSymbolFeature extends WorkspaceFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'workspace'), 'symbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; } initialize(capabilities) { if (!capabilities.workspaceSymbolProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider }); } registerLanguageProvider(_options) { const provider = { provideWorkspaceSymbols: (query, token) => { const client = this._client; const provideWorkspaceSymbols = (query, token) => { return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then(client.protocol2CodeConverter.asSymbolInformations, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); } }; return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider]; } } class CodeActionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeActionRequest.type); } fillClientCapabilities(capabilites) { const cap = ensure(ensure(capabilites, 'textDocument'), 'codeAction'); cap.dynamicRegistration = true; cap.isPreferredSupport = true; cap.codeActionLiteralSupport = { codeActionKind: { valueSet: [ vscode_languageserver_protocol_1.CodeActionKind.Empty, vscode_languageserver_protocol_1.CodeActionKind.QuickFix, vscode_languageserver_protocol_1.CodeActionKind.Refactor, vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract, vscode_languageserver_protocol_1.CodeActionKind.RefactorInline, vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite, vscode_languageserver_protocol_1.CodeActionKind.Source, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports ] } }; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideCodeActions: (document, range, context, token) => { const client = this._client; const _provideCodeActions = (document, range, context, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), context: client.code2ProtocolConverter.asCodeActionContext(context) }; return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token).then((values) => { if (values === null) { return undefined; } const result = []; for (let item of values) { if (vscode_languageserver_protocol_1.Command.is(item)) { result.push(client.protocol2CodeConverter.asCommand(item)); } else { result.push(client.protocol2CodeConverter.asCodeAction(item)); } } return result; }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) : _provideCodeActions(document, range, context, token); } }; return [vscode_1.languages.registerCodeActionsProvider(options.documentSelector, provider, (options.codeActionKinds ? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) } : undefined)), provider]; } } class CodeLensFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeLensRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'codeLens').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideCodeLenses: (document, token) => { const client = this._client; const provideCodeLenses = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then(client.protocol2CodeConverter.asCodeLenses, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token); }, resolveCodeLens: (options.resolveProvider) ? (codeLens, token) => { const client = this._client; const resolveCodeLens = (codeLens, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then(client.protocol2CodeConverter.asCodeLens, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, error); return codeLens; }); }; const middleware = client.clientOptions.middleware; return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); } : undefined }; return [vscode_1.languages.registerCodeLensProvider(options.documentSelector, provider), provider]; } } class DocumentFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'formatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentFormattingEdits: (document, options, token) => { const client = this._client; const provideDocumentFormattingEdits = (document, options, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options, token); } }; return [vscode_1.languages.registerDocumentFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentRangeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'rangeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentRangeFormattingEdits: (document, range, options, token) => { const client = this._client; const provideDocumentRangeFormattingEdits = (document, range, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options, token); } }; return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentOnTypeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideOnTypeFormattingEdits: (document, position, ch, options, token) => { const client = this._client; const provideOnTypeFormattingEdits = (document, position, ch, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), ch: ch, options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options, token); } }; const moreTriggerCharacter = options.moreTriggerCharacter || []; return [vscode_1.languages.registerOnTypeFormattingEditProvider(options.documentSelector, provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider]; } } class RenameFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.RenameRequest.type); } fillClientCapabilities(capabilites) { let rename = ensure(ensure(capabilites, 'textDocument'), 'rename'); rename.dynamicRegistration = true; rename.prepareSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider); if (!options) { return; } if (Is.boolean(capabilities.renameProvider)) { options.prepareProvider = false; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideRenameEdits: (document, position, newName, token) => { const client = this._client; const provideRenameEdits = (document, position, newName, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), newName: newName }; return client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token).then(client.protocol2CodeConverter.asWorkspaceEdit, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; const middleware = client.clientOptions.middleware; return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token); }, prepareRename: options.prepareProvider ? (document, position, token) => { const client = this._client; const prepareRename = (document, position, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), }; return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token).then((result) => { if (vscode_languageserver_protocol_1.Range.is(result)) { return client.protocol2CodeConverter.asRange(result); } else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) { return { range: client.protocol2CodeConverter.asRange(result.range), placeholder: result.placeholder }; } // To cancel the rename vscode API expects a rejected promise. return Promise.reject(new Error(`The element can't be renamed.`)); }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; const middleware = client.clientOptions.middleware; return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token); } : undefined }; return [vscode_1.languages.registerRenameProvider(options.documentSelector, provider), provider]; } } class DocumentLinkFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type); } fillClientCapabilities(capabilites) { const documentLinkCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentLink'); documentLinkCapabilities.dynamicRegistration = true; documentLinkCapabilities.tooltipSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentLinks: (document, token) => { const client = this._client; const provideDocumentLinks = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then(client.protocol2CodeConverter.asDocumentLinks, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token); }, resolveDocumentLink: options.resolveProvider ? (link, token) => { const client = this._client; let resolveDocumentLink = (link, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then(client.protocol2CodeConverter.asDocumentLink, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, error); return Promise.resolve(link); }); }; const middleware = client.clientOptions.middleware; return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); } : undefined }; return [vscode_1.languages.registerDocumentLinkProvider(options.documentSelector, provider), provider]; } } class ConfigurationFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeConfiguration').dynamicRegistration = true; } initialize() { let section = this._client.clientOptions.synchronize.configurationSection; if (section !== void 0) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { section: section } }); } } register(_message, data) { let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => { this.onDidChangeConfiguration(data.registerOptions.section, event); }); this._listeners.set(data.id, disposable); if (data.registerOptions.section !== void 0) { this.onDidChangeConfiguration(data.registerOptions.section, undefined); } } unregister(id) { let disposable = this._listeners.get(id); if (disposable) { this._listeners.delete(id); disposable.dispose(); } } dispose() { for (let disposable of this._listeners.values()) { disposable.dispose(); } this._listeners.clear(); } onDidChangeConfiguration(configurationSection, event) { let sections; if (Is.string(configurationSection)) { sections = [configurationSection]; } else { sections = configurationSection; } if (sections !== void 0 && event !== void 0) { let affected = sections.some((section) => event.affectsConfiguration(section)); if (!affected) { return; } } let didChangeConfiguration = (sections) => { if (sections === void 0) { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null }); return; } this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections) }); }; let middleware = this.getMiddleware(); middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections); } extractSettingsInformation(keys) { function ensurePath(config, path) { let current = config; for (let i = 0; i < path.length - 1; i++) { let obj = current[path[i]]; if (!obj) { obj = Object.create(null); current[path[i]] = obj; } current = obj; } return current; } let resource = this._client.clientOptions.workspaceFolder ? this._client.clientOptions.workspaceFolder.uri : undefined; let result = Object.create(null); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let index = key.indexOf('.'); let config = null; if (index >= 0) { config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1)); } else { config = vscode_1.workspace.getConfiguration(key, resource); } if (config) { let path = keys[i].split('.'); ensurePath(result, path)[path[path.length - 1]] = config; } } return result; } getMiddleware() { let middleware = this._client.clientOptions.middleware; if (middleware.workspace && middleware.workspace.didChangeConfiguration) { return middleware.workspace.didChangeConfiguration; } else { return undefined; } } } class ExecuteCommandFeature { constructor(_client) { this._client = _client; this._commands = new Map(); } get messages() { return vscode_languageserver_protocol_1.ExecuteCommandRequest.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true; } initialize(capabilities) { if (!capabilities.executeCommandProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, capabilities.executeCommandProvider) }); } register(_message, data) { const client = this._client; const middleware = client.clientOptions.middleware; const executeCommand = (command, args) => { let params = { command, arguments: args }; return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, error); }); }; if (data.registerOptions.commands) { const disposeables = []; for (const command of data.registerOptions.commands) { disposeables.push(vscode_1.commands.registerCommand(command, (...args) => { return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args); })); } this._commands.set(data.id, disposeables); } } unregister(id) { let disposeables = this._commands.get(id); if (disposeables) { disposeables.forEach(disposable => disposable.dispose()); } } dispose() { this._commands.forEach((value) => { value.forEach(disposable => disposable.dispose()); }); this._commands.clear(); } } var MessageTransports; (function (MessageTransports) { function is(value) { let candidate = value; return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer); } MessageTransports.is = is; })(MessageTransports = exports.MessageTransports || (exports.MessageTransports = {})); class OnReady { constructor(_resolve, _reject) { this._resolve = _resolve; this._reject = _reject; this._used = false; } get isUsed() { return this._used; } resolve() { this._used = true; this._resolve(); } reject(error) { this._used = true; this._reject(error); } } class BaseLanguageClient { constructor(id, name, clientOptions) { this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; this._features = []; this._method2Message = new Map(); this._dynamicFeatures = new Map(); this._id = id; this._name = name; clientOptions = clientOptions || {}; this._clientOptions = { documentSelector: clientOptions.documentSelector || [], synchronize: clientOptions.synchronize || {}, diagnosticCollectionName: clientOptions.diagnosticCollectionName, outputChannelName: clientOptions.outputChannelName || this._name, revealOutputChannelOn: clientOptions.revealOutputChannelOn || RevealOutputChannelOn.Error, stdioEncoding: clientOptions.stdioEncoding || 'utf8', initializationOptions: clientOptions.initializationOptions, initializationFailedHandler: clientOptions.initializationFailedHandler, progressOnInitialization: !!clientOptions.progressOnInitialization, errorHandler: clientOptions.errorHandler || new DefaultErrorHandler(this._name), middleware: clientOptions.middleware || {}, uriConverters: clientOptions.uriConverters, workspaceFolder: clientOptions.workspaceFolder }; this._clientOptions.synchronize = this._clientOptions.synchronize || {}; this.state = ClientState.Initial; this._connectionPromise = undefined; this._resolvedConnection = undefined; this._initializeResult = undefined; if (clientOptions.outputChannel) { this._outputChannel = clientOptions.outputChannel; this._disposeOutputChannel = false; } else { this._outputChannel = undefined; this._disposeOutputChannel = true; } this._traceOutputChannel = clientOptions.traceOutputChannel; this._listeners = undefined; this._providers = undefined; this._diagnostics = undefined; this._fileEvents = []; this._fileEventDelayer = new async_1.Delayer(250); this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); this._onStop = undefined; this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter(); this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter(); this._tracer = { log: (messageOrDataObject, data) => { if (Is.string(messageOrDataObject)) { this.logTrace(messageOrDataObject, data); } else { this.logObjectTrace(messageOrDataObject); } }, }; this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined); this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined); this._syncedDocuments = new Map(); this.registerBuiltinFeatures(); } get state() { return this._state; } set state(value) { let oldState = this.getPublicState(); this._state = value; let newState = this.getPublicState(); if (newState !== oldState) { this._stateChangeEmitter.fire({ oldState, newState }); } } getPublicState() { if (this.state === ClientState.Running) { return State.Running; } else if (this.state === ClientState.Starting) { return State.Starting; } else { return State.Stopped; } } get initializeResult() { return this._initializeResult; } sendRequest(type, ...params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { return this._resolvedConnection.sendRequest(type, ...params); } catch (error) { this.error(`Sending request ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onRequest(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { this._resolvedConnection.onRequest(type, handler); } catch (error) { this.error(`Registering request handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } sendNotification(type, params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendNotification(type, params); } catch (error) { this.error(`Sending notification ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onNotification(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { this._resolvedConnection.onNotification(type, handler); } catch (error) { this.error(`Registering notification handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onProgress(type, token, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { return this._resolvedConnection.onProgress(type, token, handler); } catch (error) { this.error(`Registering progress handler for token ${token} failed.`, error); throw error; } } sendProgress(type, token, value) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendProgress(type, token, value); } catch (error) { this.error(`Sending progress for token ${token} failed.`, error); throw error; } } get clientOptions() { return this._clientOptions; } get protocol2CodeConverter() { return this._p2c; } get code2ProtocolConverter() { return this._c2p; } get onTelemetry() { return this._telemetryEmitter.event; } get onDidChangeState() { return this._stateChangeEmitter.event; } get outputChannel() { if (!this._outputChannel) { this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name); } return this._outputChannel; } get traceOutputChannel() { if (this._traceOutputChannel) { return this._traceOutputChannel; } return this.outputChannel; } get diagnostics() { return this._diagnostics; } createDefaultErrorHandler() { return new DefaultErrorHandler(this._name); } set trace(value) { this._trace = value; this.onReady().then(() => { this.resolveConnection().then((connection) => { connection.trace(this._trace, this._tracer, { sendNotification: false, traceFormat: this._traceFormat }); }); }, () => { }); } data2String(data) { if (data instanceof vscode_languageserver_protocol_1.ResponseError) { const responseError = data; return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`; } if (data instanceof Error) { if (Is.string(data.stack)) { return data.stack; } return data.message; } if (Is.string(data)) { return data; } return data.toString(); } info(message, data) { this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) { this.showNotificationMessage(); } } warn(message, data) { this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) { this.showNotificationMessage(); } } error(message, data) { this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) { this.showNotificationMessage(); } } showNotificationMessage() { vscode_1.window.showInformationMessage('A request has failed. See the output for more information.', 'Go to output').then(() => { this.outputChannel.show(true); }); } logTrace(message, data) { this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.traceOutputChannel.appendLine(this.data2String(data)); } } logObjectTrace(data) { if (data.isLSPMessage && data.type) { this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `); } else { this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `); } if (data) { this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`); } } needsStart() { return this.state === ClientState.Initial || this.state === ClientState.Stopping || this.state === ClientState.Stopped; } needsStop() { return this.state === ClientState.Starting || this.state === ClientState.Running; } onReady() { return this._onReady; } isConnectionActive() { return this.state === ClientState.Running && !!this._resolvedConnection; } start() { if (this._onReadyCallbacks.isUsed) { this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); } this._listeners = []; this._providers = []; // If we restart then the diagnostics collection is reused. if (!this._diagnostics) { this._diagnostics = this._clientOptions.diagnosticCollectionName ? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName) : vscode_1.languages.createDiagnosticCollection(); } this.state = ClientState.Starting; this.resolveConnection().then((connection) => { connection.onLogMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: this.error(message.message); break; case vscode_languageserver_protocol_1.MessageType.Warning: this.warn(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: this.info(message.message); break; default: this.outputChannel.appendLine(message.message); } }); connection.onShowMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: vscode_1.window.showErrorMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Warning: vscode_1.window.showWarningMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: vscode_1.window.showInformationMessage(message.message); break; default: vscode_1.window.showInformationMessage(message.message); } }); connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => { let messageFunc; switch (params.type) { case vscode_languageserver_protocol_1.MessageType.Error: messageFunc = vscode_1.window.showErrorMessage; break; case vscode_languageserver_protocol_1.MessageType.Warning: messageFunc = vscode_1.window.showWarningMessage; break; case vscode_languageserver_protocol_1.MessageType.Info: messageFunc = vscode_1.window.showInformationMessage; break; default: messageFunc = vscode_1.window.showInformationMessage; } let actions = params.actions || []; return messageFunc(params.message, ...actions); }); connection.onTelemetry((data) => { this._telemetryEmitter.fire(data); }); connection.listen(); // Error is handled in the initialize call. return this.initialize(connection); }).then(undefined, (error) => { this.state = ClientState.StartFailed; this._onReadyCallbacks.reject(error); this.error('Starting client failed', error); vscode_1.window.showErrorMessage(`Couldn't start client ${this._name}`); }); return new vscode_1.Disposable(() => { if (this.needsStop()) { this.stop(); } }); } resolveConnection() { if (!this._connectionPromise) { this._connectionPromise = this.createConnection(); } return this._connectionPromise; } initialize(connection) { this.refreshTrace(connection, false); let initOption = this._clientOptions.initializationOptions; let rootPath = this._clientOptions.workspaceFolder ? this._clientOptions.workspaceFolder.uri.fsPath : this._clientGetRootPath(); let initParams = { processId: process.pid, clientInfo: { name: 'vscode', version: vscode_1.version }, rootPath: rootPath ? rootPath : null, rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null, capabilities: this.computeClientCapabilities(), initializationOptions: Is.func(initOption) ? initOption() : initOption, trace: vscode_languageserver_protocol_1.Trace.toString(this._trace), workspaceFolders: null }; this.fillInitializeParams(initParams); if (this._clientOptions.progressOnInitialization) { const token = UUID.generateUuid(); const part = new progressPart_1.ProgressPart(connection, token); initParams.workDoneToken = token; return this.doInitialize(connection, initParams).then((result) => { part.done(); return result; }, (error) => { part.cancel(); throw error; }); } else { return this.doInitialize(connection, initParams); } } doInitialize(connection, initParams) { return connection.initialize(initParams).then((result) => { this._resolvedConnection = connection; this._initializeResult = result; this.state = ClientState.Running; let textDocumentSyncOptions = undefined; if (Is.number(result.capabilities.textDocumentSync)) { if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { textDocumentSyncOptions = { openClose: false, change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None, save: undefined }; } else { textDocumentSyncOptions = { openClose: true, change: result.capabilities.textDocumentSync, save: { includeText: false } }; } } else if (result.capabilities.textDocumentSync !== void 0 && result.capabilities.textDocumentSync !== null) { textDocumentSyncOptions = result.capabilities.textDocumentSync; } this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions }); connection.onDiagnostics(params => this.handleDiagnostics(params)); connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params => this.handleRegistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params => this.handleUnregistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params)); connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {}); this.hookFileEvents(connection); this.hookConfigurationChanged(connection); this.initializeFeatures(connection); this._onReadyCallbacks.resolve(); return result; }).then(undefined, (error) => { if (this._clientOptions.initializationFailedHandler) { if (this._clientOptions.initializationFailedHandler(error)) { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } } else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) { vscode_1.window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => { if (item && item.id === 'retry') { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } }); } else { if (error && error.message) { vscode_1.window.showErrorMessage(error.message); } this.error('Server initialization failed.', error); this.stop(); this._onReadyCallbacks.reject(error); } throw error; }); } _clientGetRootPath() { let folders = vscode_1.workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } let folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } return undefined; } stop() { this._initializeResult = undefined; if (!this._connectionPromise) { this.state = ClientState.Stopped; return Promise.resolve(); } if (this.state === ClientState.Stopping && this._onStop) { return this._onStop; } this.state = ClientState.Stopping; this.cleanUp(false); // unhook listeners return this._onStop = this.resolveConnection().then(connection => { return connection.shutdown().then(() => { connection.exit(); connection.dispose(); this.state = ClientState.Stopped; this.cleanUpChannel(); this._onStop = undefined; this._connectionPromise = undefined; this._resolvedConnection = undefined; }); }); } cleanUp(channel = true, diagnostics = true) { if (this._listeners) { this._listeners.forEach(listener => listener.dispose()); this._listeners = undefined; } if (this._providers) { this._providers.forEach(provider => provider.dispose()); this._providers = undefined; } if (this._syncedDocuments) { this._syncedDocuments.clear(); } for (let handler of this._dynamicFeatures.values()) { handler.dispose(); } if (channel) { this.cleanUpChannel(); } if (diagnostics && this._diagnostics) { this._diagnostics.dispose(); this._diagnostics = undefined; } } cleanUpChannel() { if (this._outputChannel && this._disposeOutputChannel) { this._outputChannel.dispose(); this._outputChannel = undefined; } } notifyFileEvent(event) { var _a; const client = this; function didChangeWatchedFile(event) { client._fileEvents.push(event); client._fileEventDelayer.trigger(() => { client.onReady().then(() => { client.resolveConnection().then(connection => { if (client.isConnectionActive()) { client.forceDocumentSync(); connection.didChangeWatchedFiles({ changes: client._fileEvents }); } client._fileEvents = []; }); }, (error) => { client.error(`Notify file events failed.`, error); }); }); } const workSpaceMiddleware = (_a = this.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; (workSpaceMiddleware === null || workSpaceMiddleware === void 0 ? void 0 : workSpaceMiddleware.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event); } forceDocumentSync() { this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method).forceDelivery(); } handleDiagnostics(params) { if (!this._diagnostics) { return; } let uri = this._p2c.asUri(params.uri); let diagnostics = this._p2c.asDiagnostics(params.diagnostics); let middleware = this.clientOptions.middleware; if (middleware.handleDiagnostics) { middleware.handleDiagnostics(uri, diagnostics, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics)); } else { this.setDiagnostics(uri, diagnostics); } } setDiagnostics(uri, diagnostics) { if (!this._diagnostics) { return; } this._diagnostics.set(uri, diagnostics); } createConnection() { let errorHandler = (error, message, count) => { this.handleConnectionError(error, message, count); }; let closeHandler = () => { this.handleConnectionClosed(); }; return this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8').then((transports) => { return createConnection(transports.reader, transports.writer, errorHandler, closeHandler); }); } handleConnectionClosed() { // Check whether this is a normal shutdown in progress or the client stopped normally. if (this.state === ClientState.Stopping || this.state === ClientState.Stopped) { return; } try { if (this._resolvedConnection) { this._resolvedConnection.dispose(); } } catch (error) { // Disposing a connection could fail if error cases. } let action = CloseAction.DoNotRestart; try { action = this._clientOptions.errorHandler.closed(); } catch (error) { // Ignore errors coming from the error handler. } this._connectionPromise = undefined; this._resolvedConnection = undefined; if (action === CloseAction.DoNotRestart) { this.error('Connection to server got closed. Server will not be restarted.'); this.state = ClientState.Stopped; this.cleanUp(false, true); } else if (action === CloseAction.Restart) { this.info('Connection to server got closed. Server will restart.'); this.cleanUp(false, false); this.state = ClientState.Initial; this.start(); } } handleConnectionError(error, message, count) { let action = this._clientOptions.errorHandler.error(error, message, count); if (action === ErrorAction.Shutdown) { this.error('Connection to server is erroring. Shutting down server.'); this.stop(); } } hookConfigurationChanged(connection) { vscode_1.workspace.onDidChangeConfiguration(() => { this.refreshTrace(connection, true); }); } refreshTrace(connection, sendNotification = false) { let config = vscode_1.workspace.getConfiguration(this._id); let trace = vscode_languageserver_protocol_1.Trace.Off; let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; if (config) { const traceConfig = config.get('trace.server', 'off'); if (typeof traceConfig === 'string') { trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig); } else { trace = vscode_languageserver_protocol_1.Trace.fromString(config.get('trace.server.verbosity', 'off')); traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get('trace.server.format', 'text')); } } this._trace = trace; this._traceFormat = traceFormat; connection.trace(this._trace, this._tracer, { sendNotification, traceFormat: this._traceFormat }); } hookFileEvents(_connection) { let fileEvents = this._clientOptions.synchronize.fileEvents; if (!fileEvents) { return; } let watchers; if (Is.array(fileEvents)) { watchers = fileEvents; } else { watchers = [fileEvents]; } if (!watchers) { return; } this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers); } registerFeatures(features) { for (let feature of features) { this.registerFeature(feature); } } registerFeature(feature) { this._features.push(feature); if (DynamicFeature.is(feature)) { let messages = feature.messages; if (Array.isArray(messages)) { for (let message of messages) { this._method2Message.set(message.method, message); this._dynamicFeatures.set(message.method, feature); } } else { this._method2Message.set(messages.method, messages); this._dynamicFeatures.set(messages.method, feature); } } } getFeature(request) { return this._dynamicFeatures.get(request); } registerBuiltinFeatures() { this.registerFeature(new ConfigurationFeature(this)); this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new DidChangeTextDocumentFeature(this)); this.registerFeature(new WillSaveFeature(this)); this.registerFeature(new WillSaveWaitUntilFeature(this)); this.registerFeature(new DidSaveTextDocumentFeature(this)); this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); this.registerFeature(new CompletionItemFeature(this)); this.registerFeature(new HoverFeature(this)); this.registerFeature(new SignatureHelpFeature(this)); this.registerFeature(new DefinitionFeature(this)); this.registerFeature(new ReferencesFeature(this)); this.registerFeature(new DocumentHighlightFeature(this)); this.registerFeature(new DocumentSymbolFeature(this)); this.registerFeature(new WorkspaceSymbolFeature(this)); this.registerFeature(new CodeActionFeature(this)); this.registerFeature(new CodeLensFeature(this)); this.registerFeature(new DocumentFormattingFeature(this)); this.registerFeature(new DocumentRangeFormattingFeature(this)); this.registerFeature(new DocumentOnTypeFormattingFeature(this)); this.registerFeature(new RenameFeature(this)); this.registerFeature(new DocumentLinkFeature(this)); this.registerFeature(new ExecuteCommandFeature(this)); } fillInitializeParams(params) { for (let feature of this._features) { if (Is.func(feature.fillInitializeParams)) { feature.fillInitializeParams(params); } } } computeClientCapabilities() { let result = {}; ensure(result, 'workspace').applyEdit = true; let workspaceEdit = ensure(ensure(result, 'workspace'), 'workspaceEdit'); workspaceEdit.documentChanges = true; workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete]; workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional; let diagnostics = ensure(ensure(result, 'textDocument'), 'publishDiagnostics'); diagnostics.relatedInformation = true; diagnostics.versionSupport = false; diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] }; for (let feature of this._features) { feature.fillClientCapabilities(result); } return result; } initializeFeatures(_connection) { let documentSelector = this._clientOptions.documentSelector; for (let feature of this._features) { feature.initialize(this._capabilities, documentSelector); } } handleRegistrationRequest(params) { return new Promise((resolve, reject) => { for (let registration of params.registrations) { const feature = this._dynamicFeatures.get(registration.method); if (!feature) { reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); return; } const options = registration.registerOptions || {}; options.documentSelector = options.documentSelector || this._clientOptions.documentSelector; const data = { id: registration.id, registerOptions: options }; feature.register(this._method2Message.get(registration.method), data); } resolve(); }); } handleUnregistrationRequest(params) { return new Promise((resolve, reject) => { for (let unregistration of params.unregisterations) { const feature = this._dynamicFeatures.get(unregistration.method); if (!feature) { reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); return; } feature.unregister(unregistration.id); } resolve(); }); } handleApplyWorkspaceEdit(params) { // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit. // However doing it here adds some safety since the server can lag more behind then an extension. let workspaceEdit = params.edit; let openTextDocuments = new Map(); vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)); let versionMismatch = false; if (workspaceEdit.documentChanges) { for (const change of workspaceEdit.documentChanges) { if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { let textDocument = openTextDocuments.get(change.textDocument.uri); if (textDocument && textDocument.version !== change.textDocument.version) { versionMismatch = true; break; } } } } if (versionMismatch) { return Promise.resolve({ applied: false }); } return Is.asPromise(vscode_1.workspace.applyEdit(this._p2c.asWorkspaceEdit(params.edit)).then((value) => { return { applied: value }; })); } logFailedRequest(type, error) { // If we get a request cancel or a content modified don't log anything. if (error instanceof vscode_languageserver_protocol_1.ResponseError && (error.code === vscode_languageserver_protocol_1.ErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.ErrorCodes.ContentModified)) { return; } this.error(`Request ${type.method} failed.`, error); } } exports.BaseLanguageClient = BaseLanguageClient;
Marker = function({ settings, rad }) { const long = settings.longMarker ? 'protractor-extension-marker-long' : ""; this.theta = rad - Math.PI / 2; this.phi = settings.phi; this.settings = settings; this.node = document.createElement('div'); this.node.className = `protractor-extension-marker ${long}`; this.node.style.borderBottom = `20px solid ${settings.markerFill}`; PubSub.subscribe(Channels.MOVE_CONTAINER, this); PubSub.subscribe(Channels.MOVE_HANDLE_ROTATE, this); return this.node; }; Marker.prototype = { onRotate: function(msg) { this.rotation += msg.phi; }, onUpdate: function(chan, msg) { switch(chan) { case Channels.MOVE_CONTAINER: this.onMoveContainer(msg); break; case Channels.MOVE_HANDLE_ROTATE: this.onMoveHandleRotate(msg); break; } }, onMoveContainer: function(msg) { this.node.style.height = `${msg.radius + 10}px`; if (this.settings.longMarker) { const rgba = this.settings.markerFill.replace('1)', '0.4)'); this.node.style.borderTop = `${msg.radius - 10}px solid ${rgba}`; } this.transform(); }, onMoveHandleRotate: function(msg) { this.phi = msg.phi; this.transform(); }, transform: function() { this.node.style.transform = `rotate(${this.theta + this.phi}rad)`; }, setMode: function() { this.node.className = (msg.mode === "lock" ? 'protractor-extension-marker protractor-extension-marker-locked' : 'protractor-extension-marker'); }, };
"use strict"; import React from 'react' import Course from '../partials/Course.js' import Modal from '../partials/Modal.js' import MetricModal from '../partials/MetricModal.js' export default class Courses extends React.Component { constructor(props) { super(props); this.state = { course: props.course, sections: props.course.sections, showModal: false, showMetricModal: false, modalInfo: { modalType: "ADD_QUIZ", title: "Add Quiz" } }; } componentDidMount() { this.getCoursesAndSections(this.state.course.id); } componentWillReceiveProps(newProps) { if(newProps.course != undefined) { this.getCoursesAndSections(newProps.course.id); } } getCoursesAndSections(courseId) { if(courseId == -1) return; var me = this; $.when( $.post("/course/find", {id: courseId}), $.post("/section/find", {course: courseId}) ).then(function(course, sections) { console.log("course", course[0]); console.log("sections", sections[0]); if(course == undefined) return; // if there are no courses, then there are no sections me.setState({ course: course[0], sections: sections[0] }); }); } closeModal() { this.setState({ showModal: false, showMetricModal: false }); } showMetricModal(quiz) { console.log("showMetricModal!", quiz); var modalInfo = this.state.modalInfo; modalInfo.title = quiz.title; this.setState({ showModal: false, showMetricModal: true, modalInfo: modalInfo }); } showCourseModal() { var modalInfo = this.state.modalInfo; modalInfo.modalType = "ADD_COURSE"; modalInfo.title = "Add Course or Section"; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } showQuizModal(quizIndex) { var modalInfo = this.state.modalInfo; modalInfo.title = "Add Quiz"; modalInfo.modalType = "ADD_QUIZ"; modalInfo.quizIndex = quizIndex; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } showQuizInModal(quizIndex) { console.log("showQuizInModal::quizIndex", quizIndex); this.showQuizModal(quizIndex); } showStudentsModal(section) { var modalInfo = this.state.modalInfo; modalInfo.modalType = "ADD_STUDENTS"; modalInfo.title = "Add Students"; modalInfo.section = section; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } addQuizToCourse(quiz, quizIndex) { console.log("Adding quiz '" + quiz.title + "' in course " + this.props.course.title); var me = this; if(quizIndex > -1) { $.post('/quiz/update/' + quiz.id, { title: quiz.title }) .then(function(quiz) { console.log(quiz); var course = me.state.course; course.quizzes[quizIndex] = quiz; me.setState({course: course}); me.closeModal(); }); } else { $.post('/quiz/create/', { title: quiz.title, course: me.props.course.id } ) .then(function(quiz) { console.log(quiz); var course = me.state.course; course.quizzes.push(quiz); me.setState({course: course}); me.closeModal(); }); } } addSectionToCourse(section) { var me = this; if(section.title == '') { return; } $.post('/section/create/', { title: section.title, course: me.state.course.id }) .then(function(section) { console.log("created section", section); var sections = me.state.sections; sections.push(section); me.setState({sections: sections}); me.closeModal(); }); } addCourseToProfessor(course, term) { var me = this; this.props.addCourseToProfessor(course, term) .then(function(newCourse) { me.setState({course: newCourse}); me.closeModal(); }); } addStudentsToSection(sectionId, studentIds) { var me = this; this.props.addStudentsToSection(sectionId, studentIds) .then(function() { me.closeModal(); }); } deleteSectionFromCourse(sectionIndex) { var me = this; var sections = me.state.sections; if(sections[sectionIndex] == undefined) return $.when(null); $.post('/section/destroy/' + sections[sectionIndex].id) .then(function(section) { console.log("section", section); sections.splice(sectionIndex, 1); me.setState({sections: sections}); me.closeModal(); }); } deleteQuizFromCourse(quizIndex) { var me = this; var quizzes = this.state.course.quizzes; $.post('/quiz/find/' + quizzes[quizIndex].id) .then(function(quiz) { return $.post('/quiz/destroy/' + quizzes[quizIndex].id); }) // .then(function(quiz) { // if(quiz.questions.length == 0) return $.when(null); // var questionIds = quiz.questions.map(function(question){return question.id;}); // return $.post('/question/multidestroy', {ids: questionIds}); // }) .then(function() { quizzes.splice(quizIndex, 1); var course = me.state.course; course.quizzes = quizzes; me.setState({course: course}); me.closeModal(); }); } deleteCourseFromProfessor(course) { var me = this; this.props.deleteCourseFromProfessor(course) .then(function() { var course = { id: -1, title: "FAKE 101", quizzes: [], sections: [] }; me.setState({course: course}); }); } render() { return ( <div> <div id="courses" className="quizzlyContent"> {(() => { if(this.state.course.id > -1) { return ( <Course course={this.state.course} isCourse={true} ref={'course'} showQuizModal={this.showQuizModal.bind(this)} showQuizInModal={this.showQuizInModal.bind(this)} showMetricModal={this.showMetricModal.bind(this)} deleteQuizFromCourse={this.deleteQuizFromCourse.bind(this)} sectionIndex={-1} deleteCourseFromProfessor={this.deleteCourseFromProfessor.bind(this)} deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)} /> ); } })()} {this.state.sections.map(function(section, sectionIndex) { // this is section, not course! return ( <Course section={section} sectionIndex={sectionIndex} course={this.state.course} isCourse={false} key={sectionIndex} showQuizInModal={this.showQuizInModal.bind(this)} showMetricModal={this.showMetricModal.bind(this)} showStudentsModal={this.showStudentsModal.bind(this)} deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)} /> ); }, this)} <div className="addEntityButton" onClick={this.showCourseModal.bind(this)}>+</div> </div> {(() => { if(this.state.showModal) return ( <Modal modalInfo={this.state.modalInfo} showModal={this.state.showModal} course={this.state.course} quizzes={this.state.course.quizzes} key={this.state.showModal} closeModal={this.closeModal.bind(this)} addQuizToCourse={this.addQuizToCourse.bind(this)} addCourseToProfessor={this.addCourseToProfessor.bind(this)} addSectionToCourse={this.addSectionToCourse.bind(this)} addStudentsToSection={this.addStudentsToSection.bind(this)} /> ); })()} {(() => { if(this.state.showMetricModal) return ( <MetricModal modalInfo={this.state.modalInfo} showMetricModal={this.state.showMetricModal} key={this.state.showMetricModal} closeModal={this.closeModal.bind(this)} /> ); })()} </div> ); } }
import Vue from 'vue' import Kanban from './components/kanban-app.vue' import store from './store.js' new Vue({ el: '#app', store, render: h => h(Kanban) })
import {observable, runInAction, computed, action, reaction, autorun} from "mobx"; import LynlpApi from "../common/lynlp-api" import _ from "lodash"; class EntityExtractStore { @observable isFetching = false; @observable currentItem = '图形展示'; @observable entity = {}; @action fetchData(content) { this.isFetching = true; LynlpApi.entity(content).then((result)=>{ this.entity = result; this.isFetching = false; }) } } const entityExtractStore = new EntityExtractStore(); export default entityExtractStore
(window.webpackJsonp=window.webpackJsonp||[]).push([[88],{499:function(t,e,s){"use strict";s.r(e);var a=s(0),n=Object(a.a)({},(function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h2",{attrs:{id:"examples"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#examples"}},[t._v("#")]),t._v(" Examples")]),t._v(" "),s("p",[t._v("Spreadsheets: Edit a cell in the sheet")]),t._v(" "),s("h2",{attrs:{id:"solutions"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#solutions"}},[t._v("#")]),t._v(" Solutions")]),t._v(" "),s("p",[s("strong",[t._v("Data Curator")]),s("br"),t._v("\nEdit CSV and XLS files without unintentionally changing the raw data. Also, automatically detects the schema for every file.")]),t._v(" "),s("p",[s("strong",[t._v("Delimiter")]),s("br"),t._v("\nEdit and sync CSV files with GitHub directly in the browser.")])])}),[],!1,null,null,null);e.default=n.exports}}]);
'use strict'; const async = require('async'); const getApp = require('../utils/utils.js').getApp; module.exports = function(Worker) { //Worker.validatesPresenceOf('title'); Worker.upsertItem = (data, cb) => { let res = {}; getApp(Worker) .then((app) => { if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'}); if (!!!data.cargos || data.cargos.length === 0 ) cb({errCode: 'ERR_WORKER_NO_CARGO'}); console.log(data); return (!!!data.person.id ? app.models.person.create(data.person) : Promise.resolve(data.person) ) .then((result) => { res.person = result; return app.models.worker.upsert({ personId: res.person.id }); }) .then(results => { res.worker = results; res.cargoMapping = []; return new Promise((resolve, reject) => async.each(data.cargos, (cargoId, cbInner) => app.models.cargoMapping.create({ cargoId: cargoId, workerId: res.worker.id }) .then(r => cbInner(null, res.cargoMapping.push(r))) .catch(err => async.each(res.cargoMapping, (itemInner, cbInner2) => cbInner2(null, itemInner.destroy()), err => cbInner({ errCode: 'ERR_WORKER_FAIL_CARGOS', message: 'problem to save cargo in worker' }) )), err => !!err ? reject(err) : resolve(res) )); }) .then(res => { cb(null, res); }) .catch(err => { if (!!res.person) res.person.destroy(); if (!!res.worker) res.worker.destroy(); cb({errCode: 'ERR_WORKER_NO_SAVE'}); }); }); }; Worker.remoteMethod('upsertItem', { description: 'upsert client ', http: {verb: 'post'}, accepts: { arg: 'data', type: 'object', description: 'data from form to upsert client', http: {source: 'body'}, required: true }, returns: { arg: 'res', type: 'object', root: true } }); };
import { combineReducers } from 'redux' import auth from './auth' import watt from './watt' import locations from './locations' export default combineReducers({ auth, watt, locations })
'use strict'; require('./components/dropdown'); require('./components/active-link');
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; /* Copyright 2013 jQuery Foundation and other contributors Released under the MIT license. http://jquery.org/license */ define(["ojs/ojcore","jquery","ojdnd","ojs/ojlistview"],function(a,g){a.jb=function(a){this.Ja=a};o_("ListViewDndContext",a.jb,a);a.f.xa(a.jb,a.f,"oj.ListViewDndContext");a.jb.nra=67;a.jb.rT=86;a.jb.tT=88;a.jb.prototype.reset=function(){this.t1();this.un=this.SI=this.XI=this.jR=null};a.jb.prototype.CX=function(a){var b=this.Ja.Jd("dnd");return null!=b&&b[a]?b[a].items:null};a.jb.prototype.WM=function(){return this.CX("drag")};a.jb.prototype.DX=function(){return this.CX("drop")};a.jb.prototype.ps= function(){return"enabled"==this.CX("reorder")};a.jb.prototype.Vg=function(a){return this.Ja.On(a)};a.jb.prototype.sN=function(){var a,b,d,e;a=[];if(this.Ja.Pc())for(b=this.Ja.Jd("selection"),d=0;d<b.length;d++)e=this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||a.push(e);else e=this.dca(),null!=e&&a.push(e);null!=this.kz&&0<this.kz.length&&-1==a.indexOf(this.kz.get(0))&&a.push(this.kz.get(0));return a};a.jb.prototype.dca=function(){return null==this.Ja.V?null:this.Ja.V.elem[0]};a.jb.prototype.hz=function(a){var b; g(a).hasClass(this.Ja.eg())||(a=a.firstElementChild);a=g(a).find(".oj-listview-drag-handle");null!=a&&0<a.length&&(b=a.attr("aria-labelledby"),null==b?a.attr("aria-labelledby",this.Ja.qx("instr")):a.attr("aria-labelledby",b+" "+this.Ja.qx("instr")),this.Ja.Um()&&a.attr("draggable","true"))};a.jb.prototype.t1=function(){this.ooa&&g.each(this.ooa,function(a,b){g(b).removeClass("oj-draggable")})};a.jb.prototype.CTa=function(){var a=[],b,d,e;this.t1();b=this.Ja.Jd("selection");for(d=0;d<b.length;d++)e= this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||(a.push(e),g(e).addClass("oj-draggable"));this.ooa=a};a.jb.prototype.Wia=function(a){var b;b=a.find(".oj-listview-drag-handle");if(null!=b&&0<b.length)return!0;a.addClass("oj-draggable");return!1};a.jb.prototype.WMa=function(a){a.removeClass("oj-draggable")};a.jb.prototype.Sia=function(a){var b,d;if(null!=this.WM()||this.ps()){if(a.hasClass("oj-listview-drag-handle"))b=g(a);else{a=this.Vg(a);if(null!=a&&(d=this.Wia(a)))return;d=this.sN();0<d.length&&(null!= a&&-1<d.indexOf(a[0])?b=a:g(d[0]).removeClass("oj-draggable"))}null!=b&&b.attr("draggable",!0)}};a.jb.prototype.uka=function(a){if(null!=this.WM()||this.ps())a=a.hasClass("oj-listview-drag-handle")?g(a):this.Vg(a),null!=a&&a.removeAttr("draggable")};a.jb.prototype.wo=function(c,b,d,e){var f;if(c="drag"===c?this.WM():this.DX())if((b=c[b])&&"function"==typeof b)try{d.dataTransfer=d.originalEvent.dataTransfer,f=b(d,e)}catch(g){a.F.error("Error: "+g)}else return-1;return f};a.jb.prototype.ZKa=function(a, b,d){var e,f=[],g;for(e=0;e<d.length;e++)(g=this.Ja.tca(d[e]))&&(g.innerHTML&&g.tagName&&"LI"==g.tagName?f.push(g.innerHTML):f.push(g));return 0<f.length?(this.YKa(a.originalEvent,b,f),this.$Ka(a.originalEvent,d),{items:f}):null};a.jb.prototype.YKa=function(a,b,d){var e;a=a.dataTransfer;d=JSON.stringify(d);if("string"==typeof b)a.setData(b,d);else if(b)for(e=0;e<b.length;e++)a.setData(b[e],d);a.setData("text/ojlistview-dragsource-id",this.Ja.element.get(0).id)};a.jb.prototype.$Ka=function(a,b){var d, e,f=Number.MAX_VALUE,h,k,l,m=0,p=0;d=a.target;if(1<b.length){d=g(document.createElement("ul"));d.get(0).className=this.Ja.element.get(0).className;d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:this.Ja.element.css("height")});for(e=0;e<b.length;e++)f=Math.min(f,b[e].offsetTop);for(e=0;e<b.length;e++)h=b[e].offsetTop-f,k=b[e].offsetWidth,l=g(b[e].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").css({position:"absolute",top:h,width:k}),d.append(l)}else g(d).hasClass("oj-listview-drag-handle")&& (h=0,g.contains(b[0],d.offsetParent)&&(h=d.offsetTop),m=Math.max(0,d.offsetLeft-b[0].offsetLeft)+d.offsetWidth/2,p=h+d.offsetHeight/2),l=g(b[0].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").addClass("oj-drag"),d=g(document.createElement("ul")),d.get(0).className=this.Ja.element.get(0).className,d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:2*b[0].offsetHeight}).append(l);g("body").append(d);this.XI=d;a.dataTransfer.setDragImage(d.get(0),m,p)}; a.jb.prototype.OY=function(a){var b,d,e;b=this.WM();if(null!=b||this.ps())if(d=null!=b?b.dataTypes:"text/ojlistview-items-data",g(a.target).hasClass("oj-listview-drag-handle")?(e=[],e.push(this.Vg(a.target)[0])):e=this.sN(),0<e.length){if(null==b&&1<e.length)return!1;this.un=e;this.SI=g(e[0]);if(b=this.ZKa(a,d,e)){if(a=this.wo("drag","dragStart",a,b),-1!==a)return a}else return!1}};a.jb.prototype.EDa=function(a){return this.wo("drag","drag",a)};a.jb.prototype.oM=function(){null!=this.XI&&(this.XI.remove(), this.XI=null)};a.jb.prototype.KY=function(a){var b;if(null!=this.SI&&null!=this.un)for(this.SI.find(".oj-listview-drag-handle").removeAttr("draggable"),this.SI.removeClass("oj-drag oj-draggable").removeAttr("draggable"),b=0;b<this.un.length;b++)g(this.un[b]).removeClass("oj-listview-drag-item");this.lF();this.oM();this.t1();this.wo("drag","dragEnd",a);this.jR=this.un;this.un=this.SI=this.XI=null};a.jb.prototype.WZ=function(a){var b,d;b=this.DX();if(this.ps()&&null==b)return!0;if(b&&b.dataTypes)for(b= b.dataTypes,b="string"==typeof b?[b]:b,a=a.originalEvent.dataTransfer.types,d=0;d<a.length;d++)if(0<=b.indexOf(a[d]))return!0;return!1};a.jb.prototype.xo=function(a,b,d){a=this.wo("drop",a,b,d);(void 0===a||-1===a)&&this.WZ(b)&&b.preventDefault();return a};a.jb.prototype.vaa=function(a){var b;null==this.Sj&&(b=g(a.get(0).cloneNode(!1)),b.addClass("oj-drop").removeClass("oj-drag oj-draggable oj-hover oj-focus oj-selected").css({display:"block",height:a.outerHeight()}),this.Sj=b);return this.Sj};a.jb.prototype.R$= function(){null!=this.cj&&-1===this.pD&&this.cj.children("."+this.Ja.dg()).removeClass("oj-drop")};a.jb.prototype.Q$=function(){null!=this.cj&&this.cj.hasClass("oj-listview-no-data-message")&&(this.cj.removeClass("oj-drop"),this.cj.get(0).textContent=this.Ja.zca())};a.jb.prototype.lF=function(){null!=this.Sj&&(this.Sj.css("height","0"),this.Sj.remove(),this.Sj=null);this.Q$();this.R$()};a.jb.prototype.LY=function(a){var b;b=this.Vg(a.target);a=this.xo("dragEnter",a,{item:b.get(0)});if(-1!=a)return a}; a.jb.prototype.l0=function(a){null!=this.cj&&this.cj.removeClass("oj-valid-drop oj-invalid-drop");this.cj=a;this.cj.addClass("oj-valid-drop")};a.jb.prototype.Iia=function(a,b){var d;d=a.attr("aria-label");null==d&&(d=a.text());d=this.Ja.ea.R("accessibleReorder"+b.charAt(0).toUpperCase()+b.substr(1)+"Item",{item:d});this.Ja.Ch(d)};a.jb.prototype.owa=function(){null==this.Koa&&this.Ja.Um()&&(this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).attr("oldMaxHeight",g(this).css("maxHeight").toString()); g(this).css("maxHeight",1E4)}),this.Koa="adjusted")};a.jb.prototype.uia=function(){this.Ja.Um()&&this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).css("maxHeight",parseInt(g(this).attr("oldMaxHeight"),10));g(this).removeAttr("oldMaxHeight")});this.Koa=null};a.jb.prototype.NY=function(a){var b,d,e,f;if(null!=this.DX()||this.ps()){this.owa();if(null!=this.un&&"none"!=g(this.un[0]).css("display")){b=g(this.un[0]);d=this.vaa(b);for(a=0;a<this.un.length;a++)g(this.un[a]).addClass("oj-listview-drag-item"); d.insertBefore(b);this.pD=d.index()}else b=this.Vg(a.target),null!=b&&0<b.length?(e=this.xo("dragOver",a,{item:b.get(0)}),-1===e&&this.ps()||!1===e||a.isDefaultPrevented()?(b.hasClass(this.Ja.eg())?(this.R$(),b.hasClass("oj-drop")||(d=this.vaa(b),f=b.index(),null==this.pD||this.pD<f?(d.insertAfter(b),this.oD="after"):(d.insertBefore(b),this.oD="before"),this.Iia(b,this.oD),this.l0(b),this.pD=d.index())):(this.lF(),b.children("."+this.Ja.dg()).addClass("oj-drop"),this.l0(b),this.pD=-1,this.oD="inside", this.Iia(b,this.oD)),a.preventDefault()):g(a.target).hasClass(this.Ja.fh())||(b.addClass("oj-invalid-drop"),this.lF())):(b=this.Ja.element.children(".oj-listview-no-data-message"),null!=b&&0<b.length&&(b.addClass("oj-drop"),b.get(0).textContent="",this.l0(b),a.preventDefault()));return e}};a.jb.prototype.ZN=function(a,b){var d,e;d=b.getBoundingClientRect();e=a.originalEvent;return e.clientX>=d.left&&e.clientX<d.right&&e.clientY>=d.top&&e.clientY<d.bottom};a.jb.prototype.MY=function(a){var b,d;if(null!= this.cj&&(b=this.Vg(a.target),null!=b&&0<b.length?(b.removeClass("oj-valid-drop oj-invalid-drop"),d=this.xo("dragLeave",a,{item:b.get(0)}),this.ZN(a,a.currentTarget)||(this.lF(),this.uia())):this.ZN(a,a.currentTarget)||this.Q$(),-1!=d))return d};a.jb.prototype.PY=function(a){var b,d;if(null!=this.cj&&(b=a.originalEvent.dataTransfer.getData("text/ojlistview-dragsource-id"),d=this.cj.hasClass("oj-listview-no-data-message")?{}:{item:this.cj.get(0),position:this.oD},this.ps()&&b===this.Ja.element.get(0).id? d.reorder=!0:d.reorder=!1,b=this.xo("drop",a,d),d.reorder&&(d.items=null==this.jR?this.un:this.jR,d.reference=d.item,this.Ja.Bl("reorder",a,d),a.preventDefault()),null!=this.cj&&this.cj.removeClass("oj-valid-drop"),this.lF(),this.uia(),this.oM(),this.cj=null,this.pD=-1,this.jR=this.oD=null,-1!==b))return b};a.jb.prototype.ANa=function(a){var b=this,d,e;this.ps()&&(void 0==a&&(a=this.Ja.Jd("contextMenu")),null!=a&&(null==this.xn&&(this.xn=[]),a=g(a),d=a.find("[data-oj-command]"),e=[],d.each(function(){var a, c;0===g(this).children("a").length?0==g(this).attr("data-oj-command").indexOf("oj-listview-")&&(a=g(this).attr("data-oj-command").substring(12),c=b.tk(a),c.get(0).className=g(this).get(0).className,g(this).replaceWith(c)):(a=g(this).attr("data-oj-command"),"pasteBefore"==a?a="paste-before":"pasteAfter"==a&&(a="paste-after"));null!=a&&e.push(a)}),this.xn=e,0<e.length&&(a.data("oj-ojMenu")&&a.ojMenu("refresh"),a.on("ojbeforeopen",this.vDa.bind(this)),a.on("ojselect",this.Vl.bind(this)))))};a.jb.prototype.tk= function(a){return"paste-before"===a?this.Sg("pasteBefore"):"paste-after"===a?this.Sg("pasteAfter"):this.Sg(a)};a.jb.prototype.Sg=function(a){var b=g("\x3cli\x3e\x3c/li\x3e");b.attr("data-oj-command",a);b.append(this.fF(a));return b};a.jb.prototype.fF=function(a){a="label"+a.charAt(0).toUpperCase()+a.slice(1);return g('\x3ca href\x3d"#"\x3e\x3c/a\x3e').text(this.Ja.ea.R(a))};a.jb.prototype.iG=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");b=this.sN();g(b).addClass("oj-listview-cut"); this.Yo=b;this.Ja.Bl("cut",a,{items:b})};a.jb.prototype.dea=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");this.Yo=b=this.sN();this.Ja.Bl("copy",a,{items:b})};a.jb.prototype.kG=function(a,b,d){this.Ja.Bl("paste",a,{item:b.get(0)});g(this.Yo).removeClass("oj-listview-cut");this.Ja.Bl("reorder",a,{items:this.Yo,position:d,reference:b.get(0)});this.Yo=null};a.jb.prototype.Vl=function(a,b){if(null!=this.kz)switch(b.item.attr("data-oj-command")){case "cut":this.iG(a);break; case "copy":this.dea(a);break;case "paste":var d=!0;case "pasteBefore":var e=!0;case "pasteAfter":var f="after";d?f="inside":e&&(f="before");this.kG(a,this.kz,f);this.kz=null}};a.jb.prototype.XE=function(a,b){null!=this.xn&&("paste-before"==b?b="pasteBefore":"paste-after"==b&&(b="pasteAfter"),a.find("[data-oj-command\x3d'"+b+"']").removeClass("oj-disabled"))};a.jb.prototype.vDa=function(a,b){var d,e;d=g(a.target);d.find("[data-oj-command]").addClass("oj-disabled");e=b.openOptions.launcher;null==e|| null==this.xn||0==this.xn.length?d.ojMenu("refresh"):(e.children().first().hasClass(this.Ja.dg())?null!=this.Yo&&this.XE(d,"paste"):(this.XE(d,"cut"),this.XE(d,"copy"),null!=this.Yo&&(this.XE(d,"paste-before"),this.XE(d,"paste-after"))),d.ojMenu("refresh"),this.kz=e)};a.jb.prototype.SJ=function(c){var b,d;if(!this.ps()||null==this.xn||0==this.xn.length)return!1;if(c.ctrlKey||c.metaKey){b=c.keyCode;if(b===a.jb.tT&&-1<this.xn.indexOf("cut"))return this.iG(c),!0;if(b===a.jb.nra&&-1<this.xn.indexOf("copy"))return this.dea(c), !0;if(b===a.jb.rT&&null!=this.Yo&&(b=g(this.dca()),b.children().first().hasClass(this.Ja.dg())?-1<this.xn.indexOf("paste")&&(d="inside"):-1<this.xn.indexOf("paste-before")?d="before":-1<this.xn.indexOf("paste-after")&&(d="after"),null!=d))return this.kG(c,b,d),!0}return!1}});
/* eslint-env mocha */ 'use strict' const chai = require('chai') chai.use(require('dirty-chai')) const expect = chai.expect const parallel = require('async/parallel') const createNode = require('./utils/create-node.js') const echo = require('./utils/echo') describe('ping', () => { let nodeA let nodeB before((done) => { parallel([ (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeA = node node.handle('/echo/1.0.0', echo) node.start(cb) }), (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeB = node node.handle('/echo/1.0.0', echo) node.start(cb) }) ], done) }) after((done) => { parallel([ (cb) => nodeA.stop(cb), (cb) => nodeB.stop(cb) ], done) }) it('should be able to ping another node', (done) => { nodeA.ping(nodeB.peerInfo, (err, ping) => { expect(err).to.not.exist() ping.once('ping', (time) => { expect(time).to.exist() ping.stop() done() }) ping.start() }) }) it('should be not be able to ping when stopped', (done) => { nodeA.stop(() => { nodeA.ping(nodeB.peerInfo, (err) => { expect(err).to.exist() done() }) }) }) })
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); this.title = ''; this.content = ''; }; $scope.remove = function(article) { if (article) { article.$remove(); for (var i in $scope.articles) { if ($scope.articles[i] === article) { $scope.articles.splice(i, 1); } } } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $scope.findOne = function () { $scope.article = Articles.get({ articleId: $stateParams.articleId }); }; } ]);
require('..').config({namespace:'NVM'}) .read({}) .on('read', function(ENV){ console.log(JSON.stringify(ENV, null, 4)); });
const express = require("express"); const app = express(); app.set('port', (process.env.PORT || 3000)); const getData = require('./src/server/api/getData'); const setup = require('./src/server/api/setupApi'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use('/assets', express.static('build')); app.use('/', require('./src/server/routers/index')); app.get('/api/:chrom', getData); const server = app.listen(app.get('port')); setup(server);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Category Schema */ var CategorySchema = new Schema({ name: { type: String, default: '', required: 'Please fill Category name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Category', CategorySchema);
var searchData= [ ['index',['index',['../d8/d33/structsvm__sample.html#a008f6b24c7c76af103e84245fb271506',1,'svm_sample']]], ['initlibirwls',['initLIBIRWLS',['../d4/d54/pythonmodule_8c.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c'],['../d0/da7/pythonmodule_8h.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c']]], ['initmemory',['initMemory',['../d0/d98/ParallelAlgorithms_8h.html#aa6df8c3f4f455d5692b3cb220fc205c7',1,'ParallelAlgorithms.h']]], ['iostructures_2ec',['IOStructures.c',['../dc/dfc/IOStructures_8c.html',1,'']]], ['iostructures_2eh',['IOStructures.h',['../de/d79/IOStructures_8h.html',1,'']]], ['irwlspar',['IRWLSpar',['../d4/d49/budgeted-train_8h.html#ad51d9a46645ad0b0bedb1113a3807d24',1,'budgeted-train.h']]] ];
module.exports = { options: { templateCompilerPath: 'bower_components/ember/ember-template-compiler.js', handlebarsPath: 'bower_components/handlebars/handlebars.js', preprocess: function (source) { return source.replace(/\s+/g, ' '); }, templateName: function (sourceFile) { /* These are how templates will be named based on their folder structure. components/[name].hbs ==> components/[name] partials/[name].hbs ==> _[name] modules/application/templates/[name].hbs ==> [name] modules/application/partials/[name].hbs ==> _[name] modules/[moduleName]/templates/[moduleName].hbs ==> [moduleName] modules/[moduleName]/templates/[name].hbs ==> [moduleName]/[name] modules/[moduleName]/partials/[name].hbs ==> [moduleName]/_[name] Additionally any template that is nested deeper will have that structure added as well. modules/[moduleName]/templates/[folder1]/[folder2]/[name] ==> [moduleName]/[folder1]/[folder2]/[name] */ var matches = sourceFile.match(new RegExp('(?:app/modules/(.*?)/|app/)(templates|partials)?/?(.*)')), moduleName = matches[1], isAppModule = (moduleName === 'application'), isPartial = (matches[2] === 'partials'), fileName = matches[3], prefix = (isPartial ? '_' : ''), templateName = ''; if (moduleName && !isAppModule) { if (fileName === moduleName) { templateName = moduleName; } else { templateName = moduleName + '/' + prefix + fileName; } } else { templateName = prefix + fileName; } console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green); return templateName; } }, compile: { files: { 'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}'] } } };
module.exports = api => { api.cache(true); return { presets: [ [ '@babel/preset-env', { targets: { node: '12' } } ] ] }; };
'use strict'; function UserListController(userList) { var vm = this; console.log('UserListController'); vm.userList = userList; } module.exports = UserListController;
import log from 'log'; import Ember from 'ember'; import {registerComponent} from 'ember-utils'; import layout from './confirm-toolbar.hbs!'; export var RheaConfirmToolbar = Ember.Component.extend({ layout, tagName: '', actions: { confirm: function(opID) { this.sendAction('confirm'); }, cancel: function(opID) { this.sendAction('cancel'); } } }); registerComponent('rhea-confirm-toolbar', RheaConfirmToolbar);
/** * 乘法操作符 */ define( function ( require, exports, modules ) { var kity = require( "kity" ); return kity.createClass( 'MultiplicationOperator', { base: require( "operator/binary-opr/left-right" ), constructor: function () { var ltr = new kity.Rect( 0, 20, 43, 3, 3 ).fill( "black"), rtl = new kity.Rect( 20, 0, 3, 43, 3 ).fill( "black" ); this.callBase( "Multiplication" ); this.addOperatorShape( ltr.setAnchor( 22, 22 ).rotate( 45 ) ); this.addOperatorShape( rtl.setAnchor( 22, 22 ).rotate( 45 ) ); } } ); } );