<commit_before>(function($window, L) {

    "use strict";

    /**
     * @module FreeDraw
     * @submodule Options
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/Leaflet.FreeDraw
     * @constructor
     */
    L.FreeDraw.Options = function FreeDrawOptions() {};

    /**
     * @property prototype
     * @type {Object}
     */
    L.FreeDraw.Options.prototype = {

        /**
         * @property multiplePolygons
         * @type {Boolean}
         */
        multiplePolygons: true,

        /**
         * @property simplifyPolygon
         * @type {Boolean}
         */
        simplifyPolygon: true,

        /**
         * @property hullAlgorithm
         * @type {String|Boolean}
         */
        hullAlgorithm: 'wildhoneyConcaveHull',

        /**
         * @property boundariesAfterEdit
         * @type {Boolean}
         */
        boundariesAfterEdit: false,

        /**
         * @property createExitMode
         * @type {Boolean}
         */
        createExitMode: true,

        /**
         * @property attemptMerge
         * @type {Boolean}
         */
        attemptMerge: true,

        /**
         * @property svgClassName
         * @type {String}
         */
        svgClassName: 'tracer',

        /**
         * @property smoothFactor
         * @type {Number}
         */
        smoothFactor: 5,

        /**
         * @property iconClassName
         * @type {String}
         */
        iconClassName: 'polygon-elbow',

        /**
         * @property deleteExitMode
         * @type {Boolean}
         */
        deleteExitMode: false,

        /**
         * @property memoriseEachEdge
         * @type {Boolean}
         */
        memoriseEachEdge: true,

        /**
         * @property destroyPrevious
         * @type {Boolean}
         */
        destroyPrevious: false,

        /**
         * @property disablePropagation
         * @type {Boolean}
         */
        disablePropagation: false,

        /**
         * @property elbowDistance
         * @type {Number}
         */
        elbowDistance: 10,

        /**
         * @property onlyInDistance
         * @type {Boolean}
         */
        onlyInDistance: false,

        /**
         * @property hullAlgorithms
         * @type {Object}
         */
        hullAlgorithms: {

            /**
             * @property brian3kb/graham_scan_js
             * @type {Object}
             */
            'brian3kb/graham_scan_js': {
                method: 'brian3kbGrahamScan',
                name: 'Graham Scan JS',
                global: 'ConvexHullGrahamScan',
                link: 'https://github.com/brian3kb/graham_scan_js'
            },

            /**
             * @property Wildhoney/ConcaveHull
             * @type {Object}
             */
            'Wildhoney/ConcaveHull': {
                method: 'wildhoneyConcaveHull',
                name: 'Concave Hull',
                global: 'ConcaveHull',
                link: 'https://github.com/Wildhoney/ConcaveHull'
            }

        },

        /**
         * @method setMemoriseEachEdge
         * @param value {Boolean}
         * @return {void}
         */
        setMemoriseEachEdge: function setMemoriseEachEdge(value) {
            this.memoriseEachEdge = !!value;
        },

        /**
         * @method addElbowOnlyWithinDistance
         * @param value {Boolean}
         */
        addElbowOnlyWithinDistance: function addElbowOnlyWithinDistance(value) {
            this.onlyInDistance = !!value;
        },

        /**
         * @method setPathClipperPadding
         * @param value {Number}
         * @return {void}
         */
        setPathClipperPadding: function setPathClipperPadding(value) {

            // Prevent polygons outside of the viewport from being clipped.
            L.Path.CLIP_PADDING = value;

        },

        /**
         * @method disableStopPropagation
         * @return {void}
         */
        disableStopPropagation: function disableStopPropagation() {
            this.disablePropagation = true;
        },

        /**
         * @method setMaximumDistanceForElbow
         * @param maxDistance {Number}
         * @return {void}
         */
        setMaximumDistanceForElbow: function setMaximumDistanceForElbow(maxDistance) {
            this.elbowDistance = +maxDistance;
        },

        /**
         * @method exitModeAfterCreate
         * @param value {Boolean}
         * @return {void}
         */
        exitModeAfterCreate: function exitModeAfterCreate(value) {
            this.createExitMode = !!value;
        },

        /**
         * @method exitModeAfterDelete
         * @param value {Boolean}
         * @return {void}
         */
        exitModeAfterDelete: function exitModeAfterDelete(value) {
            this.deleteExitMode = !!value;
        },

        /**
         * @method destroyPreviousPolygon
         * @param value {Boolean}
         * @return {void}
         */
        destroyPreviousPolygon: function destroyPreviousPolygon(value) {
            this.destroyPrevious = !!value;
        },

        /**
         * @method allowMultiplePolygons
         * @param allow {Boolean}
         * @return {void}
         */
        allowMultiplePolygons: function allowMultiplePolygons(allow) {
            this.multiplePolygons = !!allow;
        },

        /**
         * @method setSVGClassName
         * @param className {String}
         * @return {void}
         */
        setSVGClassName: function setSVGClassName(className) {
            this.svgClassName = className;
        },

        /**
         * @method setBoundariesAfterEdit
         * @param value {Boolean}
         * @return {void}
         */
        setBoundariesAfterEdit: function setBoundariesAfterEdit(value) {
            this.boundariesAfterEdit = !!value;
        },

        /**
         * @method smoothFactor
         * @param factor {Number}
         * @return {void}
         */
        setSmoothFactor: function setSmoothFactor(factor) {
            this.smoothFactor = +factor;
        },

        /**
         * @method setIconClassName
         * @param className {String}
         * @return {void}
         */
        setIconClassName: function setIconClassName(className) {
            this.iconClassName = className;
        },

        /**
         * @method setHullAlgorithm
         * @param algorithm {String|Boolean}
         * @return {void}
         */
        setHullAlgorithm: function setHullAlgorithm(algorithm) {

            if (algorithm && !this.hullAlgorithms.hasOwnProperty(algorithm)) {

                // Ensure the passed algorithm is valid.
                return;

            }

            if (!algorithm) {
                return;
            }

            // Resolve the hull algorithm.
            algorithm = this.hullAlgorithms[algorithm];

            if (typeof $window[algorithm.global] === 'undefined') {

                // Ensure hull algorithm module has been included.
                L.FreeDraw.Throw(algorithm.name + ' is a required library for concave/convex hulls', algorithm.link);

            }

            this.hullAlgorithm = algorithm.method;

        }

    };

})(window, window.L);<commit_msg>Allow setHullAlgorithm to be given a falsy value. Fixes #48<commit_after>(function($window, L) {

    "use strict";

    /**
     * @module FreeDraw
     * @submodule Options
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/Leaflet.FreeDraw
     * @constructor
     */
    L.FreeDraw.Options = function FreeDrawOptions() {};

    /**
     * @property prototype
     * @type {Object}
     */
    L.FreeDraw.Options.prototype = {

        /**
         * @property multiplePolygons
         * @type {Boolean}
         */
        multiplePolygons: true,

        /**
         * @property simplifyPolygon
         * @type {Boolean}
         */
        simplifyPolygon: true,

        /**
         * @property hullAlgorithm
         * @type {String|Boolean}
         */
        hullAlgorithm: 'wildhoneyConcaveHull',

        /**
         * @property boundariesAfterEdit
         * @type {Boolean}
         */
        boundariesAfterEdit: false,

        /**
         * @property createExitMode
         * @type {Boolean}
         */
        createExitMode: true,

        /**
         * @property attemptMerge
         * @type {Boolean}
         */
        attemptMerge: true,

        /**
         * @property svgClassName
         * @type {String}
         */
        svgClassName: 'tracer',

        /**
         * @property smoothFactor
         * @type {Number}
         */
        smoothFactor: 5,

        /**
         * @property iconClassName
         * @type {String}
         */
        iconClassName: 'polygon-elbow',

        /**
         * @property deleteExitMode
         * @type {Boolean}
         */
        deleteExitMode: false,

        /**
         * @property memoriseEachEdge
         * @type {Boolean}
         */
        memoriseEachEdge: true,

        /**
         * @property destroyPrevious
         * @type {Boolean}
         */
        destroyPrevious: false,

        /**
         * @property disablePropagation
         * @type {Boolean}
         */
        disablePropagation: false,

        /**
         * @property elbowDistance
         * @type {Number}
         */
        elbowDistance: 10,

        /**
         * @property onlyInDistance
         * @type {Boolean}
         */
        onlyInDistance: false,

        /**
         * @property hullAlgorithms
         * @type {Object}
         */
        hullAlgorithms: {

            /**
             * @property brian3kb/graham_scan_js
             * @type {Object}
             */
            'brian3kb/graham_scan_js': {
                method: 'brian3kbGrahamScan',
                name: 'Graham Scan JS',
                global: 'ConvexHullGrahamScan',
                link: 'https://github.com/brian3kb/graham_scan_js'
            },

            /**
             * @property Wildhoney/ConcaveHull
             * @type {Object}
             */
            'Wildhoney/ConcaveHull': {
                method: 'wildhoneyConcaveHull',
                name: 'Concave Hull',
                global: 'ConcaveHull',
                link: 'https://github.com/Wildhoney/ConcaveHull'
            }

        },

        /**
         * @method setMemoriseEachEdge
         * @param value {Boolean}
         * @return {void}
         */
        setMemoriseEachEdge: function setMemoriseEachEdge(value) {
            this.memoriseEachEdge = !!value;
        },

        /**
         * @method addElbowOnlyWithinDistance
         * @param value {Boolean}
         */
        addElbowOnlyWithinDistance: function addElbowOnlyWithinDistance(value) {
            this.onlyInDistance = !!value;
        },

        /**
         * @method setPathClipperPadding
         * @param value {Number}
         * @return {void}
         */
        setPathClipperPadding: function setPathClipperPadding(value) {

            // Prevent polygons outside of the viewport from being clipped.
            L.Path.CLIP_PADDING = value;

        },

        /**
         * @method disableStopPropagation
         * @return {void}
         */
        disableStopPropagation: function disableStopPropagation() {
            this.disablePropagation = true;
        },

        /**
         * @method setMaximumDistanceForElbow
         * @param maxDistance {Number}
         * @return {void}
         */
        setMaximumDistanceForElbow: function setMaximumDistanceForElbow(maxDistance) {
            this.elbowDistance = +maxDistance;
        },

        /**
         * @method exitModeAfterCreate
         * @param value {Boolean}
         * @return {void}
         */
        exitModeAfterCreate: function exitModeAfterCreate(value) {
            this.createExitMode = !!value;
        },

        /**
         * @method exitModeAfterDelete
         * @param value {Boolean}
         * @return {void}
         */
        exitModeAfterDelete: function exitModeAfterDelete(value) {
            this.deleteExitMode = !!value;
        },

        /**
         * @method destroyPreviousPolygon
         * @param value {Boolean}
         * @return {void}
         */
        destroyPreviousPolygon: function destroyPreviousPolygon(value) {
            this.destroyPrevious = !!value;
        },

        /**
         * @method allowMultiplePolygons
         * @param allow {Boolean}
         * @return {void}
         */
        allowMultiplePolygons: function allowMultiplePolygons(allow) {
            this.multiplePolygons = !!allow;
        },

        /**
         * @method setSVGClassName
         * @param className {String}
         * @return {void}
         */
        setSVGClassName: function setSVGClassName(className) {
            this.svgClassName = className;
        },

        /**
         * @method setBoundariesAfterEdit
         * @param value {Boolean}
         * @return {void}
         */
        setBoundariesAfterEdit: function setBoundariesAfterEdit(value) {
            this.boundariesAfterEdit = !!value;
        },

        /**
         * @method smoothFactor
         * @param factor {Number}
         * @return {void}
         */
        setSmoothFactor: function setSmoothFactor(factor) {
            this.smoothFactor = +factor;
        },

        /**
         * @method setIconClassName
         * @param className {String}
         * @return {void}
         */
        setIconClassName: function setIconClassName(className) {
            this.iconClassName = className;
        },

        /**
         * @method setHullAlgorithm
         * @param algorithm {String|Boolean}
         * @return {void}
         */
        setHullAlgorithm: function setHullAlgorithm(algorithm) {

            if (algorithm && !this.hullAlgorithms.hasOwnProperty(algorithm)) {

                // Ensure the passed algorithm is valid.
                return;

            }

            if (!algorithm) {
                this.hullAlgorithm = false;
                return;
            }

            // Resolve the hull algorithm.
            algorithm = this.hullAlgorithms[algorithm];

            if (typeof $window[algorithm.global] === 'undefined') {

                // Ensure hull algorithm module has been included.
                L.FreeDraw.Throw(algorithm.name + ' is a required library for concave/convex hulls', algorithm.link);

            }

            this.hullAlgorithm = algorithm.method;

        }

    };

})(window, window.L);<|endoftext|>


