<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author jonobr1 / http://jonobr1.com/
 */

THREE.Mesh = function ( geometry, material ) {

	THREE.Object3D.call( this );

	this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
	this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );

	this.updateMorphTargets();

};

THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );

THREE.Mesh.prototype.updateMorphTargets = function () {

	if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {

		this.morphTargetBase = -1;
		this.morphTargetForcedOrder = [];
		this.morphTargetInfluences = [];
		this.morphTargetDictionary = {};

		for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {

			this.morphTargetInfluences.push( 0 );
			this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;

		}

	}

};

THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {

	if ( this.morphTargetDictionary[ name ] !== undefined ) {

		return this.morphTargetDictionary[ name ];

	}

	console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );

	return 0;

};

THREE.Mesh.prototype.clone = function ( object ) {

	if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );

	THREE.Object3D.prototype.clone.call( this, object );

	return object;

};
<commit_msg>Pass recursive flag through from THREE.Mesh.clone() to THREE.Object3D.clone()<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author jonobr1 / http://jonobr1.com/
 */

THREE.Mesh = function ( geometry, material ) {

	THREE.Object3D.call( this );

	this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
	this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );

	this.updateMorphTargets();

};

THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );

THREE.Mesh.prototype.updateMorphTargets = function () {

	if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {

		this.morphTargetBase = -1;
		this.morphTargetForcedOrder = [];
		this.morphTargetInfluences = [];
		this.morphTargetDictionary = {};

		for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {

			this.morphTargetInfluences.push( 0 );
			this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;

		}

	}

};

THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {

	if ( this.morphTargetDictionary[ name ] !== undefined ) {

		return this.morphTargetDictionary[ name ];

	}

	console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );

	return 0;

};

THREE.Mesh.prototype.clone = function ( object, recursive ) {

	if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );

	THREE.Object3D.prototype.clone.call( this, object, recursive );

	return object;

};
<|endoftext|>


<commit_before>var os = require('os');

module.exports = Loggr;

var LEVELS = Loggr.LEVELS = {
    OFF: 0,
    INFO: 1,
    DEBUG: 2,
    TRACE: 3,
    ALL: Number.POSITIVE_INFINITY,
};

// TODO accept string levels, normalize internally to numbers

// TODO more/optional outputs
// TODO string substitution, multiple params, etc

function Loggr(config) {
    var c = config || {};

    c.level = c.level || c.logLevel || LEVELS.INFO;
    c.showTime = 'showTime' in c ? Boolean(c.showTime) : true;
    c.namespace = c.namespace || null;
    c.outStream = c.outStream || process.stdout || { write: console.log.bind(console) };
    c.eol = c.eol || os.EOL;

    this.config = c;
}

Loggr.prototype.fork = function (newNamespace) {
    var conf = this.config;

    return new Loggr({
        level: conf.level,
        showTime: conf.showTime,
        namespace: newNamespace,
        outStream: conf.outStream,
        eol: conf.eol,
    });
};

Loggr.prototype._log = function (lvl, messages) {
    if (lvl <= this.config.level) {
        var time = '';
        var namespace = '';

        if (this.config.showTime) {
            var d = new Date();
            var h = ('0' + d.getHours()).slice(-2);
            var m = ('0' + d.getMinutes()).slice(-2);
            var s = ('0' + d.getSeconds()).slice(-2);
            var ms = ('00' + d.getMilliseconds()).slice(-3);

            time = '[' + h + ':' + m + ':' + s + '.' + ms + '] ';
        }

        if (this.config.namespace) {
            namespace = '[' + this.config.namespace + '] ';
        }

        var message = messages
        .map(function (msg) {
            return String(msg);
        })
        .join(' ');

        var levelStr = Loggr.getLevelChar(lvl) + ' ';

        this.config.outStream.write(time + levelStr + namespace + message + this.config.eol);
    }
};

Loggr.prototype.info = function () {
    this._log(LEVELS.INFO, Array.prototype.slice.call(arguments));
};

Loggr.prototype.debug = function () {
    this._log(LEVELS.DEBUG, Array.prototype.slice.call(arguments));
};

Loggr.prototype.trace = function () {
    this._log(LEVELS.TRACE, Array.prototype.slice.call(arguments));
};

Loggr.getLevelChar = function (level) {
    switch (level) {
        case Loggr.LEVELS.INFO: return 'I';
        case Loggr.LEVELS.DEBUG: return 'D';
        case Loggr.LEVELS.TRACE: return 'T';
        default: return '?';
    }
};
<commit_msg>Improve Loggr<commit_after>var os = require('os');

module.exports = Loggr;

// Apache Log4j 2 levels
var LEVELS = Loggr.LEVELS = {
    OFF: 0,
    FATAL: 1,
    ERROR: 2,
    WARN: 3,
    INFO: 4,
    DEBUG: 5,
    TRACE: 6,
    ALL: Number.POSITIVE_INFINITY,
};

var STRING_LEVELS_MAP = {
    off: LEVELS.OFF,
    fatal: LEVELS.FATAL,
    error: LEVELS.ERROR,
    warn: LEVELS.WARN,
    info: LEVELS.INFO,
    debug: LEVELS.DEBUG,
    trace: LEVELS.TRACE,
    all: LEVELS.ALL,
};

var browserConsoleStream = {
    write: console.log.bind(console),
};

function Loggr(conf) {
    this._conf = Object.assign({
        logLevel: LEVELS.INFO,
        showTime: true,
        namespace: null,
        outStream: process.stdout || browserConsoleStream,
        eol: os.EOL,
    }, conf);

    if (typeof this._conf.logLevel === 'string') {
        var logLevelLower = this._conf.logLevel.toLowerCase();

        if (logLevelLower in STRING_LEVELS_MAP) {
            this._conf.logLevel = STRING_LEVELS_MAP[logLevelLower];
        }
        else {
            throw new Error('Loggr: unknown logLevel string "'+this._conf.logLevel+'"');
        }
    }
}

Loggr.prototype.fork = function (newNamespace) {
    var newConf = Object.assign({}, this._conf, {
        namespace: newNamespace,
    });

    return new Loggr(newConf);
};

Loggr.prototype._log = function (level, messages) {
    if (level <= this._conf.logLevel) {
        var time = '';
        var namespace = '';

        if (this._conf.showTime) {
            var d = new Date();
            var h = ('0' + d.getHours()).slice(-2);
            var m = ('0' + d.getMinutes()).slice(-2);
            var s = ('0' + d.getSeconds()).slice(-2);
            var ms = ('00' + d.getMilliseconds()).slice(-3);

            time = '[' + h + ':' + m + ':' + s + '.' + ms + '] ';
        }

        if (this._conf.namespace) {
            namespace = '[' + this._conf.namespace + '] ';
        }

        var message = messages
        .map(function (msg) {
            return String(msg);
        })
        .join(' ');

        var levelStr = Loggr.getLevelChar(level) + ' ';

        this._conf.outStream.write(time + levelStr + namespace + message + this._conf.eol);
    }
};

Loggr.prototype.fatal = function () {
    this._log(LEVELS.FATAL, Array.prototype.slice.call(arguments));
};

Loggr.prototype.error = function () {
    this._log(LEVELS.ERROR, Array.prototype.slice.call(arguments));
};

Loggr.prototype.warn = function () {
    this._log(LEVELS.WARN, Array.prototype.slice.call(arguments));
};

Loggr.prototype.info = function () {
    this._log(LEVELS.INFO, Array.prototype.slice.call(arguments));
};

Loggr.prototype.debug = function () {
    this._log(LEVELS.DEBUG, Array.prototype.slice.call(arguments));
};

Loggr.prototype.trace = function () {
    this._log(LEVELS.TRACE, Array.prototype.slice.call(arguments));
};

Loggr.getLevelChar = function (level) {
    switch (level) {
        case LEVELS.FATAL: return 'F';
        case LEVELS.ERROR: return 'E';
        case LEVELS.WARN: return 'W';
        case LEVELS.INFO: return 'I';
        case LEVELS.DEBUG: return 'D';
        case LEVELS.TRACE: return 'T';
        default: return '?';
    }
};
<|endoftext|>


<commit_before>/*exported mGenGenerate */

"use strict";

var mGenJsonHandler = function(builder) {
    this.builder = builder;
};

mGenJsonHandler.prototype.createObjectFromJSONString = function(data) {
    if (typeof data !== "string") throw "Create from string needs a string argument";
    var object = JSON.parse(data);
    return this.createObjectFromJSON(object);
};

mGenJsonHandler.prototype.createObjectFromJSON = function(object) {
    return new(this.builder.getClassWithId(object.__t))(object);
};

mGenJsonHandler.prototype.toJSONString = function(object) {
    return JSON.stringify(object);
};

/**
 *
 * MGEN BUILDER GENERATOR.
 *
 * This module is used to create a mgen-builder. The builder is
 * later used to instanciate classes. To create a builder simply
 * call mGenGenerate with a registry (generated by mgen-javascriptgenerator)
 *
 * @param {object} registry - registry object created by mgen-javascriptgenerator (REQUIRED).
 *
 * @param settings {object} Settings for adjusting the behavior on creation of objects (OPTIONAL).
 * @param settings.warn              {bool} Set to true if warnings should be printed in console, default is true
 * @param settings.never_catch_error {bool} Set to true if mgen never internally should catch error, this is preferable when you want to find the origin of a error instead of a pritty error. Default false
 * @param settings.validate          {bool} Set to true for type-validation of data on creation. There is a fairly big performace improvement to turn this of. Default true
 * @return a Builder object.
 */