<commit_before>/**
 *
Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.

 *
 * Documentation for the subprocess bin file in jsdoc format
 * @author Bryan Hughes <bhughes@appcelerator.com>
 */

/**
Command usage:
Usage: subprocess run <config file>
       subprocess queryPlugins [<search path> [<search path> [...]]]
       subprocess queryOptions

Commands:
   run       Runs the Titanium Code Processor using the supplied config file in interactive mode
   plugins   Queries the plugins in the default search path and the listed search paths
   options   Queries the options

Note: this interface is only intended for applications that subprocess the Titanium Code Processor

 * @module CommandUsage
 */

// *******************************
// *        Generic types        *
// *******************************

/**
 * @name type
 * @property {String} type One of 'null', 'boolean', 'number', 'string', 'object', or 'array'
 * @property {type} subType Only for type of 'array', this is the type of the array elements
 * @property {Object} properties Only for type of 'object', the properties of the object
 * @property {option} properties.property A property, with the key being the name of the proprety
 * @property {Array[Primitive]} [allowedValues] Only for primitive types, a list of allowed values
 * @property {String} [description] A description of this type
 * @example
 * {
 *	"type": "array",
 *	"subType": {
 *		"type": "object",
 *		"properties": {
 *			"name": {
 *				"types": [{
 *					"type": "string",
 *				}],
 *				"description": "The name of the module"
 *			},
 *			"path": {
 *				"types": [{
 *					"type": "string",
 *				}],
 *				"description": "The path to the module"
 *			},
 *			"type": {
 *				"types": [{
 *					"type": "string",
 *					"allowedValues": [
 *						"commonjs",
 *						"iphone",
 *						"android",
 *						"mobileweb"
 *					]
 *				}],
 *				"description": "The type of the module"
 *			}
 *		}
 * }
 */

/**
 * @name option
 * @type Object
 * @property {Array[{@link type}]} types The list of possible types allowed by the option
 * @property {String} [description] A description of the option
 * @property {Boolean} required Whether or not this option is required
 * @property {Any} [defaultValue] The devault value
 * @example
 * {
 *		"types": [{
 *			"type": "string"
 *		}],
 *		"required": false,
 *		"description": "I am an option",
 *		"defaultValue": "hi"
 * }
 */

// *******************************
// *       Options Command       *
// *******************************

/**
 * Queries the code processor options
 *
 * @module OptionsSubcommand
 */
/**
 * @name module:OptionsSubcommand.output
 * @property {option} optionName The options for the plugin. The key is the name of the option
 */

// *******************************
// *       Plugins Command       *
// *******************************

/**
 * Searches for plugins in the default path and the (optional) supplied search paths and queries them
 *
 * @module PluginsSubcommand
 */
/**
 * @name module:PluginsSubcommand.output
 * @property {Object} pluginName A plugin entry. The actual key is the name of the plugin
 * @property {String} pluginName.path The path to the plugin
 * @property {Array[String]} pluginName.dependencies The plugin dependencies, with each entry being the plugin name
 * @property {Object} pluginName.options The options for the plugin
 * @property {option} pluginName.options.optionName The options for the plugin. The key is the name of the option
 */

// *******************************
// *         Run Command         *
// *******************************

/**
 * The run command runs the code processor using the supplied configuration file
 *
 * @module RunSubcommand
 */

// ******** Config File ********

/**
 * The spec for the config file supplied to the run command
 *
 * @name module:RunSubcommand.ConfigFileFormat
 * @property {String} entryPoint The path to the entry point file (a.k.a. app.js)
 * @property {Object} [log] Logging information. The information logged is the same information output to stdout when
 *		using the normal CLI interface, minus results
 * @property {String} log.path The path to the log file. The file does not need to exist, but the directory does
 * @property {String} log.level The log level. One of "trace", "debug", "info", "notice", "warn", or "error"
 * @property {Object} options The core code processor options (run 'subprocess options' to see the list of options)
 * @property {Any} options.optionName An option value. The object key is the name of the option
 * @property {Object} plugins The plugins to load and their options
 * @property {Object} plugins.pluginName A plugin value. The object key is the name of the plugin
 * @property {String} plugins.pluginName.path The path to the plugin
 * @property {Object} plugins.pluginName.options The options for the plugin
 * @property {Any} plugins.pluginName.options.optionName An option value. The object key is the name of the option
 */