function mGenGenerate(registry, settings) {

    settings = settings || {};
    settings = {
        warn: (typeof settings.warn === "undefined") ? true : settings.warn,
        never_catch_error: (typeof settings.never_catch_error === "undefined") ? false : settings.never_catch_error,
        validate: (typeof settings.validate === "undefined") ? true : settings.validate,
    };

    /**
     * The Builder is a class that can create a instances from the registry
     *
     * @class
     */
    var Builder = function() {};

    /**
     * Validate
     * call this method on a instance to type-validate it.
     * @param options {object} settings for this individual object (if not specified it inherits the settings from the call to mGenGenerate)
     * @return {bool} true if all fields correspond to class registry, false otherwise.
     */
    Builder.validate = function(object, options) {
        options = options || {};
        var def = {
            warn: false,
            validate: true
        };
        extend(options, def);
        extend(options, settings);

        try {
            new(Builder.getClass(registry.lookup(object.__t)))(object, options);
        } catch (e) {
            if (options.warn) {
                window.console.warn("Validation failed. Reason: \n" + e);
            }
            if (options.never_catch_error) {
                throw e;
            }
            return false;
        }
        return true;
    };

    Builder.hasClassWithId = function(typeId) {
        return registry.lookup(typeId) !== undefined;
    };

    Builder.getClassWithId = function(typeId) {
        return Builder.getClass(registry.lookup(typeId));
    };

    Builder.hasClass = function(path) {
        return registry.classRegistry[path] !== undefined || typeof Builder[path] !== undefined;
    };

    Builder.getClass = function(path) {
        return treeIndexGet(Builder, path);
    };

    // create the classes in root and at absolue path.
    for (var obj_key in registry.classRegistry) {
        if (registry.classRegistry.hasOwnProperty(obj_key)) {
            registerClass(registry.classRegistry[obj_key], obj_key);
        }
    }

    function setParent(obj) {
        if (registry.classRegistry.hasOwnProperty(obj)) {
            var C = Builder.getClass(registry.lookup(registry.classRegistry[obj].__t));
            if (C.prototype instanceof Builder) {
                return;
            }
            var super_path = getParentTypePath(registry.classRegistry[obj]);
            if (!super_path) {
                C.prototype = new Builder();
            } else {
                setParent(super_path);
                C.prototype = new(Builder.getClass(super_path))("NO_CONSTRUCT");
            }
            C.prototype.constructor = C;
        }
    }

    //lets find each super and create inheritance
    for (var obj in registry.classRegistry) {
        setParent(obj);
    }

    /* CREATION HELPER FUNCTIONS */

    function getShortName(path) {
        var a = path.split(".");
        return a[a.length - 1];
    }

    function treeIndexGet(obj, path) {
        var original_path = path;

        function recTreeIndexGet(obj, path) {
            if (typeof path == "string") {
                return recTreeIndexGet(obj, path.split("."));
            } else if (path.length === 0 || obj[path[0]] === undefined) {
                if (typeof obj !== "function") {
                    throw "Class " + original_path + " not found in registry.";
                }
                return obj;
            } else {
                return recTreeIndexGet(obj[path[0]], path.slice(1));
            }
        }
        return recTreeIndexGet(obj, path);
    }

    function treeIndexSet(obj, path, value) {
        if (typeof path == "string") {
            treeIndexSet(obj, path.split("."), value);
        } else if (path.length == 1) {
            obj[path[0]] = value;
        } else {
            obj[path[0]] = obj[path[0]] || {};
            treeIndexSet(obj[path[0]], path.slice(1), value);
        }
    }

    function registerClass(obj, path) {
        var C = createClass(obj);
        treeIndexSet(Builder, path, C);
        if (!Builder[getShortName(path)]) {
            Builder[getShortName(path)] = C;
        } else {
            var C_ = new C("NO_CONSTRUCT");
            //TODO: we have a collision. Lets create a list of all the collisions and then later turn it into a warning for the user.
            if (typeof Builder[getShortName(path)] == "function") {
                var C1 = new Builder[getShortName(path)]("NO_CONSTRUCT");
                Builder[getShortName(path)] = [getTypePath(C1), getTypePath(C_)];
            } else {
                Builder[getShortName(path)].push(getTypePath(new C_("NO_CONSTRUCT")));
            }

        }
    }

    function createClass(obj) {
        return function(data, options) {
            if (data == "NO_CONSTRUCT") {
                this.__t = obj.__t;
                return;
            }

            var default_construction = false;
            if (data == "DEFAULT") {
                default_construction = true;
                data = null;
            }

            /* Options are local settings. Inherits from the settings done when created the registry */
            options = options || {};
            extend(options, settings);

            if (data) {
                if (data.__t) {
                    var objTypeHash = getLastHash(obj.mGenTypeHash);
                    var dataTypeHash = getLastHash(data.__t);
                    //check if they data corresponds to created object.
                    if (objTypeHash != dataTypeHash) {
                        // check if data is a child to type.
                        if (isHashInList(data.__t, objTypeHash)) {
                            return new(Builder.getClass(registry.hashRegistry[dataTypeHash]))(data);
                        } else {
                            throw " Tried to create " + registry.hashRegistry[objTypeHash] + " but got " + registry.hashRegistry[dataTypeHash];
                        }
                    }
                }
                if (options.validate) {
                    //check for faulty indata.
                    for (var _key in data) {

                        if (!data.hasOwnProperty(_key)) continue;

                        if (!obj[_key] && _key != "__t") {
                            var possible = "";
                            for (var pos in obj) {
                                if (pos != "__t") possible += " \t " + pos + " \n ";
                            }
                            throw getTypePathFromHashArray(obj.mGenTypeHash) + " does not have field " + _key +
                                " \n Possible options are: \n" + possible + " \n ";
                        }
                    }
                }
            }

            //populate fields with data.
            for (var field in obj) {
                if (!obj.hasOwnProperty(field)) continue;

                if (field == "__t") {
                    this.__t = obj.__t;
                } else {
                    try {
                        if (options.validate && !default_construction) {
                            this[field] = createField(obj[field], field, data, options);
                        } else if (default_construction) {
                            this[field] = createDefaultField(obj[field], field, options);
                        } else {
                            this[field] = data ? data[field] : null;
                        }
                    } catch (err) {
                        if (options.never_catch_error) {
                            throw err;
                        } else {
                            throw "Could not create object " + registry.lookup(obj.__t) + " Reason: \n" + err;
                        }
                    }
                    if (this[field] === null) {
                        delete(this[field]);
                    }
                }
            }
        };
    }

    function createField(field, key, data, options) {
        if (hasFlag(field.flags, "required")) {
            if (!data || !data[key]) {
                throw "Missing REQUIRED value: \"" + key + "\" of type " + field.type;
            }
            return createFieldOfType(field.type, data[key], options);
        } else {
            if (data && typeof data[key] !== "undefined") {
                return createFieldOfType(field.type, data && data[key] || null, options);
            } else {
                return null;
            }
        }
    }

    function createDefaultField(field, key, options) {
        if (options.validate && hasFlag(field.flags, "required")) {
            throw "Missing REQUIRED value: \"" + key + "\" of type " + field.type;
        } else {
            return createFieldOfType(field.type, null, options);
        }
    }

    /**
     * @param type {string} - is a base type (int64 etc.) or a complex base type ( map:int32:math.Vector3 ) or a class path ( math.Vector3 ) or a class hash.
     */
    function createFieldOfType(type, value, options) {
        var classFound, baseType, t = type.split(":");

        //if we got an hash as type
        classFound = registry.lookup(t[0]);
        if (classFound) {
            t[1] = classFound;
            baseType = "object";
        }

        //if we got a complete path as type
        classFound = registry.classRegistry[t[0]];
        if (classFound) {
            t[1] = classFound;
            baseType = "object";
        }

        if (classFound === undefined) {
            baseType = t[0];
        }

        var C, ret;
        switch (baseType) {
            case "object":
                if (value && typeof value !== "object") {
                    throw "Tried to create " + type + " but had no object data.";
                }
                value = value || {};
                ret = new(Builder.getClass(t[1]))(value);
                return ret;
            case "list":
                if (value && !Array.isArray(value)) {
                    throw "Tried to create " + type + " but had no array data.";
                }
                value = value || [];
                ret = [];
                C = Builder.getClass(t[1]);
                value.forEach(function(entry) {
                    ret.push(new C(entry));
                });
                return ret;
            case "map":
                if (value && typeof value !== "object") {
                    throw "Tried to create " + type + " but had no object data.";
                }
                value = value || {};
                ret = {};
                for (var key in value) {
                    if (value.hasOwnProperty(key)) {
                        ret[createFieldOfType(t[1], key, options)] = createFieldOfType(t[2], value[key], options);
                    }
                }
                return ret;
            case "int8":
                checkInt(value, 8, type, options);
                ret = value || 0;
                return ret;
            case "int16":
                checkInt(value, 16, type, options);
                ret = value || 0;
                return ret;
            case "int32":
                checkInt(value, 32, type, options);
                ret = value || 0;
                return ret;
            case "int64":
                checkInt(value, 64, type, options);
                ret = value || 0;
                return ret;
            case "float32":
                checkFloat(value, 32, type, options);
                ret = value || 0;
                return ret;
            case "float64":
                checkFloat(value, 64, type, options);
                ret = value || 0;
                return ret;
            case "string":
                if (value && typeof value !== "string") {
                    throw "Tried to create " + type + " but had no string data.";
                }
                ret = value || "";
                return ret;
        }
    }

    function checkInt(value, size, type, options) {
        if (size > 32) {
            if (options.warn) {
                window.console.warn("mgen_js cannot handle 64 bit integers well due to javascript limitations. See https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Int64");
            }
        }

        if (typeof value === "undefined" || value === null) {
            return;
        }

        if (typeof value !== "number") {
            throw "Tried to create " + type + " but data was of type: " + (typeof value);
        }

        if (isNumeric(parseInt(value, 10)) && (parseFloat(value, 10) == parseInt(value, 10))) {
            var lim = Math.pow(2, size - 1);
            if (value > lim - 1 || value < -lim) {
                throw value + " is out of range for int" + size;
            }
            return true;
        } else {
            throw "Tried to create " + type + " but data ( " + value + " ) was not a valid integer.";
        }

    }

    function checkFloat(value, size, type) {
        if (typeof value === "undefined" || value === null) {
            return;
        }
        if (!isNumeric(value)) {
            throw "Tried to create " + type + " but data ( " + value + " ) was not a valid float.";
        }
    }

    function hasFlag(fields, flag) {
        return (fields.indexOf(flag) > -1);
    }

    function isNumeric(number) {
        // Borrowed from jQuery with comment:
        // parseFloat NaNs numeric-cast false positives (null|true|false|"")
        // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
        // subtraction forces infinities to NaN
        return number - parseFloat(number) >= 0;
    }

    function getTypePath(obj) {
        return getTypePathFromHashArray(obj.__t);
    }

    function getLastHash(hashArray) {
        return hashArray[hashArray.length - 1];
    }

    function getTypePathFromHashArray(hashArray) {
        return registry.hashRegistry[getLastHash(hashArray)];
    }

    function getParentTypePath(obj) {
        var parentHash = obj.__t.slice(0, -3);
        if (parentHash.length > 0) {
            return registry.lookup(parentHash);
        } else {
            return null;
        }
    }

    function isHashInList(hashArray, hash) {
        return hashArray.indexOf(hash) !== -1;
    }

    function extend(options, settings) {
        for (var field in settings) {
            if (!settings.hasOwnProperty(field)) continue;
            options[field] = (typeof options[field] === "undefined") ? settings[field] : options[field];
        }
    }

    return Builder;
}<commit_msg>Better comments on mgen-lib.js<commit_after>/*exported mGenGenerate */