// ******** Inbound Messages ********

/**
 * Tells the app to exit
 *

 * Initiated by: External Process
 *

 * Message name: "exit"
 *

 * @event
 * @name module:RunSubcommand.exitMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */

// ******** Outbound Messages ********

/**
 * Indicates that a file was just entered
 *

 * Initiated by: Code Processor
 *

 * Message name: 'enteredFile'
 *

 * @event
 * @name module:RunSubcommand.enteredFileMessage
 * @param {String} request The absolute path to the file that was just entered
 * @param {Undefined} response There is no response data
 */

/**
 * Indicates that the current run of the project is about to be processed, and all pre-processing steps have been completed successfully
 *

 * Initiated by: Code Processor
 *

 * Message name: 'projectProcessingBegin'
 *

 * @event
 * @name module:RunSubcommand.projectProcessingBeginMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */

/**
 * Indicates that the current run of the project has finished being processed
 *

 * Initiated by: Code Processor
 *

 * Message name: 'projectProcessingEnd'
 *

 * @event
 * @name module:RunSubcommand.projectProcessingEndMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */<commit_msg>[TIMOB-12259] Added error and warning message documentation<commit_after>/**
 *
Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.

 *
 * Documentation for the subprocess bin file in jsdoc format
 * @author Bryan Hughes <bhughes@appcelerator.com>
 */

/**
Command usage:
Usage: subprocess run <config file>
       subprocess queryPlugins [<search path> [<search path> [...]]]
       subprocess queryOptions

Commands:
   run       Runs the Titanium Code Processor using the supplied config file in interactive mode
   plugins   Queries the plugins in the default search path and the listed search paths
   options   Queries the options

Note: this interface is only intended for applications that subprocess the Titanium Code Processor

 * @module CommandUsage
 */

// *******************************
// *        Generic types        *
// *******************************

/**
 * @name type
 * @property {String} type One of 'null', 'boolean', 'number', 'string', 'object', or 'array'
 * @property {type} subType Only for type of 'array', this is the type of the array elements
 * @property {Object} properties Only for type of 'object', the properties of the object
 * @property {option} properties.property A property, with the key being the name of the proprety
 * @property {Array[Primitive]} [allowedValues] Only for primitive types, a list of allowed values
 * @property {String} [description] A description of this type
 * @example
 * {
 *	"type": "array",
 *	"subType": {
 *		"type": "object",
 *		"properties": {
 *			"name": {
 *				"types": [{
 *					"type": "string",
 *				}],
 *				"description": "The name of the module"
 *			},
 *			"path": {
 *				"types": [{
 *					"type": "string",
 *				}],
 *				"description": "The path to the module"
 *			},
 *			"type": {
 *				"types": [{
 *					"type": "string",
 *					"allowedValues": [
 *						"commonjs",
 *						"iphone",
 *						"android",
 *						"mobileweb"
 *					]
 *				}],
 *				"description": "The type of the module"
 *			}
 *		}
 * }
 */

/**
 * @name option
 * @type Object
 * @property {Array[{@link type}]} types The list of possible types allowed by the option
 * @property {String} [description] A description of the option
 * @property {Boolean} required Whether or not this option is required
 * @property {Any} [defaultValue] The devault value
 * @example
 * {
 *		"types": [{
 *			"type": "string"
 *		}],
 *		"required": false,
 *		"description": "I am an option",
 *		"defaultValue": "hi"
 * }
 */

// *******************************
// *       Options Command       *
// *******************************

/**
 * Queries the code processor options
 *
 * @module OptionsSubcommand
 */
/**
 * @name module:OptionsSubcommand.output
 * @property {option} optionName The options for the plugin. The key is the name of the option
 */

// *******************************
// *       Plugins Command       *
// *******************************

/**
 * Searches for plugins in the default path and the (optional) supplied search paths and queries them
 *
 * @module PluginsSubcommand
 */
/**
 * @name module:PluginsSubcommand.output
 * @property {Object} pluginName A plugin entry. The actual key is the name of the plugin
 * @property {String} pluginName.path The path to the plugin
 * @property {Array[String]} pluginName.dependencies The plugin dependencies, with each entry being the plugin name
 * @property {Object} pluginName.options The options for the plugin
 * @property {option} pluginName.options.optionName The options for the plugin. The key is the name of the option
 */

// *******************************
// *         Run Command         *
// *******************************

/**
 * The run command runs the code processor using the supplied configuration file
 *
 * @module RunSubcommand
 */

// ******** Config File ********

/**
 * The spec for the config file supplied to the run command
 *
 * @name module:RunSubcommand.ConfigFileFormat
 * @property {String} entryPoint The path to the entry point file (a.k.a. app.js)
 * @property {Object} [log] Logging information. The information logged is the same information output to stdout when
 *		using the normal CLI interface, minus results
 * @property {String} log.path The path to the log file. The file does not need to exist, but the directory does
 * @property {String} log.level The log level. One of "trace", "debug", "info", "notice", "warn", or "error"
 * @property {Object} options The core code processor options (run 'subprocess options' to see the list of options)
 * @property {Any} options.optionName An option value. The object key is the name of the option
 * @property {Object} plugins The plugins to load and their options
 * @property {Object} plugins.pluginName A plugin value. The object key is the name of the plugin
 * @property {String} plugins.pluginName.path The path to the plugin
 * @property {Object} plugins.pluginName.options The options for the plugin
 * @property {Any} plugins.pluginName.options.optionName An option value. The object key is the name of the option
 */

// ******** Inbound Messages ********

/**
 * Tells the app to exit
 *

 * Initiated by: External Process
 *

 * Message name: "exit"
 *

 * @event
 * @name module:RunSubcommand.exitMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */

// ******** Outbound Messages ********

/**
 * Indicates that a file was just entered
 *

 * Initiated by: Code Processor
 *

 * Message name: 'enteredFile'
 *

 * @event
 * @name module:RunSubcommand.enteredFileMessage
 * @param {String} request The absolute path to the file that was just entered
 * @param {Undefined} response There is no response data
 */

/**
 * Indicates that the current run of the project is about to be processed, and all pre-processing steps have been completed successfully
 *

 * Initiated by: Code Processor
 *

 * Message name: 'projectProcessingBegin'
 *

 * @event
 * @name module:RunSubcommand.projectProcessingBeginMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */

/**
 * Indicates that the current run of the project has finished being processed
 *

 * Initiated by: Code Processor
 *

 * Message name: 'projectProcessingEnd'
 *

 * @event
 * @name module:RunSubcommand.projectProcessingEndMessage
 * @param {Undefined} request There is no request data
 * @param {Undefined} response There is no response data
 */

/**
 * An error was found in the project
 *

 * Initiated by: Code Processor
 *

 * Message Name: 'error'
 *

 * @event
 * @name module:RunSubcommand.errorMessage
 * @param {Object} request The error that occured
 * @param {String} request.filename The path to the file where the error occured
 * @param {Number} request.line The line number where the error occured
 * @param {Number} request.column The column number where the error occured
 * @param {String} request.type The type of error (e.g. TypeError)
 * @param {String} request.description A description of the error
 * @param {Undefined} response There is no response data
 */

/**
 * A warning was found in the project
 *

 * Initiated by: Code Processor
 *

 * Message Name: 'warning'
 *

 * @event
 * @name module:RunSubcommand.warningMessage
 * @param {Object} request The warning that occured
 * @param {String} request.filename The path to the file where the warning occured
 * @param {Number} request.line The line number where the warning occured
 * @param {Number} request.column The column number where the warning occured
 * @param {String} request.type The type of warning (e.g. TypeError)
 * @param {String} request.description A description of the warning
 * @param {Undefined} response There is no response data
 */<|endoftext|>