var mGenJsonHandler = function(builder) {
    "use strict";
    this.builder = builder;
};

mGenJsonHandler.prototype.createObjectFromJSONString = function(data) {
    "use strict";
    if (typeof data !== "string") throw "Create from string needs a string argument";
    var object = JSON.parse(data);
    return this.createObjectFromJSON(object);
};

mGenJsonHandler.prototype.createObjectFromJSON = function(object) {
    "use strict";
    return new(this.builder.getClassWithId(object.__t))(object);
};

mGenJsonHandler.prototype.toJSONString = function(object) {
    "use strict";
    return JSON.stringify(object);
};

/**
 *
 * MGEN BUILDER GENERATOR.
 *
 * This module is used to create a mgen-builder. The builder is
 * later used to instanciate classes. To create a builder simply
 * call mGenGenerate with a registry (generated by mgen-javascriptgenerator)
 *
 * @param {object} registry - registry object created by mgen-javascriptgenerator (REQUIRED).
 *
 * @param settings {object} Settings for adjusting the behavior on creation of objects (OPTIONAL).
 * @param settings.warn              {bool} Set to true if warnings should be printed in console, default is true
 * @param settings.never_catch_error {bool} Set to true if mgen never internally should catch error, this is preferable when you want to find the origin of a error instead of a pritty error. Default false
 * @param settings.validate          {bool} Set to true for type-validation of data on creation. There is a fairly big performace improvement to turn this of. Default true
 * @return a Builder object.
 */
function mGenGenerate(registry, settings) {
    "use strict";
    settings = settings || {};
    settings = {
        warn: (typeof settings.warn === "undefined") ? true : settings.warn,
        never_catch_error: (typeof settings.never_catch_error === "undefined") ? false : settings.never_catch_error,
        validate: (typeof settings.validate === "undefined") ? true : settings.validate,
    };

    /**
     * The Builder is a class that can create a instances from the registry
     *
     * @class
     */
    var Builder = function() {};

    /**
     * Validate
     * call this method on a instance to type-validate it.
     * @param options {object} settings for this individual object (if not specified it inherits the settings from the call to mGenGenerate)
     * @return {bool} true if all fields correspond to class registry, false otherwise.
     */
    Builder.validate = function(object, options) {
        options = options || {};
        var def = {
            warn: false,
            validate: true
        };
        extend(options, def);
        extend(options, settings);

        try {
            new(Builder.getClass(registry.lookup(object.__t)))(object, options);
        } catch (e) {
            if (options.warn) {
                window.console.warn("Validation failed. Reason: \n" + e);
            }
            if (options.never_catch_error) {
                throw e;
            }
            return false;
        }
        return true;
    };

    /**
    * @param typeId {string} base64 hash for the class
    * @return {bool} true if the class exist in the builder, false otherwise.
    */
    Builder.hasClassWithId = function(typeId) {
        return registry.lookup(typeId) !== undefined;
    };

    /**
    * @param typeId {string} base64 hash for the class
    * @return {constructor} returns a class constructor for the specified typeid.
    */
    Builder.getClassWithId = function(typeId) {
        return Builder.getClass(registry.lookup(typeId));
    };

    /**
    * @param type path {string} the complete type path (or shorthand version) for the class, i.e "module1.module2.ClassName" or "ClassName"
    * @return {bool} true if the class exist in the builder, false otherwise.
    */
    Builder.hasClass = function(path) {
        return registry.classRegistry[path] !== undefined || typeof Builder[path] !== undefined;
    };

    /**
    * @param type path {string} the complete type path for the class, i.e "module1.module2.ClassName"
    * @return {constructor} returns a class constructor for the specified typeid.
    */
    Builder.getClass = function(path) {
        return treeIndexGet(Builder, path);
    };

    // create the classes in root and at absolue path.
    for (var obj_key in registry.classRegistry) {
        if (registry.classRegistry.hasOwnProperty(obj_key)) {
            registerClass(registry.classRegistry[obj_key], obj_key);
        }
    }

    var obj;
    //lets find each super and create inheritance
    for (obj in registry.classRegistry) {
        setParent(obj);
    }

    // The shorthand notation can create conflicts. Lets make sure we mark them as such.
    for (obj in registry.classRegistry) {
        if (registry.classRegistry.hasOwnProperty(obj_key)) {
            handleConflict(obj_key);
        }
    }
    obj = undefined;

    /* CREATION HELPER FUNCTIONS */

    function setParent(obj) {
        if (registry.classRegistry.hasOwnProperty(obj)) {
            var C = Builder.getClass(registry.lookup(registry.classRegistry[obj].__t));
            if (C.prototype instanceof Builder) {
                return;
            }
            var super_path = getParentTypePath(registry.classRegistry[obj]);
            if (!super_path) {
                C.prototype = new Builder();
            } else {
                setParent(super_path);
                C.prototype = new(Builder.getClass(super_path))("NO_CONSTRUCT");
            }
            C.prototype.constructor = C;
        }
    }

    function handleConflict(path) {
        var shortName = getShortName(path);
        var obj = Builder[shortName];
        if( Array.isArray(obj) ){ // its a conflict
            Builder[shortName]  = createConflictConstructor(obj);
        }
    }

    function createConflictConstructor(arr) {
        return function(){
            var e = "Call to conflicting constructor, please use full path istead of shorthand notation. \n";
            e = e + "Possible versions are: \n";
            for (var classPath in arr) {
                e = e + "\t" + classPath + "\n";
            }
            throw e;
        };
    }

    function getShortName(path) {
        var a = path.split(".");
        return a[a.length - 1];
    }

    function treeIndexGet(obj, path) {
        var original_path = path;

        function recTreeIndexGet(obj, path) {
            if (typeof path == "string") {
                return recTreeIndexGet(obj, path.split("."));
            } else if (path.length === 0 || obj[path[0]] === undefined) {
                if (typeof obj !== "function") {
                    throw "Class " + original_path + " not found in registry.";
                }
                return obj;
            } else {
                return recTreeIndexGet(obj[path[0]], path.slice(1));
            }
        }
        return recTreeIndexGet(obj, path);
    }

    function treeIndexSet(obj, path, value) {
        if (typeof path == "string") {
            treeIndexSet(obj, path.split("."), value);
        } else if (path.length == 1) {
            obj[path[0]] = value;
        } else {
            obj[path[0]] = obj[path[0]] || {};
            treeIndexSet(obj[path[0]], path.slice(1), value);
        }
    }

    function registerClass(obj, path) {
        var C = createClass(obj);
        treeIndexSet(Builder, path, C);
        if (!Builder[getShortName(path)]) {
            Builder[getShortName(path)] = C;
        } else {
            var C_ = new C("NO_CONSTRUCT");
            // we have a collision. Lets create a list of all the collisions and then later turn it into a warning for the user.
            if (typeof Builder[getShortName(path)] == "function") {
                //create collision list
                var C1 = new Builder[getShortName(path)]("NO_CONSTRUCT");
                Builder[getShortName(path)] = [getTypePath(C1), getTypePath(C_)];
            } else {
                // append to collision list
                Builder[getShortName(path)].push(getTypePath(new C_("NO_CONSTRUCT")));
            }
        }
    }

    function createClass(obj) {
        return function(data, options) {
            if (data == "NO_CONSTRUCT") {
                this.__t = obj.__t;
                return;
            }

            var default_construction = false;
            if (data == "DEFAULT") {
                default_construction = true;
                data = null;
            }

            /* Options are local settings. Inherits from the settings done when created the registry */
            options = options || {};
            extend(options, settings);

            if (data) {
                if (data.__t) {
                    var objTypeHash = getLastHash(obj.mGenTypeHash);
                    var dataTypeHash = getLastHash(data.__t);
                    //check if they data corresponds to created object.
                    if (objTypeHash != dataTypeHash) {
                        // check if data is a child to type.
                        if (isHashInList(data.__t, objTypeHash)) {
                            return new(Builder.getClass(registry.hashRegistry[dataTypeHash]))(data);
                        } else {
                            throw " Tried to create " + registry.hashRegistry[objTypeHash] + " but got " + registry.hashRegistry[dataTypeHash];
                        }
                    }
                }
                if (options.validate) {
                    //check for faulty indata.
                    for (var _key in data) {

                        if (!data.hasOwnProperty(_key)) continue;

                        if (!obj[_key] && _key != "__t") {
                            var possible = "";
                            for (var pos in obj) {
                                if (pos != "__t") possible += " \t " + pos + " \n ";
                            }
                            throw getTypePathFromHashArray(obj.mGenTypeHash) + " does not have field " + _key +
                                " \n Possible options are: \n" + possible + " \n ";
                        }
                    }
                }
            }

            //populate fields with data.
            for (var field in obj) {
                if (!obj.hasOwnProperty(field)) continue;

                if (field == "__t") {
                    this.__t = obj.__t;
                } else {
                    try {
                        if (options.validate && !default_construction) {
                            this[field] = createField(obj[field], field, data, options);
                        } else if (default_construction) {
                            this[field] = createDefaultField(obj[field], field, options);
                        } else {
                            this[field] = data ? data[field] : null;
                        }
                    } catch (err) {
                        if (options.never_catch_error) {
                            throw err;
                        } else {
                            throw "Could not create object " + registry.lookup(obj.__t) + " Reason: \n" + err;
                        }
                    }
                    if (this[field] === null) {
                        delete(this[field]);
                    }
                }
            }
        };
    }

    function createField(field, key, data, options) {
        if (hasFlag(field.flags, "required")) {
            if (!data || !data[key]) {
                throw "Missing REQUIRED value: \"" + key + "\" of type " + field.type;
            }
            return createFieldOfType(field.type, data[key], options);
        } else {
            if (data && typeof data[key] !== "undefined") {
                return createFieldOfType(field.type, data && data[key] || null, options);
            } else {
                return null;
            }
        }
    }

    function createDefaultField(field, key, options) {
        if (options.validate && hasFlag(field.flags, "required")) {
            throw "Missing REQUIRED value: \"" + key + "\" of type " + field.type;
        } else {
            return createFieldOfType(field.type, null, options);
        }
    }

    /**
     * @param type {string} - is a base type (int64 etc.) or a complex base type ( map:int32:math.Vector3 ) or a class path ( math.Vector3 ) or a class hash.
     */
    function createFieldOfType(type, value, options) {
        var classFound, baseType, t = type.split(":");

        //if we got an hash as type
        classFound = registry.lookup(t[0]);
        if (classFound) {
            t[1] = classFound;
            baseType = "object";
        }

        //if we got a complete path as type
        classFound = registry.classRegistry[t[0]];
        if (classFound) {
            t[1] = classFound;
            baseType = "object";
        }

        if (classFound === undefined) {
            baseType = t[0];
        }

        var C, ret;
        switch (baseType) {
            case "object":
                if (value && typeof value !== "object") {
                    throw "Tried to create " + type + " but had no object data.";
                }
                value = value || {};
                ret = new(Builder.getClass(t[1]))(value);
                return ret;
            case "list":
                if (value && !Array.isArray(value)) {
                    throw "Tried to create " + type + " but had no array data.";
                }
                value = value || [];
                ret = [];
                C = Builder.getClass(t[1]);
                value.forEach(function(entry) {
                    ret.push(new C(entry));
                });
                return ret;
            case "map":
                if (value && typeof value !== "object") {
                    throw "Tried to create " + type + " but had no object data.";
                }
                value = value || {};
                ret = {};
                for (var key in value) {
                    if (value.hasOwnProperty(key)) {
                        ret[createFieldOfType(t[1], key, options)] = createFieldOfType(t[2], value[key], options);
                    }
                }
                return ret;
            case "int8":
                checkInt(value, 8, type, options);
                ret = value || 0;
                return ret;
            case "int16":
                checkInt(value, 16, type, options);
                ret = value || 0;
                return ret;
            case "int32":
                checkInt(value, 32, type, options);
                ret = value || 0;
                return ret;
            case "int64":
                checkInt(value, 64, type, options);
                ret = value || 0;
                return ret;
            case "float32":
                checkFloat(value, 32, type, options);
                ret = value || 0;
                return ret;
            case "float64":
                checkFloat(value, 64, type, options);
                ret = value || 0;
                return ret;
            case "string":
                if (value && typeof value !== "string") {
                    throw "Tried to create " + type + " but had no string data.";
                }
                ret = value || "";
                return ret;
        }
    }

    function checkInt(value, size, type, options) {
        if (size > 32) {
            if (options.warn) {
                window.console.warn("mgen_js cannot handle 64 bit integers well due to javascript limitations. See https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Int64");
            }
        }

        if (typeof value === "undefined" || value === null) {
            return;
        }

        if (typeof value !== "number") {
            throw "Tried to create " + type + " but data was of type: " + (typeof value);
        }

        if (isNumeric(parseInt(value, 10)) && (parseFloat(value, 10) == parseInt(value, 10))) {
            var lim = Math.pow(2, size - 1);
            if (value > lim - 1 || value < -lim) {
                throw value + " is out of range for int" + size;
            }
            return true;
        } else {
            throw "Tried to create " + type + " but data ( " + value + " ) was not a valid integer.";
        }

    }

    function checkFloat(value, size, type) {
        if (typeof value === "undefined" || value === null) {
            return;
        }
        if (!isNumeric(value)) {
            throw "Tried to create " + type + " but data ( " + value + " ) was not a valid float.";
        }
    }

    function hasFlag(fields, flag) {
        return (fields.indexOf(flag) > -1);
    }

    function isNumeric(number) {
        // Borrowed from jQuery with comment:
        // parseFloat NaNs numeric-cast false positives (null|true|false|"")
        // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
        // subtraction forces infinities to NaN
        return number - parseFloat(number) >= 0;
    }

    function getTypePath(obj) {
        return getTypePathFromHashArray(obj.__t);
    }

    function getLastHash(hashArray) {
        return hashArray[hashArray.length - 1];
    }

    function getTypePathFromHashArray(hashArray) {
        //TODO: Fixme?
        return registry.hashRegistry[getLastHash(hashArray)];
    }

    function getParentTypePath(obj) {
        var parentHash = obj.__t.slice(0, -3);
        if (parentHash.length > 0) {
            return registry.lookup(parentHash);
        } else {
            return null;
        }
    }

    function isHashInList(hashArray, hash) {
        return hashArray.indexOf(hash) !== -1;
    }

    function extend(options, settings) {
        for (var field in settings) {
            if (!settings.hasOwnProperty(field)) continue;
            options[field] = (typeof options[field] === "undefined") ? settings[field] : options[field];
        }
    }

    return Builder;
}<|endoftext|>


<commit_before>export const defaultChatSubject = 'Introduce yourself!';
export const rewardValue = {
  star: 200
};
import { Color } from './css';

export const clientVersion = '0.1.87';

export const charLimit = {
  chat: {
    subject: 200,
    message: 5000
  },
  comment: 10000,
  playlist: {
    title: 200,
    description: 5000
  },
  videoQuestion: {
    title: 2000,
    choice: 2000
  },
  subject: {
    title: 300,
    description: 5000
  },
  rewardComment: 5000,
  statusMsg: 500,
  url: {
    title: 300,
    description: 20000,
    url: 1000
  },
  video: {
    title: 200,
    description: 10000,
    url: 300
  }
};
export const profileThemes = {
  black: {
    color: Color.black(),
    cover: Color.black()
  },
  logoBlue: {
    color: Color.logoBlue(),
    cover: Color.logoBlue()
  },
  green: {
    color: Color.green(),
    cover: Color.green()
  },
  orange: {
    color: Color.orange(),
    cover: Color.orange()
  },
  pink: {
    color: Color.pink(),
    cover: Color.pink()
  },
  rose: {
    color: Color.rose(),
    cover: Color.rose()
  }
};
export const returnMaxStars = ({ difficulty }) => {
  let maxStars = 5;
  if (difficulty > 0) {
    maxStars = 10 * difficulty;
  }
  return maxStars;
};
<commit_msg>version up<commit_after>export const defaultChatSubject = 'Introduce yourself!';
export const rewardValue = {
  star: 200
};
import { Color } from './css';

export const clientVersion = '0.1.88';

export const charLimit = {
  chat: {
    subject: 200,
    message: 5000
  },
  comment: 10000,
  playlist: {
    title: 200,
    description: 5000
  },
  videoQuestion: {
    title: 2000,
    choice: 2000
  },
  subject: {
    title: 300,
    description: 5000
  },
  rewardComment: 5000,
  statusMsg: 500,
  url: {
    title: 300,
    description: 20000,
    url: 1000
  },
  video: {
    title: 200,
    description: 10000,
    url: 300
  }
};
export const profileThemes = {
  black: {
    color: Color.black(),
    cover: Color.black()
  },
  logoBlue: {
    color: Color.logoBlue(),
    cover: Color.logoBlue()
  },
  green: {
    color: Color.green(),
    cover: Color.green()
  },
  orange: {
    color: Color.orange(),
    cover: Color.orange()
  },
  pink: {
    color: Color.pink(),
    cover: Color.pink()
  },
  rose: {
    color: Color.rose(),
    cover: Color.rose()
  }
};
export const returnMaxStars = ({ difficulty }) => {
  let maxStars = 5;
  if (difficulty > 0) {
    maxStars = 10 * difficulty;
  }
  return maxStars;
};
<|endoftext|>


<commit_before>/*
 * @author: Qennix
 * Jan 24th, 2011
 */