<commit_before>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            node = unwrap(node);
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            node = unwrap(newElement);
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            node = unwrap(newChild);
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS,
        Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    (function ($createElement, $createElementNS) {
        document.createElement = function(tagName) {
            var elm = $createElement.call(this, tagName);
            if (tagName == "img") {
                var desc = {
                    set: function (newVal) {
                        desc.value = $url(newVal);
                        Object.defineProperty(elm, "src", desc)
                    },
                    get: function () {
                        return desc.value;
                    },
                    value: "", writable: false, enumerable: true, configurable: true
                };
                Object.defineProperty(elm, "src", desc)
            }

            return elm;
        };
    })(document.createElement, document.createElementNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    var wrap = function (object) {
        console.log("stub " + object.name);

        var _origin;

        function copy_prop(name, from, to) {
            if (from[name] != undefined && from[name] != to[name]) {
                if (is_url_prop(name)) {
                    var url = $url(from[name]);
                    to[name] = url;
                    from[name] = url;
                } else {
                    try {
                        to[name] = from[name];
                    } catch (e) {
                        //console.log(e);
                    }
                }
            }
        }

        function updateProps(stub) {
            for(prop in _origin) {
                if (typeof _origin[prop] != 'function') {
                    copy_prop(prop, stub, _origin);
                }
            }
        }

        var _returnOrigin = function() {
            updateProps(this);
            return _origin;
        };

        if (typeof object == 'function') {
            return function() {
                var $this = this;
                _origin = new object(arguments);
                for (prop in _origin) {
                    if (typeof _origin[prop] == 'function') {
                        var originalMethod = _origin[prop];
                        var method = function() {
                            console.log("method " + prop + " is called");
                            updateProps(this);
                            return originalMethod.apply(_origin, arguments);
                        }
                    } else {
                        var val = _origin[prop];
                        if (val != 0 && val != "" && val != undefined) {
                            copy_prop(prop, _origin, this);
                        }
                    }
                }

                this._returnOrigin = _returnOrigin;

            };
        } else if (typeof object == 'object') {

        }
    };

    var unwrap = function (object) {
        if (object instanceof wImage) {
            return object._returnOrigin();
        } else {
            return object;
        }
    };

    window.wrap = wrap;
    window.unwrap = unwrap;

    // todo intercept an insertion of this object into DOM
    window.Image = wImage = wrap(window.Image);

    //todo intercept document.createElement()

})(window, document);
<commit_msg>updated wrap method<commit_after>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            node = unwrap(node);
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            node = unwrap(newElement);
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            node = unwrap(newChild);
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS,
        Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    (function ($createElement, $createElementNS) {
        document.createElement = function(tagName) {
            var elm = $createElement.call(this, tagName);
            if (tagName == "img") {
                var desc = {
                    set: function (newVal) {
                        desc.value = $url(newVal);
                        Object.defineProperty(elm, "src", desc)
                    },
                    get: function () {
                        return desc.value;
                    },
                    value: "", writable: false, enumerable: true, configurable: true
                };
                Object.defineProperty(elm, "src", desc)
            }

            return elm;
        };
    })(document.createElement, document.createElementNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    var wrap = function (object) {
        console.log("stub " + object.name);

        var _origin = object;

        var _returnOrigin = function() {
            for (var prop in this) {
                if (!_origin[prop] && prop != "_real") {
                    console.log("copy new property " + prop);
                    _origin[prop] = this[prop];
                }
            }
            return _origin;
        };

        function reflect(from, to) {
            for (var prop in from) {
                if (typeof from[prop] == 'function') {
                    to[prop] = (function(method, prop) {
                        return function() {
                            console.log("method " + prop + " is called");
                            return method.apply(from, arguments);
                        }
                    })(from[prop], prop);
                } else {
                    (function(prop) {
                        Object.defineProperty(to, prop, {
                            set: function(newVal) {
                                console.log("set property " + prop + " to " + newVal);
                                if (is_url_prop(prop)) {
                                    from[prop] = $url(newVal);
                                } else {
                                    from[prop] = newVal;
                                }
                            },
                            get: function() {
                                console.log("get property " + prop);
                                return from[prop];
                            }
                        });
                    })(prop);
                }
            }

            return to;
        }

        if (typeof object == 'function') {
            return function() {
                _origin = new object(arguments);
                this._real = _returnOrigin;
                reflect(_origin, this);
            };
        } else if (typeof object == 'object') {
            var proxy = {
                _real: _returnOrigin
            };

            return reflect(_origin, proxy);
        }
    };

    var unwrap = function (object) {
        if (object instanceof wImage) {
            return object._real();
        } else {
            return object;
        }
    };

    window.wrap = wrap;
    window.unwrap = unwrap;

    // todo intercept an insertion of this object into DOM
    window.Image = wImage = wrap(window.Image);

    //todo intercept document.createElement()

})(window, document);
<|endoftext|>


<commit_before>
var koa = require('koa');
var jade = require('jade');
var path = require('path');

var app = module.exports = koa();

app.use(function* () {
  var filename = path.join(__dirname, 'homepage.jade');
  // this.response.body=
});
<commit_msg>finished 9<commit_after>
var koa = require('koa');
var jade = require('jade');
var path = require('path');

var app = module.exports = koa();

app.use(function* () {
    var filename = path.join(__dirname, 'homepage.jade');
    this.response.body = jade.renderFile(filename);
});
<|endoftext|>


<commit_before>var currentContent ="content1";
var switching = false;

var switchContent = (function(sender){
  var contentBlock = $(sender).attr("rel");
  if(!switching && contentBlock!=currentContent){
    switching = true;
    $("ul.features a").removeClass("active");
    $("#"+currentContent).fadeOut(500, function(){
      $("#"+contentBlock).fadeIn(1000, function(){
        switching = false;
      });
    });
    $("a[rel='"+contentBlock+"']").addClass("active");
    currentContent = contentBlock;
  }
});

var validateEmail = (function(address){
  // var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  // !(reg.test(address) == false);
  return true;
});

/*
 * DOM Ready
 */
$(document).ready(function() {
  var header    = $('#header'),
      footer    = $('#footer'),
      login     = $('#login'),
      subscribe = $('#subscribe');

  //borrowed from jQuery easing plugin
  //http://gsgd.co.uk/sandbox/jquery.easing.php
  $.easing.easeOutQuad = function(x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  };

  $(".links a", footer).mouseover(function(){
    $(this).stop();
    $(this).animate({ opacity: 1 }, 200);
  });

  $(".links a", footer).mouseout(function(){
    $(this).stop();
    $(this).animate({ opacity: 0.5 }, 200);
  });

  $('#selectAll').click(function(){
    var checked = $('#selectAll').is(':checked');
    $("td input[type='checkbox']").attr('checked', checked);
  });

  $("ul.features a,#header ul li.request a, a.toTab").each(function(){
    $(this).attr("href","javascript:;");
  });

  $("ul.features a").click(function(){
    switchContent(this);
  });

  $("ul li.login a", header).click(function(){
    if (login.hasClass('active')) {
      $(this).html("Login");
      login.fadeOut(500);
      login.removeClass('active');
    } else {
      $(this).html("Hide");
      login.fadeIn(1000);
      login.addClass('active');
      subscribe.fadeOut(250);
      subscribe.removeClass('active');
      $("ul li.subscribe a", header).html("Newsletter");
    }
  });

  $("ul li.subscribe a", header).click(function(){
    if (subscribe.hasClass('active')) {
      $(this).html("Newsletter");
      subscribe.fadeOut(500);
      subscribe.removeClass('active');
    } else {
      $(this).html('Hide');
      subscribe.fadeIn(1000);
      subscribe.addClass('active');
      login.fadeOut(250);
      login.removeClass('active');
      $("ul li.login a", header).html("Login");
    }
  });

  $("a.toTab").click(function(){
    switchContent(this);
  });

  $("ul li.request a", header).click(function(){
    switchContent(this);
    $.scrollTo($("#container"), 1500, {easing:'easeOutQuad'});
  });

  $("form.emailForm").submit(function(){
    var email      = $("#invitation_request_email").attr("value"),
        authentity = $("input[name='authenticity_token']").attr("value");
    $("span.valid").hide();
    $("span.invalid").hide();
    if (validateEmail(email)) {
      var post_data = {
        "invitation_request[email]": email,
        "authenticity_token":        authentity };
      $.post("/invitation_requests.js", post_data, function(data){
        $("span.valid").html("Thank you for your request. You will receive an e-mail very soon!");
        $("span.valid").attr("style","display:block;");
      });
    } else {
      $("span.invalid").html("Please enter a valid e-mail address.");
      $("span.invalid").attr("style","display:block;");
    }
    return false;
  });

  /*
   * Clearfield
   */
  $('.clear-field').clearField();

  /*
   * Table sorter
   */
   // $("table.sortable").tablesorter({textExtraction: 'complex'});
   // $("table.sortable th").filter(function(idx){
   //     if ($(this).hasClass('sortable')) {
   //         return false;
   //     } else {
   //         return $(this);
   //     }
   // }).unbind('click');

}); // End DOM ready
<commit_msg>Re-adding the email validation<commit_after>var currentContent ="content1";
var switching = false;