//Keyboard Events
new Ext.KeyMap(document, [
  {
  key: Ext.EventObject.F5,
    fn: function(keycode, e) {
      if (! e.ctrlKey) {
      if (Ext.isIE) {
        // IE6 doesn't allow cancellation of the F5 key, so trick it into
        // thinking some other key was pressed (backspace in this case)
        e.browserEvent.keyCode = 8;
      }
      e.stopEvent();
      document.location = document.location;
      }else{
      Ext.Msg.alert('Refresh', 'You clicked: CTRL-F5');
      }
   }
},
{
  key: Ext.EventObject.DELETE,
  fn: function(k,e){
    iGrid = Ext.getCmp('infoGrid');
    rowSelected = iGrid.getSelectionModel().getSelected();
    if (rowSelected){
      DeleteUserAction();
    }
  }
}
]);

var store;
var cmodel;
var infoGrid;
var viewport;
var smodel;
var newButton;
var editButton;
var deleteButton;
var summaryButton;
var groupsButton;
//var reassignButton;
var authenticationButton;
var searchButton;
var searchText;
var contextMenu;
var user_admin = '00000000000000000000000000000001';
var pageSize;
var fullNameFormat;
var dateFormat;
var comboAuthSources;
var storeAuthSources;

Ext.onReady(function(){
  Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
  Ext.QuickTips.init();

  fullNameFormat = CONFIG.fullNameFormat;
  dateFormat = CONFIG.dateFormat;
  pageSize = parseInt(CONFIG.pageSize);

  newButton = new Ext.Action({
    text: _('ID_NEW'),
     iconCls: 'button_menu_ext ss_sprite  ss_add',
     handler: NewUserAction
  });

  summaryButton = new Ext.Action({
    text: _('ID_SUMMARY'),
     iconCls: 'button_menu_ext ss_sprite  ss_table',
     handler: SummaryTabOpen,
    disabled: true
  });

  editButton = new Ext.Action({
    text: _('ID_EDIT'),
     iconCls: 'button_menu_ext ss_sprite  ss_pencil',
     handler: EditUserAction,
     disabled: true
  });

  deleteButton = new Ext.Action({
    text: _('ID_DELETE'),
     iconCls: 'button_menu_ext ss_sprite  ss_delete',
     handler: DeleteUserAction,
     disabled: true
  });

  groupsButton = new Ext.Action({
     text: _('ID_GROUPS'),
     iconCls: 'button_menu_ext ss_sprite ss_group_add',
     handler: UsersGroupPage,
     disabled: true
  });

//    reassignButton = new Ext.Action({
//      text: _('ID_REASSIGN_CASES'),
//      iconCls: 'button_menu_ext ss_sprite ss_arrow_rotate_clockwise',
//      handler: DoNothing,
//      disabled: true
//    });

  authenticationButton = new Ext.Action({
     text: _('ID_AUTHENTICATION'),
    iconCls: 'button_menu_ext ss_sprite ss_key',
     handler: AuthUserPage,
     disabled: true
  });

  searchButton = new Ext.Action({
    text: _('ID_SEARCH'),
    handler: DoSearch
  });

  contextMenu = new Ext.menu.Menu({
    items: [editButton, deleteButton,'-',groupsButton,'-',authenticationButton,'-',summaryButton]
  });

  searchText = new Ext.form.TextField ({
    id: 'searchTxt',
    ctCls:'pm_search_text_field',
    allowBlank: true,
    width: 100,
    emptyText: _('ID_ENTER_SEARCH_TERM'),//'enter search term',
    listeners: {
      specialkey: function(f,e){
        if (e.getKey() == e.ENTER) {
          DoSearch();
        }
      },
      focus: function(f,e) {
        var row = infoGrid.getSelectionModel().getSelected();
         infoGrid.getSelectionModel().deselectRow(infoGrid.getStore().indexOf(row));
      }
    }
  });

  clearTextButton = new Ext.Action({
    text: 'X',
     ctCls:'pm_search_x_button',
     handler: GridByDefault
  });

  smodel = new Ext.grid.RowSelectionModel({
    singleSelect: true,
     listeners:{
       rowselect: function(sm){
      editButton.enable();
      deleteButton.enable();
        groupsButton.enable();
        //reassignButton.enable();
        authenticationButton.enable();
        summaryButton.enable();
      },
      rowdeselect: function(sm){
        editButton.disable();
      deleteButton.disable();
      groupsButton.disable();
      //reassignButton.disable();
      authenticationButton.disable();
      summaryButton.disable();
      }
    }
  });

  store = new Ext.data.GroupingStore( {
    proxy : new Ext.data.HttpProxy({
      url: 'users_Ajax?function=usersList'
    }),
    reader : new Ext.data.JsonReader( {
      root: 'users',
      totalProperty: 'total_users',
      fields : [
        {name : 'USR_UID'},
      {name : 'USR_USERNAME'},
      {name : 'USR_FIRSTNAME'},
      {name : 'USR_LASTNAME'},
      {name : 'USR_EMAIL'},
      {name : 'USR_ROLE'},
      {name : 'USR_DUE_DATE'},
      {name : 'DEP_TITLE'},
      {name : 'LAST_LOGIN'},
      {name : 'USR_STATUS'},
      {name : 'TOTAL_CASES'},
      {name : 'DUE_DATE_OK'},
      {name : 'USR_AUTH_SOURCE'}
      ]
    })
  });

  storePageSize = new Ext.data.SimpleStore({
    fields: ['size'],
     data: [['20'],['30'],['40'],['50'],['100']],
     autoLoad: true
  });

  comboPageSize = new Ext.form.ComboBox({
    typeAhead     : false,
    mode          : 'local',
    triggerAction : 'all',
    store: storePageSize,
    valueField: 'size',
    displayField: 'size',
    width: 50,
    editable: false,
    listeners:{
      select: function(c,d,i){
        UpdatePageConfig(d.data['size']);
        bbarpaging.pageSize = parseInt(d.data['size']);
        bbarpaging.moveFirst();
      }
    }
  });

  comboPageSize.setValue(pageSize);

  storeAuthSources = new Ext.data.GroupingStore({
    autoLoad: true,
    proxy : new Ext.data.HttpProxy({
      url: 'users_Ajax?function=authSources&cmb=yes'
    }),
    reader : new Ext.data.JsonReader( {
      root: 'sources',
      fields: [
        {name: 'AUTH_SOURCE_UID'},
        {name: 'AUTH_SOURCE_SHOW'}
      ]
    })
  });

  comboAuthSources = new Ext.form.ComboBox({
    mode: 'local',
    triggerAction: 'all',
    store: storeAuthSources,
    valueField: 'AUTH_SOURCE_UID',
    displayField: 'AUTH_SOURCE_SHOW',
    //emptyText: 'All',
    width: 160,
    editable: false,
    value: _('ID_ALL'),
    listeners:{
      select: function(c,d,i){
        store.setBaseParam('auths',d.data['AUTH_SOURCE_UID']);
        UpdateAuthSource(d.data['AUTH_SOURCE_UID']);
      }
    }
  });

  bbarpaging = new Ext.PagingToolbar({
    pageSize: pageSize,
     store: store,
     displayInfo: true,
     displayMsg: _('ID_GRID_PAGE_DISPLAYING_USERS_MESSAGE') + '    ',
     emptyMsg: _('ID_GRID_PAGE_NO_USERS_MESSAGE'),
     items: ['-',_('ID_PAGE_SIZE')+':',comboPageSize]
  });

  cmodel = new Ext.grid.ColumnModel({
    defaults: {
      width: 50,
      sortable: true
    },
    columns: [
      {id:'USR_UID', dataIndex: 'USR_UID', hidden:true, hideable:false},
      //{header: '', dataIndex: 'USR_UID', width: 30, align:'center', sortable: false, renderer: photo_user},
      {header: _('ID_USER_NAME'), dataIndex: 'USR_USERNAME', width: 90, hidden:false, align:'left'},
      {header: _('ID_FULL_NAME'), dataIndex: 'USR_USERNAME', width: 175, align:'left', renderer: full_name},
      {header: _('ID_EMAIL'), dataIndex: 'USR_EMAIL', width: 120, hidden: true, align: 'left'},
      {header: _('ID_STATUS'), dataIndex: 'USR_STATUS', width: 50, hidden: false, align: 'center', renderer: render_status},
      {header: _('ID_ROLE'), dataIndex: 'USR_ROLE', width: 180, hidden:false, align:'left'},
      {header: _('ID_DEPARTMENT'), dataIndex: 'DEP_TITLE', width: 150, hidden:true, align:'left'},
      {header: _('ID_LAST_LOGIN'), dataIndex: 'LAST_LOGIN', width: 108, hidden:false, align:'center', renderer: render_lastlogin},
      {header: _('ID_AUTHENTICATION_SOURCE'), dataIndex: 'USR_AUTH_SOURCE', width: 108, hidden: true, align: 'left'},
      {header: _('ID_CASES'), dataIndex: 'TOTAL_CASES', width: 45, hidden:false, align:'right'},
      {header: _('ID_DUE_DATE'), dataIndex: 'USR_DUE_DATE', width: 108, hidden:false, align:'center', renderer: render_duedate}
    ]
  });

  infoGrid = new Ext.grid.GridPanel({
    region: 'center',
     layout: 'fit',
     id: 'infoGrid',
    height:100,
     autoWidth : true,
     stateful : true,
     stateId : 'grid',
     enableColumnResize: true,
     enableHdMenu: true,
     frame:false,
     columnLines: false,
     viewConfig: {
      forceFit:true
    },
    title : _('ID_USERS'),
    store: store,
    cm: cmodel,
    sm: smodel,
    tbar: [newButton, '-',summaryButton,'-', editButton, deleteButton,/*'-',groupsButton,'-',authenticationButton,*/  {xtype: 'tbfill'},_('ID_AUTH_SOURCES')+': ',comboAuthSources,'-', searchText,clearTextButton,searchButton],
    bbar: bbarpaging,
    listeners: {
      rowdblclick: SummaryTabOpen
    },
    view: new Ext.grid.GroupingView({
      forceFit:true,
      groupTextTpl: '{text}'
    })
  });

  infoGrid.on('rowcontextmenu',
    function (grid, rowIndex, evt) {
      var sm = grid.getSelectionModel();
      sm.selectRow(rowIndex, sm.isSelected(rowIndex));
    },
    this
  );

  infoGrid.on('contextmenu',
    function (evt) {
      evt.preventDefault();
    },
    this
  );

  infoGrid.addListener('rowcontextmenu',onMessageContextMenu,this);

  infoGrid.store.load();

  viewport = new Ext.Viewport({
     layout: 'fit',
     autoScroll: false,
     items: [infoGrid]
  });
});