var switchContent = (function(sender){
  var contentBlock = $(sender).attr("rel");
  if(!switching && contentBlock!=currentContent){
    switching = true;
    $("ul.features a").removeClass("active");
    $("#"+currentContent).fadeOut(500, function(){
      $("#"+contentBlock).fadeIn(1000, function(){
        switching = false;
      });
    });
    $("a[rel='"+contentBlock+"']").addClass("active");
    currentContent = contentBlock;
  }
});

var validateEmail = (function(address){
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  return reg.test(address);
});

/*
 * DOM Ready
 */
$(document).ready(function() {
  var header    = $('#header'),
      footer    = $('#footer'),
      login     = $('#login'),
      subscribe = $('#subscribe');

  //borrowed from jQuery easing plugin
  //http://gsgd.co.uk/sandbox/jquery.easing.php
  $.easing.easeOutQuad = function(x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  };

  $(".links a", footer).mouseover(function(){
    $(this).stop();
    $(this).animate({ opacity: 1 }, 200);
  });

  $(".links a", footer).mouseout(function(){
    $(this).stop();
    $(this).animate({ opacity: 0.5 }, 200);
  });

  $('#selectAll').click(function(){
    var checked = $('#selectAll').is(':checked');
    $("td input[type='checkbox']").attr('checked', checked);
  });

  $("ul.features a,#header ul li.request a, a.toTab").each(function(){
    $(this).attr("href","javascript:;");
  });

  $("ul.features a").click(function(){
    switchContent(this);
  });

  $("ul li.login a", header).click(function(){
    if (login.hasClass('active')) {
      $(this).html("Login");
      login.fadeOut(500);
      login.removeClass('active');
    } else {
      $(this).html("Hide");
      login.fadeIn(1000);
      login.addClass('active');
      subscribe.fadeOut(250);
      subscribe.removeClass('active');
      $("ul li.subscribe a", header).html("Newsletter");
    }
  });

  $("ul li.subscribe a", header).click(function(){
    if (subscribe.hasClass('active')) {
      $(this).html("Newsletter");
      subscribe.fadeOut(500);
      subscribe.removeClass('active');
    } else {
      $(this).html('Hide');
      subscribe.fadeIn(1000);
      subscribe.addClass('active');
      login.fadeOut(250);
      login.removeClass('active');
      $("ul li.login a", header).html("Login");
    }
  });

  $("a.toTab").click(function(){
    switchContent(this);
  });

  $("ul li.request a", header).click(function(){
    switchContent(this);
    $.scrollTo($("#container"), 1500, {easing:'easeOutQuad'});
  });

  $("form.emailForm").submit(function(){
    var email      = $("#invitation_request_email").attr("value"),
        authentity = $("input[name='authenticity_token']").attr("value");
    $("span.valid").hide();
    $("span.invalid").hide();
    if (validateEmail(email)) {
      var post_data = {
        "invitation_request[email]": email,
        "authenticity_token":        authentity };
      $.post("/invitation_requests.js", post_data, function(data){
        $("span.valid").html("Thank you for your request. You will receive an e-mail very soon!");
        $("span.valid").attr("style","display:block;");
      });
    } else {
      $("span.invalid").html("Please enter a valid e-mail address.");
      $("span.invalid").attr("style","display:block;");
    }
    return false;
  });

  /*
   * Clearfield
   */
  $('.clear-field').clearField();

  try {
    /*
     * Table sorter
     */
    $("table.sortable").tablesorter({textExtraction: 'complex'});
    $("table.sortable th").filter(function(idx){
        if ($(this).hasClass('sortable')) {
            return false;
        } else {
            return $(this);
        }
    }).unbind('click');
  } catch (e) { /* ignore */ };

}); // End DOM ready
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import Button, { IconButton } from '../button';
import cx from 'classnames';
import theme from './theme.css';
import { IconCloseMediumOutline, IconCloseSmallOutline } from '@teamleader/ui-icons';

class Tag extends PureComponent {
  render() {
    const { children, className, inverse, onLabelClick, onRemoveClick, size, color, disabled, ...others } = this.props;

    const classNames = cx(
      theme['tag'],
      theme[`is-${size}`],
      theme[color],
      {
        [theme['is-removable']]: onRemoveClick,
        [theme['is-inverse']]: inverse,
        [theme['is-disabled']]: disabled,
      },
      className,
    );

    const closeButtonColor = inverse ? 'white' : 'neutral';
    const closeButtonIcon = size === 'large' ? <IconCloseMediumOutline /> : <IconCloseSmallOutline />;

    return (
      <Box className={classNames} data-teamleader-ui="tag" {...others}>
        {onLabelClick ? (
          <Button
            className={theme['label-button']}
            onClick={onLabelClick}
            level="outline"
            inverse={inverse}
            disabled={disabled}
          >
            {children}
          </Button>
        ) : (
          {children}
        )}

        {onRemoveClick && (
          <IconButton
            className={theme['remove-button']}
            color={closeButtonColor}
            icon={closeButtonIcon}
            onClick={onRemoveClick}
            size="small"
            disabled={disabled}
          />
        )}
      </Box>
    );
  }
}

Tag.propTypes = {
  children: PropTypes.any.isRequired,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  inverse: PropTypes.bool,
  onLabelClick: PropTypes.func,
  onRemoveClick: PropTypes.func,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  color: PropTypes.oneOf(['neutral', 'mint', 'gold', 'ruby', 'violet', 'aqua']),
};

Tag.defaultProps = {
  inverse: false,
  size: 'medium',
  color: 'neutral',
};

export default Tag;
<commit_msg>close button is always small so remove the medium icon if tag size is large<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import Button, { IconButton } from '../button';
import cx from 'classnames';
import theme from './theme.css';
import { IconCloseMediumOutline, IconCloseSmallOutline } from '@teamleader/ui-icons';

class Tag extends PureComponent {
  render() {
    const { children, className, inverse, onLabelClick, onRemoveClick, size, color, disabled, ...others } = this.props;

    const classNames = cx(
      theme['tag'],
      theme[`is-${size}`],
      theme[color],
      {
        [theme['is-removable']]: onRemoveClick,
        [theme['is-inverse']]: inverse,
        [theme['is-disabled']]: disabled,
      },
      className,
    );

    const closeButtonColor = inverse ? 'white' : 'neutral';
    const closeButtonIcon = <IconCloseSmallOutline />;

    return (
      <Box className={classNames} data-teamleader-ui="tag" {...others}>
        {onLabelClick ? (
          <Button
            className={theme['label-button']}
            onClick={onLabelClick}
            level="outline"
            inverse={inverse}
            disabled={disabled}
          >
            {children}
          </Button>
        ) : (
          {children}
        )}

        {onRemoveClick && (
          <IconButton
            className={theme['remove-button']}
            color={closeButtonColor}
            icon={closeButtonIcon}
            onClick={onRemoveClick}
            size="small"
            disabled={disabled}
          />
        )}
      </Box>
    );
  }
}

Tag.propTypes = {
  children: PropTypes.any.isRequired,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  inverse: PropTypes.bool,
  onLabelClick: PropTypes.func,
  onRemoveClick: PropTypes.func,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  color: PropTypes.oneOf(['neutral', 'mint', 'gold', 'ruby', 'violet', 'aqua']),
};

Tag.defaultProps = {
  inverse: false,
  size: 'medium',
  color: 'neutral',
};

export default Tag;
<|endoftext|>


<commit_before>const DEBUG = false;