//Function Handles Context Menu Opening
onMessageContextMenu = function (grid, rowIndex, e) {
  e.stopEvent();
  var coords = e.getXY();
  contextMenu.showAt([coords[0], coords[1]]);
};

//Do Nothing Function
DoNothing = function(){};

//Open New User Form
NewUserAction = function(){
  location.href = 'users_New';
};

//Delete User Action
DeleteUserAction = function(){
  var uid = infoGrid.getSelectionModel().getSelected();
  if (uid){
  if (uid.data.USR_UID==user_admin){
    Ext.Msg.alert(_('ID_USERS'), _('ID_CANNOT_DELETE_ADMIN_USER'));
  }else{
    viewport.getEl().mask(_('ID_PROCESSING'));
    Ext.Ajax.request({
    url: 'users_Ajax',
    params: {'function': 'canDeleteUser', uUID: uid.data.USR_UID},
    success: function(res, opt){
      viewport.getEl().unmask();
      response = Ext.util.JSON.decode(res.responseText);
      if (response.candelete){
      if (response.hashistory){
        Ext.Msg.confirm(_('ID_CONFIRM'), _('ID_USERS_DELETE_WITH_HISTORY'),
        function(btn){
          if (btn=='yes') DeleteUser(uid.data.USR_UID);
        }
        );
      }else{
        Ext.Msg.confirm(_('ID_CONFIRM'), _('ID_MSG_CONFIRM_DELETE_USER'),
        function(btn){
          if (btn=='yes') DeleteUser(uid.data.USR_UID);
          }
        );
        }
      }else{
      PMExt.error(_('ID_USERS'), _('ID_MSG_CANNOT_DELETE_USER'));
      }
    },
    failure: function(r,o){
      viewport.getEl().unmask();
      DoNothing();
    }
    });
  }
  }
};

//Open User-Groups Manager
UsersGroupPage = function(value){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=group';
  }
};

//Open Summary Tab
SummaryTabOpen = function(){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=summary';
  }
};

//Edit User Action
EditUserAction = function(){
  var uid = infoGrid.getSelectionModel().getSelected();
  if (uid){
  location.href = 'users_Edit?USR_UID=' + uid.data.USR_UID;
  }
};

//Open Authentication-User Manager
AuthUserPage = function(value){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=auth';;
  }
};

////Renderer Active/Inactive Role
//photo_user = function(value){
//  return '';
//};

//Render Full Name
full_name = function(v,x,s){
  return _FNF(v, s.data.USR_FIRSTNAME, s.data.USR_LASTNAME);
};

//Render Status
render_status = function(v){
  switch(v){
  case 'ACTIVE': return '' + _('ID_ACTIVE') + ''; break;
  case 'INACTIVE': return '' + _('ID_INACTIVE') + '';; break;
  case 'VACATION': return '' + _('ID_VACATION') + '';; break;
  }
};

//Render Due Date
render_duedate = function(v,x,s){
  if (s.data.DUE_DATE_OK)
    return _DF(v);
  else
    return '' + _DF(v) + '';
};

render_lastlogin = function(v){
	return _DF(v);
};

//Load Grid By Default
GridByDefault = function(){
  searchText.reset();
  infoGrid.store.load();
};

//Do Search Function
DoSearch = function(){
  infoGrid.store.load({params: {textFilter: searchText.getValue()}});
};

//Delete User Function
DeleteUser = function(uid){
  Ext.Ajax.request({
  url: 'users_Ajax',
  params: {'function': 'deleteUser', USR_UID: uid},
  success: function(res, opt){
    DoSearch();
    PMExt.notify(_('ID_USERS'),_('ID_USERS_SUCCESS_DELETE'));
  },
  failure: DoNothing
  });
};

//Update Page Size Configuration
UpdatePageConfig = function(pageSize){
  Ext.Ajax.request({
  url: 'users_Ajax',
  params: {'function':'updatePageSize', size: pageSize}
  });
};

//Update Authentication Source Filter
UpdateAuthSource = function(index){
  searchText.reset();
  infoGrid.store.load({params: {auths: index}});
};<commit_msg>BUG 7386 Order by as number int<commit_after>/*
 * @author: Qennix
 * Jan 24th, 2011
 */

//Keyboard Events
new Ext.KeyMap(document, [
  {
  key: Ext.EventObject.F5,
    fn: function(keycode, e) {
      if (! e.ctrlKey) {
      if (Ext.isIE) {
        // IE6 doesn't allow cancellation of the F5 key, so trick it into
        // thinking some other key was pressed (backspace in this case)
        e.browserEvent.keyCode = 8;
      }
      e.stopEvent();
      document.location = document.location;
      }else{
      Ext.Msg.alert('Refresh', 'You clicked: CTRL-F5');
      }
   }
},
{
  key: Ext.EventObject.DELETE,
  fn: function(k,e){
    iGrid = Ext.getCmp('infoGrid');
    rowSelected = iGrid.getSelectionModel().getSelected();
    if (rowSelected){
      DeleteUserAction();
    }
  }
}
]);

var store;
var cmodel;
var infoGrid;
var viewport;
var smodel;
var newButton;
var editButton;
var deleteButton;
var summaryButton;
var groupsButton;
//var reassignButton;
var authenticationButton;
var searchButton;
var searchText;
var contextMenu;
var user_admin = '00000000000000000000000000000001';
var pageSize;
var fullNameFormat;
var dateFormat;
var comboAuthSources;
var storeAuthSources;