var gLogger = {
  messages: [],
  log: function(aMessage) {
    this.messages.push(aMessage);
    this.output();
  },
  output: function() {
    if (!DEBUG)
      return;
    Components.utils.import('resource://force-addon-status-modules/lib/textIO.jsm');
    var file = Cc['@mozilla.org/file/directory_service;1']
                 .getService(Ci.nsIProperties)
                 .get('Desk', Ci.nsIFile);
    file.append('force-addon-status.log');
    var previous = textIO.readFrom(file, 'UTF-8') || '';
    var log = [previous, this.messages.join('\n')].join('\n-----' + (new Date()) + '-----\n');
    textIO.writeTo(log, file, 'UTF-8');
/*
    Cc['@mozilla.org/embedcomp/prompt-service;1']
      .getService(Ci.nsIPromptService)
      .alert(null, kID, file.path+'\n\n'+this.messages.join('\n'));;
*/
  }
}

const kCID  = Components.ID('{cd2892e0-87a8-11e2-9e96-0800200c9a66}');
const kID   = '@clear-code.com/force-addon-status/startup;1';
const kNAME = 'ForceAddonStatusStartupService';

const Cc = Components.classes;
const Ci = Components.interfaces;

const ObserverService = Cc['@mozilla.org/observer-service;1']
                         .getService(Ci.nsIObserverService);

Components.utils.import('resource://gre/modules/AddonManager.jsm');

Components.utils.import('resource://force-addon-status-modules/lib/prefs.js');
Components.utils.import('resource://force-addon-status-modules/lib/jsdeferred.js');

const BASE = 'extensions.force-addon-status@clear-code.com.';

function ForceAddonStatusStartupService() {
  this.ready = false;
  this.active = false;
}
ForceAddonStatusStartupService.prototype = {
  classID          : kCID,
  contractID       : kID,
  classDescription : kNAME,

  observe : function(aSubject, aTopic, aData)
  {
    gLogger.log('observe: ' + aTopic);
    switch (aTopic)
    {
      case 'profile-after-change':
        ObserverService.addObserver(this, 'final-ui-startup', false);
        ObserverService.addObserver(this, 'sessionstore-windows-restored', false);
        ObserverService.addObserver(this, 'mail-startup-done', false);
        return;

      case 'final-ui-startup':
        ObserverService.removeObserver(this, 'final-ui-startup');
        this.registerListener();
        var self = this;
        return this.waitUntilStarted()
          .next(function() {
            return self.checkStatus();
          })
          .next(function() {
            self.active = true;
          });
        return;

      case 'sessionstore-windows-restored':
      case 'mail-startup-done':
        ObserverService.removeObserver(this, 'sessionstore-windows-restored');
        ObserverService.removeObserver(this, 'mail-startup-done');
        this.ready = true;
        if (this.waitUntilStarted_trigger)
          this.waitUntilStarted_trigger.call();
        return;
    }
  },

  checkStatus : function()
  {
    if (this.checking)
      return;
    this.checking = true;

    var self = this;
    var changedCount = { value : 0 };
    return Deferred.next(function() {
        self.checkExtensionsStatus(changedCount);
      })
      .next(function() {
        return self.checkPluginsStatus();
      })
      .next(function() {
        gLogger.log(changedCount.value + ' changed addon(s)');
        if (changedCount.value > 0)
          self.restart();
      })
      .error(function(error) {
        Components.utils.reportError(error);
        gLogger.log('unexpected error: ' + error + '\n' + error.stack);
      })
      .next(function() {
        self.checking = false;
      });
  },

  checkExtensionsStatus : function(aChangedCount)
  {
    gLogger.log('ForceAddonStatusStartupService::checkExtensionsStatus');
    var deferredTasks = [];

    var prefix = BASE + 'addons.';
    var keys = prefs.getDescendant(prefix);
    aChangedCount.value = aChangedCount.value || 0;
    keys.forEach(function(aKey) {
      if (!aKey)
        return;

      var id = aKey.replace(prefix, '');
      gLogger.log('  id ' + id);
      var newStatus;
      if (/\.status$/.test(id)) {
        newStatus = prefs.getPref(aKey);
        id = id.replace(/\.status$/, '');
        gLogger.log('  => ' + id);
      } else { // backward compatibility
        newStatus = prefs.getPref(aKey);
        if (newStatus)
          newStatus = 'enabled';
        else
          newStatus = 'disabled';
      }

      newStatus = String(newStatus).toLowerCase();

      gLogger.log('  newStatus ' + newStatus);

      var deferred = new Deferred();
      AddonManager.getAddonByID(id, function(aAddon) {
        if (!aAddon) {
          gLogger.log('  => not installed.');
          return deferred.call();
        }

        var shouldBeActive = newStatus.indexOf('enabled') > -1 || newStatus.indexOf('disabled') < 0;
        if (newStatus.indexOf('disabled') > -1)
          shouldBeActive = false;
        gLogger.log('  shouldBeActive ' + shouldBeActive);
        if (aAddon.isActive != shouldBeActive) {
          aAddon.userDisabled = !shouldBeActive;
          gLogger.log(aAddon.userDisabled ? ' => deactivated' : ' => activated');
          aChangedCount.value++;
        }

        var shouldUninstall = newStatus.indexOf('uninstall') > -1;
        gLogger.log('  shouldUninstall ' + shouldUninstall);
        var shouldGlobal = newStatus.indexOf('global') > -1;
        gLogger.log('  shouldGlobal ' + shouldGlobal);
        var isGlobal = aAddon.scope != AddonManager.SCOPE_PROFILE;
        gLogger.log('  isGlobal ' + isGlobal);
        if (shouldUninstall || shouldGlobal != isGlobal) {
          aAddon.uninstall();
          gLogger.log(' => uninstalled');
          aChangedCount.value++;
        }

        deferred.call();
      });
      deferredTasks.push(deferred);
    });

    if (deferredTasks.length > 0)
      return Deferred.parallel(deferredTasks);
  },

  checkPluginsStatus : function()
  {
    var controlledPlugins = prefs.getChildren(BASE + 'plugins.');
    if (controlledPlugins.length == 0)
      return;

    var allPatterns = [];
    controlledPlugins = controlledPlugins.map(function(aEntryBaseKey) {
      var pattern = prefs.getPref(aEntryBaseKey + '.pattern');
      if (!pattern) return null;
      allPatterns.push(pattern);
      return {
        pattern :        new RegExp(pattern),
        shouldBeActive : prefs.getPref(aEntryBaseKey + '.status'),
        blocklisted :    prefs.getPref(aEntryBaseKey + '.blocklisted')
      };
    });
    controlledPlugins = controlledPlugins.filter(function(aControl) {
      return aControl;
    });

    allPatterns = new RegExp('(' + allPatterns.join('|') + ')');

    var PluginHost = Cc['@mozilla.org/plugin/host;1']
                      .getService(Ci.nsIPluginHost);
    var plugins = PluginHost.getPluginTags();
    plugins.forEach(function(aPluginTag) {
      if (!allPatterns.test(aPluginTag.name))
        return;

      controlledPlugins.some(function(aControl) {
        if (!aControl.pattern.test(aPluginTag.name))
          return false;
        if (aControl.shouldBeActive !== null &&
            aPluginTag.disabled !== !aControl.shouldBeActive) {
          aPluginTag.disabled = !aControl.shouldBeActive;
        }
        if (aControl.blocklisted !== null &&
            aPluginTag.blocklisted !== aControl.blocklisted) {
          aPluginTag.blocklisted = !!aControl.blocklisted;
        }
        return true;
      });
    });
  },

  registerListener : function()
  {
    AddonManager.addAddonListener(this);
  },
  onEnabling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onEnabled : function(aAddon) {
  },
  onDisabling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onDisabled : function(aAddon) {
  },
  onInstalling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onInstalled : function(aAddon) {
  },
  onUninstalling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onUninstalled : function(aAddon) {
  },
  onOperationCancelled : function(aAddon) {
    if (this.active)
      this.checkStatus();
  },
  onPropertyChanged : function(aAddon, aProperties) {
    if (this.active)
      this.checkStatus();
  },

  waitUntilStarted : function() {
    if (this.ready)
      return;

    this.waitUntilStarted_trigger = new Deferred();
    return this.waitUntilStarted_trigger;
  },

  restart : function()
  {
    gLogger.log('try to restart');
    Cc['@mozilla.org/toolkit/app-startup;1']
      .getService(Ci.nsIAppStartup)
      .quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit);
  },

  QueryInterface : function(aIID)
  {
    if(!aIID.equals(Ci.nsIObserver) &&
       !aIID.equals(Ci.nsISupports)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    return this;
  }
};

Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
var NSGetFactory = XPCOMUtils.generateNSGetFactory([ForceAddonStatusStartupService]);
<commit_msg>Output log line with timestamp<commit_after>const DEBUG = false;