Ext.onReady(function(){
  Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
  Ext.QuickTips.init();

  fullNameFormat = CONFIG.fullNameFormat;
  dateFormat = CONFIG.dateFormat;
  pageSize = parseInt(CONFIG.pageSize);

  newButton = new Ext.Action({
    text: _('ID_NEW'),
     iconCls: 'button_menu_ext ss_sprite  ss_add',
     handler: NewUserAction
  });

  summaryButton = new Ext.Action({
    text: _('ID_SUMMARY'),
     iconCls: 'button_menu_ext ss_sprite  ss_table',
     handler: SummaryTabOpen,
    disabled: true
  });

  editButton = new Ext.Action({
    text: _('ID_EDIT'),
     iconCls: 'button_menu_ext ss_sprite  ss_pencil',
     handler: EditUserAction,
     disabled: true
  });

  deleteButton = new Ext.Action({
    text: _('ID_DELETE'),
     iconCls: 'button_menu_ext ss_sprite  ss_delete',
     handler: DeleteUserAction,
     disabled: true
  });

  groupsButton = new Ext.Action({
     text: _('ID_GROUPS'),
     iconCls: 'button_menu_ext ss_sprite ss_group_add',
     handler: UsersGroupPage,
     disabled: true
  });

//    reassignButton = new Ext.Action({
//      text: _('ID_REASSIGN_CASES'),
//      iconCls: 'button_menu_ext ss_sprite ss_arrow_rotate_clockwise',
//      handler: DoNothing,
//      disabled: true
//    });

  authenticationButton = new Ext.Action({
     text: _('ID_AUTHENTICATION'),
    iconCls: 'button_menu_ext ss_sprite ss_key',
     handler: AuthUserPage,
     disabled: true
  });

  searchButton = new Ext.Action({
    text: _('ID_SEARCH'),
    handler: DoSearch
  });

  contextMenu = new Ext.menu.Menu({
    items: [editButton, deleteButton,'-',groupsButton,'-',authenticationButton,'-',summaryButton]
  });

  searchText = new Ext.form.TextField ({
    id: 'searchTxt',
    ctCls:'pm_search_text_field',
    allowBlank: true,
    width: 100,
    emptyText: _('ID_ENTER_SEARCH_TERM'),//'enter search term',
    listeners: {
      specialkey: function(f,e){
        if (e.getKey() == e.ENTER) {
          DoSearch();
        }
      },
      focus: function(f,e) {
        var row = infoGrid.getSelectionModel().getSelected();
         infoGrid.getSelectionModel().deselectRow(infoGrid.getStore().indexOf(row));
      }
    }
  });

  clearTextButton = new Ext.Action({
    text: 'X',
     ctCls:'pm_search_x_button',
     handler: GridByDefault
  });

  smodel = new Ext.grid.RowSelectionModel({
    singleSelect: true,
     listeners:{
       rowselect: function(sm){
      editButton.enable();
      deleteButton.enable();
        groupsButton.enable();
        //reassignButton.enable();
        authenticationButton.enable();
        summaryButton.enable();
      },
      rowdeselect: function(sm){
        editButton.disable();
      deleteButton.disable();
      groupsButton.disable();
      //reassignButton.disable();
      authenticationButton.disable();
      summaryButton.disable();
      }
    }
  });

  store = new Ext.data.GroupingStore( {
    proxy : new Ext.data.HttpProxy({
      url: 'users_Ajax?function=usersList'
    }),
    reader : new Ext.data.JsonReader( {
      root: 'users',
      totalProperty: 'total_users',
      fields : [
        {name : 'USR_UID'},
      {name : 'USR_USERNAME'},
      {name : 'USR_FIRSTNAME'},
      {name : 'USR_LASTNAME'},
      {name : 'USR_EMAIL'},
      {name : 'USR_ROLE'},
      {name : 'USR_DUE_DATE'},
      {name : 'DEP_TITLE'},
      {name : 'LAST_LOGIN'},
      {name : 'USR_STATUS'},
      {name : 'TOTAL_CASES',type:'int'},
      {name : 'DUE_DATE_OK'},
      {name : 'USR_AUTH_SOURCE'}
      ]
    })
  });

  storePageSize = new Ext.data.SimpleStore({
    fields: ['size'],
     data: [['20'],['30'],['40'],['50'],['100']],
     autoLoad: true
  });

  comboPageSize = new Ext.form.ComboBox({
    typeAhead     : false,
    mode          : 'local',
    triggerAction : 'all',
    store: storePageSize,
    valueField: 'size',
    displayField: 'size',
    width: 50,
    editable: false,
    listeners:{
      select: function(c,d,i){
        UpdatePageConfig(d.data['size']);
        bbarpaging.pageSize = parseInt(d.data['size']);
        bbarpaging.moveFirst();
      }
    }
  });

  comboPageSize.setValue(pageSize);

  storeAuthSources = new Ext.data.GroupingStore({
    autoLoad: true,
    proxy : new Ext.data.HttpProxy({
      url: 'users_Ajax?function=authSources&cmb=yes'
    }),
    reader : new Ext.data.JsonReader( {
      root: 'sources',
      fields: [
        {name: 'AUTH_SOURCE_UID'},
        {name: 'AUTH_SOURCE_SHOW'}
      ]
    })
  });

  comboAuthSources = new Ext.form.ComboBox({
    mode: 'local',
    triggerAction: 'all',
    store: storeAuthSources,
    valueField: 'AUTH_SOURCE_UID',
    displayField: 'AUTH_SOURCE_SHOW',
    //emptyText: 'All',
    width: 160,
    editable: false,
    value: _('ID_ALL'),
    listeners:{
      select: function(c,d,i){
        store.setBaseParam('auths',d.data['AUTH_SOURCE_UID']);
        UpdateAuthSource(d.data['AUTH_SOURCE_UID']);
      }
    }
  });

  bbarpaging = new Ext.PagingToolbar({
    pageSize: pageSize,
     store: store,
     displayInfo: true,
     displayMsg: _('ID_GRID_PAGE_DISPLAYING_USERS_MESSAGE') + '    ',
     emptyMsg: _('ID_GRID_PAGE_NO_USERS_MESSAGE'),
     items: ['-',_('ID_PAGE_SIZE')+':',comboPageSize]
  });

  cmodel = new Ext.grid.ColumnModel({
    defaults: {
      width: 50,
      sortable: true
    },
    columns: [
      {id:'USR_UID', dataIndex: 'USR_UID', hidden:true, hideable:false},
      //{header: '', dataIndex: 'USR_UID', width: 30, align:'center', sortable: false, renderer: photo_user},
      {header: _('ID_USER_NAME'), dataIndex: 'USR_USERNAME', width: 90, hidden:false, align:'left'},
      {header: _('ID_FULL_NAME'), dataIndex: 'USR_USERNAME', width: 175, align:'left', renderer: full_name},
      {header: _('ID_EMAIL'), dataIndex: 'USR_EMAIL', width: 120, hidden: true, align: 'left'},
      {header: _('ID_STATUS'), dataIndex: 'USR_STATUS', width: 50, hidden: false, align: 'center', renderer: render_status},
      {header: _('ID_ROLE'), dataIndex: 'USR_ROLE', width: 180, hidden:false, align:'left'},
      {header: _('ID_DEPARTMENT'), dataIndex: 'DEP_TITLE', width: 150, hidden:true, align:'left'},
      {header: _('ID_LAST_LOGIN'), dataIndex: 'LAST_LOGIN', width: 108, hidden:false, align:'center', renderer: render_lastlogin},
      {header: _('ID_AUTHENTICATION_SOURCE'), dataIndex: 'USR_AUTH_SOURCE', width: 108, hidden: true, align: 'left'},
      {header: _('ID_CASES'), dataIndex: 'TOTAL_CASES', width: 45, hidden:false, align:'right', sortable: true ,sortType: 'asInt'},
      {header: _('ID_DUE_DATE'), dataIndex: 'USR_DUE_DATE', width: 108, hidden:false, align:'center', renderer: render_duedate}
    ]
  });

  infoGrid = new Ext.grid.GridPanel({
    region: 'center',
     layout: 'fit',
     id: 'infoGrid',
    height:100,
     autoWidth : true,
     stateful : true,
     stateId : 'grid',
     enableColumnResize: true,
     enableHdMenu: true,
     frame:false,
     columnLines: false,
     viewConfig: {
      forceFit:true
    },
    title : _('ID_USERS'),
    store: store,
    cm: cmodel,
    sm: smodel,
    tbar: [newButton, '-',summaryButton,'-', editButton, deleteButton,/*'-',groupsButton,'-',authenticationButton,*/  {xtype: 'tbfill'},_('ID_AUTH_SOURCES')+': ',comboAuthSources,'-', searchText,clearTextButton,searchButton],
    bbar: bbarpaging,
    listeners: {
      rowdblclick: SummaryTabOpen
    },
    view: new Ext.grid.GroupingView({
      forceFit:true,
      groupTextTpl: '{text}'
    })
  });

  infoGrid.on('rowcontextmenu',
    function (grid, rowIndex, evt) {
      var sm = grid.getSelectionModel();
      sm.selectRow(rowIndex, sm.isSelected(rowIndex));
    },
    this
  );

  infoGrid.on('contextmenu',
    function (evt) {
      evt.preventDefault();
    },
    this
  );

  infoGrid.addListener('rowcontextmenu',onMessageContextMenu,this);

  infoGrid.store.load();

  viewport = new Ext.Viewport({
     layout: 'fit',
     autoScroll: false,
     items: [infoGrid]
  });
});

//Function Handles Context Menu Opening
onMessageContextMenu = function (grid, rowIndex, e) {
  e.stopEvent();
  var coords = e.getXY();
  contextMenu.showAt([coords[0], coords[1]]);
};

//Do Nothing Function
DoNothing = function(){};

//Open New User Form
NewUserAction = function(){
  location.href = 'users_New';
};

//Delete User Action
DeleteUserAction = function(){
  var uid = infoGrid.getSelectionModel().getSelected();
  if (uid){
  if (uid.data.USR_UID==user_admin){
    Ext.Msg.alert(_('ID_USERS'), _('ID_CANNOT_DELETE_ADMIN_USER'));
  }else{
    viewport.getEl().mask(_('ID_PROCESSING'));
    Ext.Ajax.request({
    url: 'users_Ajax',
    params: {'function': 'canDeleteUser', uUID: uid.data.USR_UID},
    success: function(res, opt){
      viewport.getEl().unmask();
      response = Ext.util.JSON.decode(res.responseText);
      if (response.candelete){
      if (response.hashistory){
        Ext.Msg.confirm(_('ID_CONFIRM'), _('ID_USERS_DELETE_WITH_HISTORY'),
        function(btn){
          if (btn=='yes') DeleteUser(uid.data.USR_UID);
        }
        );
      }else{
        Ext.Msg.confirm(_('ID_CONFIRM'), _('ID_MSG_CONFIRM_DELETE_USER'),
        function(btn){
          if (btn=='yes') DeleteUser(uid.data.USR_UID);
          }
        );
        }
      }else{
      PMExt.error(_('ID_USERS'), _('ID_MSG_CANNOT_DELETE_USER'));
      }
    },
    failure: function(r,o){
      viewport.getEl().unmask();
      DoNothing();
    }
    });
  }
  }
};

//Open User-Groups Manager
UsersGroupPage = function(value){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=group';
  }
};

//Open Summary Tab
SummaryTabOpen = function(){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=summary';
  }
};

//Edit User Action
EditUserAction = function(){
  var uid = infoGrid.getSelectionModel().getSelected();
  if (uid){
  location.href = 'users_Edit?USR_UID=' + uid.data.USR_UID;
  }
};

//Open Authentication-User Manager
AuthUserPage = function(value){
  rowSelected = infoGrid.getSelectionModel().getSelected();
  if (rowSelected){
  value = rowSelected.data.USR_UID;
  location.href = 'usersGroups?uUID=' + value + '&type=auth';;
  }
};

////Renderer Active/Inactive Role
//photo_user = function(value){
//  return '';
//};

//Render Full Name
full_name = function(v,x,s){
  return _FNF(v, s.data.USR_FIRSTNAME, s.data.USR_LASTNAME);
};

//Render Status
render_status = function(v){
  switch(v){
  case 'ACTIVE': return '' + _('ID_ACTIVE') + ''; break;
  case 'INACTIVE': return '' + _('ID_INACTIVE') + '';; break;
  case 'VACATION': return '' + _('ID_VACATION') + '';; break;
  }
};

//Render Due Date
render_duedate = function(v,x,s){
  if (s.data.DUE_DATE_OK)
    return _DF(v);
  else
    return '' + _DF(v) + '';
};

render_lastlogin = function(v){
	return _DF(v);
};

//Load Grid By Default
GridByDefault = function(){
  searchText.reset();
  infoGrid.store.load();
};

//Do Search Function
DoSearch = function(){
  infoGrid.store.load({params: {textFilter: searchText.getValue()}});
};

//Delete User Function
DeleteUser = function(uid){
  Ext.Ajax.request({
  url: 'users_Ajax',
  params: {'function': 'deleteUser', USR_UID: uid},
  success: function(res, opt){
    DoSearch();
    PMExt.notify(_('ID_USERS'),_('ID_USERS_SUCCESS_DELETE'));
  },
  failure: DoNothing
  });
};