var gLogger = {
  messages: [],
  log: function(aMessage) {
    this.messages.push(aMessage);
    this.output(aMessage);
  },
  output: function(aMessage) {
    if (!DEBUG)
      return;
    Components.utils.import('resource://force-addon-status-modules/lib/textIO.jsm');
    var file = Cc['@mozilla.org/file/directory_service;1']
                 .getService(Ci.nsIProperties)
                 .get('Desk', Ci.nsIFile);
    file.append('force-addon-status.log');
    var previous = textIO.readFrom(file, 'UTF-8') || '';
    var log;
    if (aMessage) {
      log = previous + '\n[' + (new Date()) + '] ' + aMessage;
    } else {
      log = [previous, this.messages.join('\n')].join('\n-----' + (new Date()) + '-----\n');
    }
    textIO.writeTo(log, file, 'UTF-8');
/*
    Cc['@mozilla.org/embedcomp/prompt-service;1']
      .getService(Ci.nsIPromptService)
      .alert(null, kID, file.path+'\n\n'+this.messages.join('\n'));;
*/
  }
}

const kCID  = Components.ID('{cd2892e0-87a8-11e2-9e96-0800200c9a66}');
const kID   = '@clear-code.com/force-addon-status/startup;1';
const kNAME = 'ForceAddonStatusStartupService';

const Cc = Components.classes;
const Ci = Components.interfaces;

const ObserverService = Cc['@mozilla.org/observer-service;1']
                         .getService(Ci.nsIObserverService);

Components.utils.import('resource://gre/modules/AddonManager.jsm');

Components.utils.import('resource://force-addon-status-modules/lib/prefs.js');
Components.utils.import('resource://force-addon-status-modules/lib/jsdeferred.js');

const BASE = 'extensions.force-addon-status@clear-code.com.';

function ForceAddonStatusStartupService() {
  this.ready = false;
  this.active = false;
}
ForceAddonStatusStartupService.prototype = {
  classID          : kCID,
  contractID       : kID,
  classDescription : kNAME,

  observe : function(aSubject, aTopic, aData)
  {
    gLogger.log('observe: ' + aTopic);
    switch (aTopic)
    {
      case 'profile-after-change':
        ObserverService.addObserver(this, 'final-ui-startup', false);
        ObserverService.addObserver(this, 'sessionstore-windows-restored', false);
        ObserverService.addObserver(this, 'mail-startup-done', false);
        return;

      case 'final-ui-startup':
        ObserverService.removeObserver(this, 'final-ui-startup');
        this.registerListener();
        var self = this;
        return this.waitUntilStarted()
          .next(function() {
            return self.checkStatus();
          })
          .next(function() {
            self.active = true;
          });
        return;

      case 'sessionstore-windows-restored':
      case 'mail-startup-done':
        ObserverService.removeObserver(this, 'sessionstore-windows-restored');
        ObserverService.removeObserver(this, 'mail-startup-done');
        this.ready = true;
        if (this.waitUntilStarted_trigger)
          this.waitUntilStarted_trigger.call();
        return;
    }
  },

  checkStatus : function()
  {
    if (this.checking)
      return;
    this.checking = true;

    var self = this;
    var changedCount = { value : 0 };
    return Deferred.next(function() {
        self.checkExtensionsStatus(changedCount);
      })
      .next(function() {
        return self.checkPluginsStatus();
      })
      .next(function() {
        gLogger.log(changedCount.value + ' changed addon(s)');
        if (changedCount.value > 0)
          self.restart();
      })
      .error(function(error) {
        Components.utils.reportError(error);
        gLogger.log('unexpected error: ' + error + '\n' + error.stack);
      })
      .next(function() {
        self.checking = false;
      });
  },

  checkExtensionsStatus : function(aChangedCount)
  {
    gLogger.log('ForceAddonStatusStartupService::checkExtensionsStatus');
    var deferredTasks = [];

    var prefix = BASE + 'addons.';
    var keys = prefs.getDescendant(prefix);
    aChangedCount.value = aChangedCount.value || 0;
    keys.forEach(function(aKey) {
      if (!aKey)
        return;

      var id = aKey.replace(prefix, '');
      gLogger.log('  id ' + id);
      var newStatus;
      if (/\.status$/.test(id)) {
        newStatus = prefs.getPref(aKey);
        id = id.replace(/\.status$/, '');
        gLogger.log('  => ' + id);
      } else { // backward compatibility
        newStatus = prefs.getPref(aKey);
        if (newStatus)
          newStatus = 'enabled';
        else
          newStatus = 'disabled';
      }

      newStatus = String(newStatus).toLowerCase();

      gLogger.log('  newStatus ' + newStatus);

      var deferred = new Deferred();
      AddonManager.getAddonByID(id, function(aAddon) {
        if (!aAddon) {
          gLogger.log('  => not installed.');
          return deferred.call();
        }

        var shouldBeActive = newStatus.indexOf('enabled') > -1 || newStatus.indexOf('disabled') < 0;
        if (newStatus.indexOf('disabled') > -1)
          shouldBeActive = false;
        gLogger.log('  shouldBeActive ' + shouldBeActive);
        if (aAddon.isActive != shouldBeActive) {
          aAddon.userDisabled = !shouldBeActive;
          gLogger.log(aAddon.userDisabled ? ' => deactivated' : ' => activated');
          aChangedCount.value++;
        }

        var shouldUninstall = newStatus.indexOf('uninstall') > -1;
        gLogger.log('  shouldUninstall ' + shouldUninstall);
        var shouldGlobal = newStatus.indexOf('global') > -1;
        gLogger.log('  shouldGlobal ' + shouldGlobal);
        var isGlobal = aAddon.scope != AddonManager.SCOPE_PROFILE;
        gLogger.log('  isGlobal ' + isGlobal);
        if (shouldUninstall || shouldGlobal != isGlobal) {
          aAddon.uninstall();
          gLogger.log(' => uninstalled');
          aChangedCount.value++;
        }

        deferred.call();
      });
      deferredTasks.push(deferred);
    });

    if (deferredTasks.length > 0)
      return Deferred.parallel(deferredTasks);
  },

  checkPluginsStatus : function()
  {
    var controlledPlugins = prefs.getChildren(BASE + 'plugins.');
    if (controlledPlugins.length == 0)
      return;

    var allPatterns = [];
    controlledPlugins = controlledPlugins.map(function(aEntryBaseKey) {
      var pattern = prefs.getPref(aEntryBaseKey + '.pattern');
      if (!pattern) return null;
      allPatterns.push(pattern);
      return {
        pattern :        new RegExp(pattern),
        shouldBeActive : prefs.getPref(aEntryBaseKey + '.status'),
        blocklisted :    prefs.getPref(aEntryBaseKey + '.blocklisted')
      };
    });
    controlledPlugins = controlledPlugins.filter(function(aControl) {
      return aControl;
    });

    allPatterns = new RegExp('(' + allPatterns.join('|') + ')');

    var PluginHost = Cc['@mozilla.org/plugin/host;1']
                      .getService(Ci.nsIPluginHost);
    var plugins = PluginHost.getPluginTags();
    plugins.forEach(function(aPluginTag) {
      if (!allPatterns.test(aPluginTag.name))
        return;

      controlledPlugins.some(function(aControl) {
        if (!aControl.pattern.test(aPluginTag.name))
          return false;
        if (aControl.shouldBeActive !== null &&
            aPluginTag.disabled !== !aControl.shouldBeActive) {
          aPluginTag.disabled = !aControl.shouldBeActive;
        }
        if (aControl.blocklisted !== null &&
            aPluginTag.blocklisted !== aControl.blocklisted) {
          aPluginTag.blocklisted = !!aControl.blocklisted;
        }
        return true;
      });
    });
  },

  registerListener : function()
  {
    AddonManager.addAddonListener(this);
  },
  onEnabling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onEnabled : function(aAddon) {
  },
  onDisabling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onDisabled : function(aAddon) {
  },
  onInstalling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onInstalled : function(aAddon) {
  },
  onUninstalling : function(aAddon, aNeedsRestart) {
    if (this.active)
      this.checkStatus();
  },
  onUninstalled : function(aAddon) {
  },
  onOperationCancelled : function(aAddon) {
    if (this.active)
      this.checkStatus();
  },
  onPropertyChanged : function(aAddon, aProperties) {
    if (this.active)
      this.checkStatus();
  },

  waitUntilStarted : function() {
    if (this.ready)
      return;

    this.waitUntilStarted_trigger = new Deferred();
    return this.waitUntilStarted_trigger;
  },

  restart : function()
  {
    gLogger.log('try to restart');
    Cc['@mozilla.org/toolkit/app-startup;1']
      .getService(Ci.nsIAppStartup)
      .quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit);
  },

  QueryInterface : function(aIID)
  {
    if(!aIID.equals(Ci.nsIObserver) &&
       !aIID.equals(Ci.nsISupports)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    return this;
  }
};

Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
var NSGetFactory = XPCOMUtils.generateNSGetFactory([ForceAddonStatusStartupService]);
<|endoftext|>