//Update Page Size Configuration
UpdatePageConfig = function(pageSize){
  Ext.Ajax.request({
  url: 'users_Ajax',
  params: {'function':'updatePageSize', size: pageSize}
  });
};

//Update Authentication Source Filter
UpdateAuthSource = function(index){
  searchText.reset();
  infoGrid.store.load({params: {auths: index}});
};<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');

  var ModuleUnit = function(props) {
    this.module = props.module;
    this.port = props.port;
  };

  ModuleUnit.prototype.equal = function(other) {
    return Object.keys(this).every(function(key) {
      return helper.equal(this[key], other[key]);
    }.bind(this));
  };

  ModuleUnit.prototype.portType = function() {
    return this.port.type();
  };

  ModuleUnit.prototype.circuitElementMember = function() {
    return this.module.circuitElementMember(this.port.name());
  };

  ModuleUnit.prototype.plugPosition = function() {
    return this.module.plugPosition(this.port);
  };

  ModuleUnit.prototype.socketPosition = function() {
    return this.module.socketPosition(this.port);
  };

  ModuleUnit.prototype.addRelation = function(relation) {
    this.module.relations().push(relation);
    this.port.relations().push(relation);
  };

  ModuleUnit.prototype.removeRelation = function(relation) {
    helper.remove(this.module.relations(), relation);
    helper.remove(this.port.relations(), relation);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleUnit;
  else
    app.ModuleUnit = ModuleUnit;
})(this.app || (this.app = {}));
<commit_msg>Add method to get/set 'socketConnected' property of a port in module-unit<commit_after>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');

  var ModuleUnit = function(props) {
    this.module = props.module;
    this.port = props.port;
  };

  ModuleUnit.prototype.equal = function(other) {
    return Object.keys(this).every(function(key) {
      return helper.equal(this[key], other[key]);
    }.bind(this));
  };

  ModuleUnit.prototype.portType = function() {
    return this.port.type();
  };

  ModuleUnit.prototype.portSocketConnected = function(value) {
    return this.port.socketConnected(value);
  };

  ModuleUnit.prototype.circuitElementMember = function() {
    return this.module.circuitElementMember(this.port.name());
  };

  ModuleUnit.prototype.plugPosition = function() {
    return this.module.plugPosition(this.port);
  };

  ModuleUnit.prototype.socketPosition = function() {
    return this.module.socketPosition(this.port);
  };

  ModuleUnit.prototype.addRelation = function(relation) {
    this.module.relations().push(relation);
    this.port.relations().push(relation);
  };

  ModuleUnit.prototype.removeRelation = function(relation) {
    helper.remove(this.module.relations(), relation);
    helper.remove(this.port.relations(), relation);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleUnit;
  else
    app.ModuleUnit = ModuleUnit;
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>const webpack = require('webpack')
const { resolve, join } = require('path')
const config = require('./config')
const env = require('./env-utils')
const projectRoot = resolve(__dirname, '../')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')

const styleLoaders = [
  env.prod ? MiniCssExtractPlugin.loader : 'style-loader',
  {
    loader: 'css-loader',
    options: { importLoaders: 1 },
  },
  {
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: loader => [
        require('autoprefixer')(),
      ],
    },
  },
]

module.exports = {
  mode: env.prod ? 'production' : 'development',
  devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
  entry: {
    app: './src/main.js',
  },
  output: {
    path: resolve(__dirname, '../dist'),
    publicPath: env.prod ? '' : '/',
    filename: 'assets/js/[name].[hash].js',
    chunkFilename: 'assets/js/[id].[chunkhash].js',
    pathinfo: false,
  },
  resolve: {
    extensions: [
      '.mat.js', // for use inside quasar
      '.js',
      '.vue',
      '.json',
    ],
    modules: [
      resolve('src'),
      resolve('node_modules'),
    ],
    alias: {
      quasar: 'quasar-framework',
      'quasar-vue-plugin': 'quasar-framework/src/vue-plugin',
      '@': resolve(__dirname, '../src'),
      '>': resolve(__dirname, '../test'),
      variables: resolve(__dirname, '../src/themes/quasar.variables.styl'),
      slidetoggle: resolve(__dirname, '../src/themes/karrot.slidetoggle.styl'),
      editbox: resolve(__dirname, '../src/themes/karrot.editbox.styl'),
    },
    symlinks: false,
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(vue|js)$/,
        loader: 'eslint-loader',
        include: projectRoot,
        exclude: /node_modules/,
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [
          join(projectRoot, 'src'),
          /quasar\//,
        ],
      },
      {
        test: /\.vue$/,
        exclude: /(node_modules)/,
        use: 'vue-loader',
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'img/[name].[hash:7].[ext]',
        },
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'fonts/[name].[hash:7].[ext]',
        },
      },
      {
        test: /\.css$/,
        use: styleLoaders,
      },
      {
        test: /\.(stylus|styl)$/,
        use: [
          ...styleLoaders,
          'stylus-loader',
        ],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config[env.prod ? 'build' : 'dev'].env,
      'DEV': env.dev,
      'PROD': env.prod,
      'CORDOVA': env.cordova,
      'BACKEND': '"' + config.backend + '"',
      'KARROT_THEME': '"' + env.karrotTheme + '"',
      'FCM_SENDER_ID': '"' + env.fcmSenderId + '"',
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'src/index.html',
      minify: true,
    }),
    new VueLoaderPlugin(),
    ...(env.prod ? [
      new MiniCssExtractPlugin({
        filename: '[contenthash].css',
      }),
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        reportFilename: 'bundlesize.html',
        defaultSizes: 'gzip',
        openAnalyzer: false,
        generateStatsFile: false,
        statsFilename: 'stats.json',
        statsOptions: null,
        logLevel: 'info',
      }),
    ] : []),
    new HardSourceWebpackPlugin(),
  ],
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        sourceMap: env.prod,
        cache: true,
        parallel: true,
        uglifyOptions: {
          mangle: true,
        },
      }),
      new OptimizeCSSAssetsPlugin({}),
    ],
    splitChunks: {
      chunks: 'all',
      minChunks: 2,
      name: !env.prod,
    },
    runtimeChunk: 'single',
  },
}
<commit_msg>Build webpack assets into /assets (#1075)<commit_after>const webpack = require('webpack')
const { resolve, join } = require('path')
const config = require('./config')
const env = require('./env-utils')
const projectRoot = resolve(__dirname, '../')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')

const styleLoaders = [
  env.prod ? MiniCssExtractPlugin.loader : 'style-loader',
  {
    loader: 'css-loader',
    options: { importLoaders: 1 },
  },
  {
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: loader => [
        require('autoprefixer')(),
      ],
    },
  },
]

module.exports = {
  mode: env.prod ? 'production' : 'development',
  devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
  entry: {
    app: './src/main.js',
  },
  output: {
    path: resolve(__dirname, '../dist'),
    publicPath: env.prod ? '' : '/',
    filename: 'assets/js/[name].[hash].js',
    chunkFilename: 'assets/js/[id].[chunkhash].js',
    pathinfo: false,
  },
  resolve: {
    extensions: [
      '.mat.js', // for use inside quasar
      '.js',
      '.vue',
      '.json',
    ],
    modules: [
      resolve('src'),
      resolve('node_modules'),
    ],
    alias: {
      quasar: 'quasar-framework',
      'quasar-vue-plugin': 'quasar-framework/src/vue-plugin',
      '@': resolve(__dirname, '../src'),
      '>': resolve(__dirname, '../test'),
      variables: resolve(__dirname, '../src/themes/quasar.variables.styl'),
      slidetoggle: resolve(__dirname, '../src/themes/karrot.slidetoggle.styl'),
      editbox: resolve(__dirname, '../src/themes/karrot.editbox.styl'),
    },
    symlinks: false,
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(vue|js)$/,
        loader: 'eslint-loader',
        include: projectRoot,
        exclude: /node_modules/,
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [
          join(projectRoot, 'src'),
          /quasar\//,
        ],
      },
      {
        test: /\.vue$/,
        exclude: /(node_modules)/,
        use: 'vue-loader',
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: (env.prod ? '/' : '') + 'assets/images/[name].[hash:7].[ext]',
        },
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: (env.prod ? '/' : '') + 'assets/fonts/[name].[hash:7].[ext]',
        },
      },
      {
        test: /\.css$/,
        use: styleLoaders,
      },
      {
        test: /\.(stylus|styl)$/,
        use: [
          ...styleLoaders,
          'stylus-loader',
        ],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config[env.prod ? 'build' : 'dev'].env,
      'DEV': env.dev,
      'PROD': env.prod,
      'CORDOVA': env.cordova,
      'BACKEND': '"' + config.backend + '"',
      'KARROT_THEME': '"' + env.karrotTheme + '"',
      'FCM_SENDER_ID': '"' + env.fcmSenderId + '"',
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'src/index.html',
      minify: true,
    }),
    new VueLoaderPlugin(),
    ...(env.prod ? [
      new MiniCssExtractPlugin({
        filename: 'assets/css/[contenthash].css',
      }),
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        reportFilename: 'bundlesize.html',
        defaultSizes: 'gzip',
        openAnalyzer: false,
        generateStatsFile: false,
        statsFilename: 'stats.json',
        statsOptions: null,
        logLevel: 'info',
      }),
    ] : []),
    new HardSourceWebpackPlugin(),
  ],
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        sourceMap: env.prod,
        cache: true,
        parallel: true,
        uglifyOptions: {
          mangle: true,
        },
      }),
      new OptimizeCSSAssetsPlugin({}),
    ],
    splitChunks: {
      chunks: 'all',
      minChunks: 2,
      name: !env.prod,
    },
    runtimeChunk: 'single',
  },
}
<|endoftext|>