<commit_before>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS, Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, childList: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    function wrap(object) {
        console.log("stub " + object.name);
        return function(args) {
            var _origin = new object();
            for (prop in _origin) {
                if (typeof _origin[prop] == 'function') {
                    var originalMethod = _origin[prop];
                    var method = function() {
                        console.log("method " + prop + " is called");
                        updateProps(this);
                        return originalMethod.apply(_origin, args);
                    }
                } else {
                    var val = _origin[prop];
                    if (val == 0 || val == "") {
                    } else {
                        copy_prop(prop, _origin, this);
                    }
                }
            }

            function copy_prop(name, from, to) {
                if (is_url_prop(name)) {
                    var url = $url(from[prop]);
                    to[prop] = url;
                    from[prop] = url;

                } else {
                    try {
                        to[prop] = from[prop];
                    } catch (e) {
                        console.log(e);
                    }
                }
            }

            function updateProps(stub) {
                for(prop in _origin) {
                    if (typeof _origin[prop] != 'function') {
                        copy_prop(prop, stub, _origin);
                    }
                }
            }

            this._returnOrigin = function() {
                updateProps(this);
                return _origin;
            }

            window.setTimeout(function () {
                updateProps(this);
            }, 1000);

        };
    }

    // todo intercept an insertion of this object into DOM
    window.Image = wrap(window.Image);

    //todo intercept document.createElement()

})(window, document);
<commit_msg>fixed bug<commit_after>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS, Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, childList: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    function wrap(object) {
        console.log("stub " + object.name);
        return function(args) {
            var $this = this;
            var _origin = new object();
            for (prop in _origin) {
                if (typeof _origin[prop] == 'function') {
                    var originalMethod = _origin[prop];
                    var method = function() {
                        console.log("method " + prop + " is called");
                        updateProps(this);
                        return originalMethod.apply(_origin, args);
                    }
                } else {
                    var val = _origin[prop];
                    if (val == 0 || val == "") {
                    } else {
                        copy_prop(prop, _origin, this);
                    }
                }
            }

            function copy_prop(name, from, to) {
                if (is_url_prop(name)) {
                    var url = $url(from[prop]);
                    to[prop] = url;
                    from[prop] = url;

                } else {
                    try {
                        to[prop] = from[prop];
                    } catch (e) {
                        //console.log(e);
                    }
                }
            }

            function updateProps(stub) {
                for(prop in _origin) {
                    if (typeof _origin[prop] != 'function') {
                        copy_prop(prop, stub, _origin);
                    }
                }
            }

            this._returnOrigin = function() {
                updateProps($this);
                return _origin;
            }

            window.setTimeout(function () {
                updateProps($this);
            }, 1000);

        };
    }

    // todo intercept an insertion of this object into DOM
    window.Image = wrap(window.Image);

    //todo intercept document.createElement()

})(window, document);
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// TODO: change css and image to be error-ish
function error_growl_template()
{
		jQuery.growl.settings.displayTimeout = 6000;
		jQuery.growl.settings.noticeTemplate = ''
			+ '
'
			+ '

'
			+ '
'
			+ ' '
			+ '
%title%
'
			+ '
%message%
'
			+ '
'
			+ '

'
			+ '
';
		jQuery.growl.settings.noticeCss = {
			position: 'relative'
		};

}

// TODO: add real image paths..
function notice_growl_template()
{
		jQuery.growl.settings.displayTimeout = 4000;
		jQuery.growl.settings.noticeTemplate = ''
			+ '
'
			+ '

'
			+ '
'
			+ ' '
			+ '
%title%
'
			+ '
%message%
'
			+ '
'
			+ '

'
			+ '
';
		jQuery.growl.settings.noticeCss = {
			position: 'relative'
		};
}

// Trigger a growl alert. Call one of the above template methods if you want to
function notify(message, title)
{
	jQuery.growl(title || 'Notice', message || '');
	jQuery.growl.settings = $default_growl_settings;
}

jQuery(document).ready(function()
{
	// Prevent the default growl settings from being overwritten. OH NOES A GLOBAL
	$default_growl_settings = jQuery.growl.settings;

	var jq = jQuery.noConflict();
	jq('a.edit_page_plugin', jq('#page_plugins')).click(function()
	{
		var modal = jq('#modal');
		if(modal.html() == "")
		{
			jq.ajax({
				type: 'GET',
				url: jq(this).attr('href'),
				complete: function(transport)
				{
					modal.jqm({overlay: 50});

					jq('a.jqmClose').click(function(){
						jq(this).jqmHide();
						return false;
					});

					modal.jqmHide();
					modal.html(transport.responseText)
					modal.jqmShow();
				}
			});
		} else {
			// Don't load it again
			modal.jqmShow();
		}
		return false
	});

});

<commit_msg>whatever<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// TODO: change css and image to be error-ish
function error_growl_template()
{
		jQuery.growl.settings.displayTimeout = 6000;
		jQuery.growl.settings.noticeTemplate = ''
			+ '
'
			+ '

'
			+ '
'
			+ ' '
			+ '
%title%
'
			+ '
%message%
'
			+ '
'
			+ '

'
			+ '
';
		jQuery.growl.settings.noticeCss = {
			position: 'relative'
		};

}

// TODO: add real image paths..
function notice_growl_template()
{
		jQuery.growl.settings.displayTimeout = 4000;
		jQuery.growl.settings.noticeTemplate = ''
			+ '
'
			+ '

'
			+ '
'
			+ ' '
			+ '
%title%
'
			+ '
%message%
'
			+ '
'
			+ '

'
			+ '
';
		jQuery.growl.settings.noticeCss = {
			position: 'relative'
		};
}

// Trigger a growl alert. Call one of the above template methods before this guy if you want to style it
function notify(message, title)
{
	jQuery.growl(title || 'Notice', message || '');
	jQuery.growl.settings = $default_growl_settings;
}

jQuery(document).ready(function()
{
	// Prevent the default growl settings from being overwritten.
	$default_growl_settings = jQuery.growl.settings;

	var jq = jQuery.noConflict();
	jq('a.edit_page_plugin', jq('#page_plugins')).click(function()
	{
		var modal = jq('#modal');
		if(modal.html() == "")
		{
			jq.ajax({
				type: 'GET',
				url: jq(this).attr('href'),
				complete: function(transport)
				{
					modal.jqm({overlay: 50});

					jq('a.jqmClose').click(function(){
						jq(this).jqmHide();
						return false;
					});

					modal.jqmHide();
					modal.html(transport.responseText)
					modal.jqmShow();
				}
			});
		} else {
			// Don't load it again
			modal.jqmShow();
		}
		return false
	});

});

<|endoftext|>


<commit_before>var BigInt = this.BigInt || function () {
    function BigInt(a) {
        if (this instanceof BigInt) {
            this.val = a;
        }
        else if (a instanceof BigInt) return a;
        else return new BigInt(a);
    };
    var prototype = new BigInt;
    prototype.toString = function () {
        return this.val;
    };
    prototype.valueOf = function () {
        return this;
    }
    BigInt.prototype = prototype;
    return BigInt;
}()
<commit_msg>BigInt支持比较大小<commit_after>var BigInt = this.BigInt || function () {
    var map = {};

    function BigInt(a) {
        if (this instanceof BigInt) {
            if (map[a]) return map[a];
            this.val = a;
            map[a] = this;
        }
        else if (a instanceof BigInt) return a;
        else return new BigInt(a);
    };
    var prototype = new BigInt;
    prototype.toString = function () {
        return this.val;
    };
    prototype.valueOf = function () {
        return this;
    }
    BigInt.prototype = prototype;
    return BigInt;
}()
<|endoftext|>