<commit_before>(function ($, rho, rhoUtil) {
    'use strict';

    // === Rho.NewORM wrapper members ===
    Rho.NewORM.addModel = function(modelname, modeldef){
        var model = new Rho.NewORMModel(modelname);
        modeldef(model);
        model.initModel();
        return model;
    };
    Rho.NewORM.getModel = function(modelname){
        return Rho.NewORMModel.getModel(modelname);
    };

    // === Rho.NewORMModel wrapper members ===
    Rho.NewORMModel.prototype._normalize_complex_conditions = function(conditions, op){
        console.log("MZV_DEBUG : _normalize_complex_conditions : " + JSON.stringify(conditions) + ", " + op);
        if(!conditions){
            return ['', []];
        };
        op = op || 'AND';
        if(Object.prototype.toString.call(conditions) === '[object Array]') {
            var quests = new Array();
            var sqlRes = '';
            for (var item in conditions) {
                if (sqlRes.length > 0) {
                    sqlRes += ' ' + op + ' ';
                };
                if(item.hasOwnProperty('conditions')) {
                    var subCond = this._normalize_complex_conditions(item.conditions, item.op);
                }
                else {
                    var subCond = this._normalize_hash_condition(item, 'AND');
                }
                sqlRes += '(' + subCond[0] + ')';
                quests = quests.concat(subCond[1]);
            }
            return [sqlRes, quests];
        }
        else {
            return this._normalize_hash_condition(conditions, op);
        };
    };

    Rho.NewORMModel.prototype._normalize_hash_condition = function(item, op){
        // Hash condition can be of two forms:
        // 1) {'key1':'value'1, 'key2':'value2' ... }, 'op':'OP1' => translates into : key1=value1 OP1 key2=value2
        // 2) or full form { 'op':'OP1', 'func':'FUNC1', 'attrib':'key1', 'value(s)':'value1' } => translates into FUNC1(key1) OP1 value1
        if(item.hasOwnProperty('attrib')) {
            var itemOp = "=";
            var itemFunc = "";
            var itemName = "";
            var itemValues = "";
            for (var propName in item) {
                switch (propName) {
                case 'op'  :
                    itemOp = item[propName];
                    break;
                case 'func':
                    itemFunc = item[propName];
                    break;
                case 'attrib':
                    itemName = item[propName];
                    break;
                case 'value':
                case 'values':
                    itemValues = item[propName];
                    break;
                };
            };
            if(itemValues instanceof String){
                itemValues = [itemValues];
            };

            subCond = this.buildComplexWhereCond(itemName, itemValues, itemOp, itemFunc);
            return [subCond[0], subCond.slice(1)];
        }
        else {
            console.log("MZV_DEBUG : _normalize_hash_conditions : " + JSON.stringify(item) + ", " + op);
            var sqlRes = "";
            var condQuests = new Array();
            for (var propName in item) {
                console.log("MZV_DEBUG : _breaking cond : " + propName + ", " + item[propName]);
                var subCond = this.buildComplexWhereCond(propName, [item[propName]], "=", '');
                console.log("MZV_DEBUG : _received back : " + JSON.stringify(subCond) + ", " + subCond[0] + ", " + JSON.stringify(subCond.slice(1)));
                if(sqlRes.length > 0) {
                    sqlRes += " " + op + " ";
                };
                sqlRes += subCond[0];
                condQuests = condQuests.concat(subCond.slice(1));
                console.log("MZV_DEBUG : _should be concat : " + sqlRes + ", " + JSON.stringify(condQuests));
            };
            console.log("MZV_DEBUG : _and in the end we have : " + sqlRes + ", " + JSON.stringify(condQuests));
            return [sqlRes, condQuests];
        };
    };

    Rho.NewORMModel.prototype._normalize_conditions = function(what, conditions, op){
        console.log("MZV_DEBUG : make_conditions : " + what + ", " + JSON.stringify(conditions) + ", " + op);
        if (!op) {
            var retV;
            if(!conditions) {
                retV = this.buildSimpleWhereCond(what, []);
                return [retV[0], retV.slice(1)];
            }
            else if(Object.prototype.toString.call(conditions) === '[object String]') {
                retV = this.buildSimpleWhereCond(what, [conditions]);
                return [retV[0], retV.slice(1)];
            }
            else if(Object.prototype.toString.call(conditions) === '[object Array]') {
                retV = this.buildSimpleWhereCond(what, conditions);
                return [retV[0], retV.slice(1)];
            } else {
                return this._normalize_complex_conditions(conditions, 'AND');
            };
        };
        return this._normalize_complex_conditions(conditions, op);
    };

    Rho.NewORMModel.prototype._normalize_args_for_find = function(what, options, normalized_string_args, normalized_vector_args){
        // 1) Normalize LIMITS
        var limitArgs = this.buildFindLimits(what, options);
        for (var property in limitArgs) {
            normalized_string_args[property] = limitArgs[property];
        }

        // 2) Normalize ORDER BY
        var order_dir = options.orderdir || [];
        var order_attr = options.order || [];
        if(Object.prototype.toString.call(order_dir) === '[object String]'){
            order_dir = [order_dir];
        };
        if(Object.prototype.toString.call(order_attr) === '[object String]'){
            order_attr = [order_attr];
        };
        normalized_vector_args.order = this.buildFindOrder(order_attr, order_dir);

        // 3) Normalize SELECT
        var select_arr = options.select || [];
        if(Object.prototype.toString.call(options.conditions) === '[object String]') {
            select_arr = [select_arr];
        };
        normalized_vector_args.select = select_arr;

        // 4) Build Where Conditions
        var condVal = this._normalize_conditions(what, options.conditions, options.op);
        console.log(" we have here : " + condVal[0] + ", " + JSON.stringify(condVal[1]));
        normalized_string_args.conditions = condVal[0] || "";
        normalized_vector_args.quests = condVal[1] || [];
    };

    Rho.NewORMModel.prototype.find = function(what, options){
        what = what || 'all';
        options = options || {};
        var _found;
        // first - check for Hash conditions PropertyBag
        if(this.fixed_schema) {
            var normalized_vector_args = {};
            var normalized_string_args = {};
            console.log("we have here fixed schema options as " + JSON.stringify(options));
            this._normalize_args_for_find(what, options, normalized_string_args, normalized_vector_args);
            console.log("we have here options before find as " + what + ", " + JSON.stringify(normalized_string_args) + ", " + JSON.stringify(normalized_vector_args));
            _found = this.findObjects(what, normalized_string_args,
                                    normalized_vector_args['quests'],
                                    normalized_vector_args['select'],
                                    normalized_vector_args['order']);
        } else { // property bag
            // only LIMIT is supported
            normalized_string_args = {};
            var limitArgs = this.buildFindLimits(what, options);
            for (var property in limitArgs) {
                normalized_string_args[property] = limitArgs[property];
            }
            // 3) Normalize SELECT
            var select_arr = options.select || [];
            if(Object.prototype.toString.call(options.conditions) === '[object String]') {
                select_arr = [select_arr];
            };
            normalized_string_args['op'] = options.op || 'AND';
            if(Object.prototype.toString.call(options.conditions) === '[object Object]'){
                _found = this.findObjectsPropertyBagByCondHash(what, options.conditions, normalized_string_args, select_arr);
            } else { // the only other supported case is simple string (WHERE sql) or array (WHERE sql + quests)
                options.conditions = options.conditions || [""];
                options.quests = [];
                if(Object.prototype.toString.call(options.conditions) === '[object Array]') {
                    options.quests = options.conditions.slice(1);
                    options.conditions = options.conditions[0];
                };
                console.log("we are here and " + what + ", " + JSON.stringify(options.conditions) + ", " + JSON.stringify(options.quests));
                _found = this.findObjectsPropertyBagByCondArray(what, options.conditions, options.quests, normalized_string_args, select_arr);
            };
        };

        console.log("we are here in find result and " + JSON.stringify(_found) + ", " + JSON.stringify(_found[0]));

        switch (what) {
            case 'all'  : return this._wrapORMInstances(_found);
            case 'count': return _found ;
            case 'first':
            default     : return this._wrapORMInstance(_found[0]);
        };
    };

    Rho.NewORMModel.prototype.findBySql = function(sqlQuery){
        var _found = this.find_by_sql(sqlQuery);
        return this._wrapORMInstances(_found);
    };

    Rho.NewORMModel.prototype.paginate = function(options){
        options['page'] = options['page'] || 0;
        options['per_page'] = options['per_page'] || 10;
        options['offset'] = options['page'] * options['per_page'];
        return find('all', options);
    };

    Rho.NewORMModel.prototype.delete_all = function(options){
        console.log("we are in before 2 delete_all");
        var conditions = options || {};
        options = {};
        options.conditions = conditions;

        if(this.fixed_schema) {
            console.log("we are in before 3 fixed_schema");
            var normalized_vector_args = {};
            var normalized_string_args = {};
            this._normalize_args_for_find("all", options, normalized_string_args, normalized_vector_args);
            console.log("we are in before 3.1 fixed_schema" + options + ", " + JSON.stringify(normalized_string_args) + JSON.stringify(normalized_vector_args));
            return this.deleteObjects(normalized_string_args,
                                      normalized_vector_args['quests']);
        } else { // property bag
            normalized_string_args = {};
            console.log("we are in before 2.1 propbag");
            var limitArgs = this.buildFindLimits("all", options);
            console.log("we are in before 2.2 propbag");
            for (var property in limitArgs) {
                normalized_string_args[property] = limitArgs[property];
            }
            normalized_string_args.op = options.op || 'AND';
            if(Object.prototype.toString.call(options.conditions) === '[object Object]'){
                console.log("we are in before 3 propbag " + options.conditions);
                return this.deleteObjectsPropertyBagByCondHash(options.conditions, normalized_string_args);
            } else { // the only other supported case is simple string (WHERE sql) or array (WHERE sql + quests)
                console.log("we are in before 4 propbag");
                conditions = options.conditions || [""];
                quests = [];
                if(Object.prototype.toString.call(options.conditions) === '[object Array]') {
                    quests = options.conditions.slice(1);
                    conditions = options.conditions[0];
                };
                console.log("we are here and " + JSON.stringify(conditions) + ", " + JSON.stringify(quests));
                return this.deleteObjectsPropertyBagByCondArray(conditions, quests, normalized_string_args);
            };
        };
    };
    Rho.NewORMModel.prototype.deleteAll = function(options){
        console.log("we are in before 1 deleteAll")
        return this.delete_all(options);
    };
    Rho.NewORMModel.prototype._wrapORMInstance = function(objInst){
        if(!objInst) {
            return undefined;
        }
        var _new_instance = new _ORMObjectInstance(this, objInst);
        return _new_instance;
    };
    Rho.NewORMModel.prototype._wrapORMInstances = function(_objects){
        var _model_instances = [];
        for (var i = 0; i < _objects.length; i++) {
            var _object_instance = new _ORMObjectInstance(this, _objects[i]);
            _model_instances.push(_object_instance);
        };
        return _model_instances;
    };
    Rho.NewORMModel.prototype.make = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createInstance(objHash));
        return _new_instance;
    };
    Rho.NewORMModel.prototype.count = function(){
        return this.getCount();
    };
    Rho.NewORMModel.prototype.create = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createObject(objHash));
        return _new_instance;
    };

    // === Rho.NewORMModel Object's wrapper methods ===
    var _ORMObjectInstance = function(model, obj){
        for (var attrname in obj) { this[attrname] = obj[attrname]; }
        this.source_id = model.source_id

        Object.defineProperty(this, '_klass_model', {
            value: function () {
                return model;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'vars', {
            value: function () {
                var objAttrs = {};
                for (var attrname in this) { objAttrs[attrname] = this[attrname]; }
                return objAttrs;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'get', {
            value: function (propname) {
                return this[propname];
            },
            enumerable: false
        });
        Object.defineProperty(this, 'has', {
            value: function (propname) {
                return this.hasOwnProperty(propname);
            },
            enumerable: false
        });
        Object.defineProperty(this, 'set', {
            value: function (propname, value) {
                this[propname] = value;
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'updateAttributes', {
            value: function (newAttrs) {
                var updatedAttrs = this._klass_model().updateObject(this.object, this, newAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                console.log("and after update we have : " + JSON.stringify(this));
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'save', {
            value: function () {
                var updatedAttrs = this._klass_model().saveObject(this.object, this);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'destroy', {
            value: function () {
                this._klass_model().deleteObject(this.object);
                return this;
            },
            enumerable: false
        });
    };

    Rho.NewORM.dbPartitions = {};
    Rho.NewORM.dbConnection = function (partition){
        //look for db connection, if not found create one
        var filepath = Rho.Application.databaseFilePath(partition);
        var partitions = Rho.NewORM.getDbPartitions();
        var db;
        if(partitions && partitions[partition]){
            db = partitions[partition];
        }
        else{
            db = new Rho.Database(filepath, partition);
            partitions[partition] = db;
        }
        return db;
    };
    Rho.NewORM.getDbPartitions = function() {
        return Rho.NewORM.dbPartitions;
    };
    Rho.NewORM.clear = function(){
        Rho.NewORMModel.clear();
    };

    // Global initialization
    console.log("Replacing Old Rho.ORM with new one!!!");
    Rho.ORM = Rho.NewORM;
    Rho.ORMHelper = Rho.NewORM;
    Rho.ORMModel = Rho.NewORMModel;
    Rho.ORM.dbConnection('local');
    Rho.ORM.dbConnection('user');
    Rho.ORM.dbConnection('app');

})(Rho.jQuery, Rho, Rho.util);

<commit_msg>Partial fix to paginate method<commit_after>(function ($, rho, rhoUtil) {
    'use strict';

    // === Rho.NewORM wrapper members ===
    Rho.NewORM.addModel = function(modelname, modeldef){
        var model = new Rho.NewORMModel(modelname);
        modeldef(model);
        model.initModel();
        return model;
    };
    Rho.NewORM.getModel = function(modelname){
        return Rho.NewORMModel.getModel(modelname);
    };

    // === Rho.NewORMModel wrapper members ===
    Rho.NewORMModel.prototype._normalize_complex_conditions = function(conditions, op){
        console.log("MZV_DEBUG : _normalize_complex_conditions : " + JSON.stringify(conditions) + ", " + op);
        if(!conditions){
            return ['', []];
        };
        op = op || 'AND';
        if(Object.prototype.toString.call(conditions) === '[object Array]') {
            var quests = new Array();
            var sqlRes = '';
            for (var item in conditions) {
                if (sqlRes.length > 0) {
                    sqlRes += ' ' + op + ' ';
                };
                if(item.hasOwnProperty('conditions')) {
                    var subCond = this._normalize_complex_conditions(item.conditions, item.op);
                }
                else {
                    var subCond = this._normalize_hash_condition(item, 'AND');
                }
                sqlRes += '(' + subCond[0] + ')';
                quests = quests.concat(subCond[1]);
            }
            return [sqlRes, quests];
        }
        else {
            return this._normalize_hash_condition(conditions, op);
        };
    };

    Rho.NewORMModel.prototype._normalize_hash_condition = function(item, op){
        // Hash condition can be of two forms:
        // 1) {'key1':'value'1, 'key2':'value2' ... }, 'op':'OP1' => translates into : key1=value1 OP1 key2=value2
        // 2) or full form { 'op':'OP1', 'func':'FUNC1', 'attrib':'key1', 'value(s)':'value1' } => translates into FUNC1(key1) OP1 value1
        if(item.hasOwnProperty('attrib')) {
            var itemOp = "=";
            var itemFunc = "";
            var itemName = "";
            var itemValues = "";
            for (var propName in item) {
                switch (propName) {
                case 'op'  :
                    itemOp = item[propName];
                    break;
                case 'func':
                    itemFunc = item[propName];
                    break;
                case 'attrib':
                    itemName = item[propName];
                    break;
                case 'value':
                case 'values':
                    itemValues = item[propName];
                    break;
                };
            };
            if(itemValues instanceof String){
                itemValues = [itemValues];
            };

            subCond = this.buildComplexWhereCond(itemName, itemValues, itemOp, itemFunc);
            return [subCond[0], subCond.slice(1)];
        }
        else {
            console.log("MZV_DEBUG : _normalize_hash_conditions : " + JSON.stringify(item) + ", " + op);
            var sqlRes = "";
            var condQuests = new Array();
            for (var propName in item) {
                console.log("MZV_DEBUG : _breaking cond : " + propName + ", " + item[propName]);
                var subCond = this.buildComplexWhereCond(propName, [item[propName]], "=", '');
                console.log("MZV_DEBUG : _received back : " + JSON.stringify(subCond) + ", " + subCond[0] + ", " + JSON.stringify(subCond.slice(1)));
                if(sqlRes.length > 0) {
                    sqlRes += " " + op + " ";
                };
                sqlRes += subCond[0];
                condQuests = condQuests.concat(subCond.slice(1));
                console.log("MZV_DEBUG : _should be concat : " + sqlRes + ", " + JSON.stringify(condQuests));
            };
            console.log("MZV_DEBUG : _and in the end we have : " + sqlRes + ", " + JSON.stringify(condQuests));
            return [sqlRes, condQuests];
        };
    };

    Rho.NewORMModel.prototype._normalize_conditions = function(what, conditions, op){
        console.log("MZV_DEBUG : make_conditions : " + what + ", " + JSON.stringify(conditions) + ", " + op);
        if (!op) {
            var retV;
            if(!conditions) {
                retV = this.buildSimpleWhereCond(what, []);
                return [retV[0], retV.slice(1)];
            }
            else if(Object.prototype.toString.call(conditions) === '[object String]') {
                retV = this.buildSimpleWhereCond(what, [conditions]);
                return [retV[0], retV.slice(1)];
            }
            else if(Object.prototype.toString.call(conditions) === '[object Array]') {
                retV = this.buildSimpleWhereCond(what, conditions);
                return [retV[0], retV.slice(1)];
            } else {
                return this._normalize_complex_conditions(conditions, 'AND');
            };
        };
        return this._normalize_complex_conditions(conditions, op);
    };

    Rho.NewORMModel.prototype._normalize_args_for_find = function(what, options, normalized_string_args, normalized_vector_args){
        // 1) Normalize LIMITS
        var limitArgs = this.buildFindLimits(what, options);
        for (var property in limitArgs) {
            normalized_string_args[property] = limitArgs[property];
        }

        // 2) Normalize ORDER BY
        var order_dir = options.orderdir || [];
        var order_attr = options.order || [];
        if(Object.prototype.toString.call(order_dir) === '[object String]'){
            order_dir = [order_dir];
        };
        if(Object.prototype.toString.call(order_attr) === '[object String]'){
            order_attr = [order_attr];
        };
        normalized_vector_args.order = this.buildFindOrder(order_attr, order_dir);

        // 3) Normalize SELECT
        var select_arr = options.select || [];
        if(Object.prototype.toString.call(options.conditions) === '[object String]') {
            select_arr = [select_arr];
        };
        normalized_vector_args.select = select_arr;

        // 4) Build Where Conditions
        var condVal = this._normalize_conditions(what, options.conditions, options.op);
        console.log(" we have here : " + condVal[0] + ", " + JSON.stringify(condVal[1]));
        normalized_string_args.conditions = condVal[0] || "";
        normalized_vector_args.quests = condVal[1] || [];
    };

    Rho.NewORMModel.prototype.find = function(what, options){
        what = what || 'all';
        options = options || {};
        var _found;
        // first - check for Hash conditions PropertyBag
        if(this.fixed_schema) {
            var normalized_vector_args = {};
            var normalized_string_args = {};
            console.log("we have here fixed schema options as " + JSON.stringify(options));
            this._normalize_args_for_find(what, options, normalized_string_args, normalized_vector_args);
            console.log("we have here options before find as " + what + ", " + JSON.stringify(normalized_string_args) + ", " + JSON.stringify(normalized_vector_args));
            _found = this.findObjects(what, normalized_string_args,
                                    normalized_vector_args['quests'],
                                    normalized_vector_args['select'],
                                    normalized_vector_args['order']);
        } else { // property bag
            // only LIMIT is supported
            normalized_string_args = {};
            var limitArgs = this.buildFindLimits(what, options);
            for (var property in limitArgs) {
                normalized_string_args[property] = limitArgs[property];
            }
            // 3) Normalize SELECT
            var select_arr = options.select || [];
            if(Object.prototype.toString.call(options.conditions) === '[object String]') {
                select_arr = [select_arr];
            };
            normalized_string_args['op'] = options.op || 'AND';
            if(Object.prototype.toString.call(options.conditions) === '[object Object]'){
                _found = this.findObjectsPropertyBagByCondHash(what, options.conditions, normalized_string_args, select_arr);
            } else { // the only other supported case is simple string (WHERE sql) or array (WHERE sql + quests)
                options.conditions = options.conditions || [""];
                options.quests = [];
                if(Object.prototype.toString.call(options.conditions) === '[object Array]') {
                    options.quests = options.conditions.slice(1);
                    options.conditions = options.conditions[0];
                };
                console.log("we are here and " + what + ", " + JSON.stringify(options.conditions) + ", " + JSON.stringify(options.quests));
                _found = this.findObjectsPropertyBagByCondArray(what, options.conditions, options.quests, normalized_string_args, select_arr);
            };
        };

        console.log("we are here in find result and " + JSON.stringify(_found) + ", " + JSON.stringify(_found[0]));

        switch (what) {
            case 'all'  : return this._wrapORMInstances(_found);
            case 'count': return _found ;
            case 'first':
            default     : return this._wrapORMInstance(_found[0]);
        };
    };

    Rho.NewORMModel.prototype.findBySql = function(sqlQuery){
        var _found = this.find_by_sql(sqlQuery);
        return this._wrapORMInstances(_found);
    };

    Rho.NewORMModel.prototype.paginate = function(options){
        options['page'] = options['page'] || 0;
        options['per_page'] = options['per_page'] || 10;
        options['offset'] = options['page'] * options['per_page'];
        // FIXME: translate options['per_page'] / options['offset'] to
        // LIMIT options['per_page'] OFFSET options['offset'] or
        // LIMIT options['offset'],options['per_page'] clause
        return this.find('all', options);
    };

    Rho.NewORMModel.prototype.delete_all = function(options){
        console.log("we are in before 2 delete_all");
        var conditions = options || {};
        options = {};
        options.conditions = conditions;

        if(this.fixed_schema) {
            console.log("we are in before 3 fixed_schema");
            var normalized_vector_args = {};
            var normalized_string_args = {};
            this._normalize_args_for_find("all", options, normalized_string_args, normalized_vector_args);
            console.log("we are in before 3.1 fixed_schema" + options + ", " + JSON.stringify(normalized_string_args) + JSON.stringify(normalized_vector_args));
            return this.deleteObjects(normalized_string_args,
                                      normalized_vector_args['quests']);
        } else { // property bag
            normalized_string_args = {};
            console.log("we are in before 2.1 propbag");
            var limitArgs = this.buildFindLimits("all", options);
            console.log("we are in before 2.2 propbag");
            for (var property in limitArgs) {
                normalized_string_args[property] = limitArgs[property];
            }
            normalized_string_args.op = options.op || 'AND';
            if(Object.prototype.toString.call(options.conditions) === '[object Object]'){
                console.log("we are in before 3 propbag " + options.conditions);
                return this.deleteObjectsPropertyBagByCondHash(options.conditions, normalized_string_args);
            } else { // the only other supported case is simple string (WHERE sql) or array (WHERE sql + quests)
                console.log("we are in before 4 propbag");
                conditions = options.conditions || [""];
                quests = [];
                if(Object.prototype.toString.call(options.conditions) === '[object Array]') {
                    quests = options.conditions.slice(1);
                    conditions = options.conditions[0];
                };
                console.log("we are here and " + JSON.stringify(conditions) + ", " + JSON.stringify(quests));
                return this.deleteObjectsPropertyBagByCondArray(conditions, quests, normalized_string_args);
            };
        };
    };
    Rho.NewORMModel.prototype.deleteAll = function(options){
        console.log("we are in before 1 deleteAll")
        return this.delete_all(options);
    };
    Rho.NewORMModel.prototype._wrapORMInstance = function(objInst){
        if(!objInst) {
            return undefined;
        }
        var _new_instance = new _ORMObjectInstance(this, objInst);
        return _new_instance;
    };
    Rho.NewORMModel.prototype._wrapORMInstances = function(_objects){
        var _model_instances = [];
        for (var i = 0; i < _objects.length; i++) {
            var _object_instance = new _ORMObjectInstance(this, _objects[i]);
            _model_instances.push(_object_instance);
        };
        return _model_instances;
    };
    Rho.NewORMModel.prototype.make = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createInstance(objHash));
        return _new_instance;
    };
    Rho.NewORMModel.prototype.count = function(){
        return this.getCount();
    };
    Rho.NewORMModel.prototype.create = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createObject(objHash));
        return _new_instance;
    };

    // === Rho.NewORMModel Object's wrapper methods ===
    var _ORMObjectInstance = function(model, obj){
        for (var attrname in obj) { this[attrname] = obj[attrname]; }
        this.source_id = model.source_id

        Object.defineProperty(this, '_klass_model', {
            value: function () {
                return model;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'vars', {
            value: function () {
                var objAttrs = {};
                for (var attrname in this) { objAttrs[attrname] = this[attrname]; }
                return objAttrs;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'get', {
            value: function (propname) {
                return this[propname];
            },
            enumerable: false
        });
        Object.defineProperty(this, 'has', {
            value: function (propname) {
                return this.hasOwnProperty(propname);
            },
            enumerable: false
        });
        Object.defineProperty(this, 'set', {
            value: function (propname, value) {
                this[propname] = value;
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'updateAttributes', {
            value: function (newAttrs) {
                var updatedAttrs = this._klass_model().updateObject(this.object, this, newAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                console.log("and after update we have : " + JSON.stringify(this));
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'save', {
            value: function () {
                var updatedAttrs = this._klass_model().saveObject(this.object, this);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'destroy', {
            value: function () {
                this._klass_model().deleteObject(this.object);
                return this;
            },
            enumerable: false
        });
    };

    Rho.NewORM.dbPartitions = {};
    Rho.NewORM.dbConnection = function (partition){
        //look for db connection, if not found create one
        var filepath = Rho.Application.databaseFilePath(partition);
        var partitions = Rho.NewORM.getDbPartitions();
        var db;
        if(partitions && partitions[partition]){
            db = partitions[partition];
        }
        else{
            db = new Rho.Database(filepath, partition);
            partitions[partition] = db;
        }
        return db;
    };
    Rho.NewORM.getDbPartitions = function() {
        return Rho.NewORM.dbPartitions;
    };
    Rho.NewORM.clear = function(){
        Rho.NewORMModel.clear();
    };

    // Global initialization
    console.log("Replacing Old Rho.ORM with new one!!!");
    Rho.ORM = Rho.NewORM;
    Rho.ORMHelper = Rho.NewORM;
    Rho.ORMModel = Rho.NewORMModel;
    Rho.ORM.dbConnection('local');
    Rho.ORM.dbConnection('user');
    Rho.ORM.dbConnection('app');

})(Rho.jQuery, Rho, Rho.util);

<|endoftext|>


<commit_before>'use strict';

var NS = {};

// MODULES //

var getKeys = require( 'object-keys' ).shim();
NS.plot = require( '@stdlib/plot/plot' ).factory({
	'autoRender': false,
	'viewer': 'window'
});
// TODO: add unicode sparklines; requires abstract interface

// VARIABLES //

var KEYS = getKeys( NS );

// ASSIGN //

/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
	var key;
	var i;
	for ( i = 0; i < KEYS.length; i++ ) {
		key = KEYS[ i ];
		ns[ key ] = NS[ key ];
	}
	return ns;
} // end FUNCTION assign()

// EXPORTS //

module.exports = assign;
<commit_msg>Wrap the plot API and separately expose the Plot constructor<commit_after>'use strict';

var NS = {};

// MODULES //

var getKeys = require( 'object-keys' ).shim();
var isObject = require( '@stdlib/utils/is-object' ); // TODO: plain object
var plot = require( '@stdlib/plot/plot' );

// FUNCTIONS //

/**
* Wraps the plot API to provide a REPL specific `plot` function.
*
* @private
* @returns {Plot} Plot instance
*/
function wrapper() {
	var opts;
	var args;
	var h;
	var i;

	// Copy the input arguments...
	args = new Array( arguments.length );
	for ( i = 0; i < args.length; i++ ) {
		args[ i ] = arguments[ i ];
		if ( isObject( args[i] ) ) {
			opts = args[ i ];
		}
	}
	// Create a new plot:
	h = plot.apply( null, args );

	// Check for rendering and view options; if not set, set to REPL defaults...
	if ( opts ) {
		if ( !opts.hasOwnProperty( 'autoRender' ) ) {
			h.autoRender = false;
		}
		if ( !opts.hasOwnProperty( 'autoView' ) ) {
			h.autoView = false;
		}
		if ( !opts.hasOwnProperty( 'viewer' ) ) {
			h.viewer = 'window';
		}
	} else {
		h.autoRender = false;
		h.autoView = false;
		h.viewer = 'window';
	}
	return h;
} // end FUNCTION wrapper()

// NAMESPACE //

NS.plot = wrapper;
NS.Plot = plot;

// VARIABLES //

var KEYS = getKeys( NS );

// ASSIGN //

/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
	var key;
	var i;
	for ( i = 0; i < KEYS.length; i++ ) {
		key = KEYS[ i ];
		ns[ key ] = NS[ key ];
	}
	return ns;
} // end FUNCTION assign()

// EXPORTS //

module.exports = assign;
<|endoftext|>


<commit_before>import { DEBUG } from '@glimmer/env';
import { AbstractTestCase, moduleFor } from 'internal-test-helpers';
import { meta, counters } from '..';

moduleFor(
  'Ember.meta listeners',
  class extends AbstractTestCase {
    ['@test basics'](assert) {
      let t = {};
      let m = meta({});
      m.addToListeners('hello', t, 'm', 0);
      let matching = m.matchingListeners('hello');
      assert.equal(matching.length, 3);
      assert.equal(matching[0], t);
      m.removeFromListeners('hello', t, 'm');
      matching = m.matchingListeners('hello');
      assert.equal(matching, undefined);
    }

    ['@test inheritance'](assert) {
      let target = {};
      let parent = {};
      let parentMeta = meta(parent);
      parentMeta.addToListeners('hello', target, 'm', 0);

      let child = Object.create(parent);
      let m = meta(child);

      let matching = m.matchingListeners('hello');
      assert.equal(matching.length, 3);
      assert.equal(matching[0], target);
      assert.equal(matching[1], 'm');
      assert.equal(matching[2], 0);
      m.removeFromListeners('hello', target, 'm');
      matching = m.matchingListeners('hello');
      assert.equal(matching, undefined);
      matching = parentMeta.matchingListeners('hello');
      assert.equal(matching.length, 3);
    }

    ['@test deduplication'](assert) {
      let t = {};
      let m = meta({});
      m.addToListeners('hello', t, 'm', 0);
      m.addToListeners('hello', t, 'm', 0);
      let matching = m.matchingListeners('hello');
      assert.equal(matching.length, 3);
      assert.equal(matching[0], t);
    }

    ['@test parent caching'](assert) {
      if (DEBUG) {
        counters.flattenedListenersCalls = 0;
        counters.parentListenersUsed = 0;
      }

      class Class {}
      let classMeta = meta(Class.prototype);
      classMeta.addToListeners('hello', null, 'm', 0);

      let instance = new Class();
      let m = meta(instance);

      let matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 2);
        assert.equal(counters.parentListenersUsed, 1);
      }
      matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 3);
        assert.equal(counters.parentListenersUsed, 1);
      }
    }

    ['@test parent cache invalidation'](assert) {
      if (DEBUG) {
        counters.flattenedListenersCalls = 0;
        counters.parentListenersUsed = 0;
        counters.listenersInherited = 0;
      }

      class Class {}
      let classMeta = meta(Class.prototype);
      classMeta.addToListeners('hello', null, 'm', 0);

      let instance = new Class();
      let m = meta(instance);

      let matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 2);
        assert.equal(counters.parentListenersUsed, 1);
        assert.equal(counters.listenersInherited, 0);
      }

      m.addToListeners('hello', null, 'm2');

      matching = m.matchingListeners('hello');

      assert.equal(matching.length, 6);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 4);
        assert.equal(counters.parentListenersUsed, 1);
        assert.equal(counters.listenersInherited, 1);
      }
    }

    ['@test reopen after flatten'](assert) {
      if (!DEBUG) {
        assert.expect(0);
        return;
      }

      // Ensure counter is zeroed
      counters.reopensAfterFlatten = 0;

      class Class1 {}
      let class1Meta = meta(Class1.prototype);
      class1Meta.addToListeners('hello', null, 'm', 0);

      let instance1 = new Class1();
      let m1 = meta(instance1);

      class Class2 {}
      let class2Meta = meta(Class2.prototype);
      class2Meta.addToListeners('hello', null, 'm', 0);

      let instance2 = new Class2();
      let m2 = meta(instance2);

      m1.matchingListeners('hello');
      m2.matchingListeners('hello');

      assert.equal(counters.reopensAfterFlatten, 0, 'no reopen calls yet');

      m1.addToListeners('world', null, 'm', 0);
      m2.addToListeners('world', null, 'm', 0);
      m1.matchingListeners('world');
      m2.matchingListeners('world');

      assert.equal(counters.reopensAfterFlatten, 1, 'reopen calls after invalidating parent cache');

      m1.addToListeners('world', null, 'm', 0);
      m2.addToListeners('world', null, 'm', 0);
      m1.matchingListeners('world');
      m2.matchingListeners('world');

      assert.equal(counters.reopensAfterFlatten, 1, 'no reopen calls after mutating leaf nodes');

      class1Meta.removeFromListeners('hello', null, 'm');
      class2Meta.removeFromListeners('hello', null, 'm');
      m1.matchingListeners('hello');
      m2.matchingListeners('hello');

      assert.equal(counters.reopensAfterFlatten, 2, 'one reopen call after mutating parents');

      class1Meta.addToListeners('hello', null, 'm', 0);
      m1.matchingListeners('hello');
      class2Meta.addToListeners('hello', null, 'm', 0);
      m2.matchingListeners('hello');

      assert.equal(
        counters.reopensAfterFlatten,
        3,
        'one reopen call after mutating parents and flattening out of order'
      );
    }

    '@test removed listeners are removed from the underlying structure GH#1112213'(assert) {
      // this is using private API to confirm the underlying data structure is properly maintained
      // and should be changed to match the data structure as needed

      class Class1 {}
      let class1Meta = meta(Class1.prototype);
      class1Meta.addToListeners('hello', null, 'm', 0);

      let instance1 = new Class1();
      let m1 = meta(instance1);

      function listenerFunc() {}

      m1.removeFromListeners('hello', null, 'm', 0);

      m1.addToListeners('stringListener', null, 'm', 0);
      m1.addToListeners('functionListener', null, listenerFunc, 0);

      m1.removeFromListeners('functionListener', null, listenerFunc, 0);
      m1.removeFromListeners('stringListener', null, 'm', 0);

      assert.equal(
        m1.flattenedListeners().length,
        1,
        'instance listeners correctly removed, inherited listeners remain'
      );
    }
  }
);
<commit_msg>Add more tests for inherited listeners. (#18160)<commit_after>import { DEBUG } from '@glimmer/env';
import { AbstractTestCase, moduleFor } from 'internal-test-helpers';
import { meta, counters } from '..';

moduleFor(
  'Ember.meta listeners',
  class extends AbstractTestCase {
    ['@test basics'](assert) {
      let t = {};
      let m = meta({});
      m.addToListeners('hello', t, 'm', 0);
      let matching = m.matchingListeners('hello');
      assert.equal(matching.length, 3);
      assert.equal(matching[0], t);
      m.removeFromListeners('hello', t, 'm');
      matching = m.matchingListeners('hello');
      assert.equal(matching, undefined);
    }

    ['@test inheritance'](assert) {
      let matching;
      let target = {};
      let parent = {};
      let parentMeta = meta(parent);
      parentMeta.addToListeners('hello', target, 'm', 0);

      let child1 = Object.create(parent);
      let m1 = meta(child1);

      let child2 = Object.create(parent);
      let m2 = meta(child2);

      let child3 = Object.create(parent);
      let m3 = meta(child3);

      m3.removeFromListeners('hello', target, 'm');

      matching = m3.matchingListeners('hello');
      assert.deepEqual(matching, undefined, 'no listeners for child3');

      m3.addToListeners('hello', target, 'm', 0);

      matching = m3.matchingListeners('hello');
      assert.deepEqual(matching, [target, 'm', false], 'listener still exists for child1');

      m3.removeFromListeners('hello', target, 'm');

      matching = m3.matchingListeners('hello');
      assert.deepEqual(matching, undefined, 'no listeners for child3');

      matching = m1.matchingListeners('hello');
      assert.deepEqual(matching, [target, 'm', false], 'listener still exists for child1');

      matching = m2.matchingListeners('hello');
      assert.deepEqual(matching, [target, 'm', false], 'listener still exists for child2');

      m1.removeFromListeners('hello', target, 'm');

      matching = m1.matchingListeners('hello');
      assert.equal(matching, undefined, 'listener removed from child1');

      matching = m2.matchingListeners('hello');
      assert.deepEqual(matching, [target, 'm', false], 'listener still exists for child2');

      matching = parentMeta.matchingListeners('hello');
      assert.deepEqual(matching, [target, 'm', false], 'listener still present for parent');
    }

    ['@test deduplication'](assert) {
      let t = {};
      let m = meta({});
      m.addToListeners('hello', t, 'm', 0);
      m.addToListeners('hello', t, 'm', 0);
      let matching = m.matchingListeners('hello');
      assert.equal(matching.length, 3);
      assert.equal(matching[0], t);
    }

    ['@test parent caching'](assert) {
      if (DEBUG) {
        counters.flattenedListenersCalls = 0;
        counters.parentListenersUsed = 0;
      }

      class Class {}
      let classMeta = meta(Class.prototype);
      classMeta.addToListeners('hello', null, 'm', 0);

      let instance = new Class();
      let m = meta(instance);

      let matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 2);
        assert.equal(counters.parentListenersUsed, 1);
      }
      matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 3);
        assert.equal(counters.parentListenersUsed, 1);
      }
    }

    ['@test parent cache invalidation'](assert) {
      if (DEBUG) {
        counters.flattenedListenersCalls = 0;
        counters.parentListenersUsed = 0;
        counters.listenersInherited = 0;
      }

      class Class {}
      let classMeta = meta(Class.prototype);
      classMeta.addToListeners('hello', null, 'm', 0);

      let instance = new Class();
      let m = meta(instance);

      let matching = m.matchingListeners('hello');

      assert.equal(matching.length, 3);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 2);
        assert.equal(counters.parentListenersUsed, 1);
        assert.equal(counters.listenersInherited, 0);
      }

      m.addToListeners('hello', null, 'm2');

      matching = m.matchingListeners('hello');

      assert.equal(matching.length, 6);
      if (DEBUG) {
        assert.equal(counters.flattenedListenersCalls, 4);
        assert.equal(counters.parentListenersUsed, 1);
        assert.equal(counters.listenersInherited, 1);
      }
    }

    ['@test reopen after flatten'](assert) {
      if (!DEBUG) {
        assert.expect(0);
        return;
      }

      // Ensure counter is zeroed
      counters.reopensAfterFlatten = 0;

      class Class1 {}
      let class1Meta = meta(Class1.prototype);
      class1Meta.addToListeners('hello', null, 'm', 0);

      let instance1 = new Class1();
      let m1 = meta(instance1);

      class Class2 {}
      let class2Meta = meta(Class2.prototype);
      class2Meta.addToListeners('hello', null, 'm', 0);

      let instance2 = new Class2();
      let m2 = meta(instance2);

      m1.matchingListeners('hello');
      m2.matchingListeners('hello');

      assert.equal(counters.reopensAfterFlatten, 0, 'no reopen calls yet');

      m1.addToListeners('world', null, 'm', 0);
      m2.addToListeners('world', null, 'm', 0);
      m1.matchingListeners('world');
      m2.matchingListeners('world');

      assert.equal(counters.reopensAfterFlatten, 1, 'reopen calls after invalidating parent cache');

      m1.addToListeners('world', null, 'm', 0);
      m2.addToListeners('world', null, 'm', 0);
      m1.matchingListeners('world');
      m2.matchingListeners('world');

      assert.equal(counters.reopensAfterFlatten, 1, 'no reopen calls after mutating leaf nodes');

      class1Meta.removeFromListeners('hello', null, 'm');
      class2Meta.removeFromListeners('hello', null, 'm');
      m1.matchingListeners('hello');
      m2.matchingListeners('hello');

      assert.equal(counters.reopensAfterFlatten, 2, 'one reopen call after mutating parents');

      class1Meta.addToListeners('hello', null, 'm', 0);
      m1.matchingListeners('hello');
      class2Meta.addToListeners('hello', null, 'm', 0);
      m2.matchingListeners('hello');

      assert.equal(
        counters.reopensAfterFlatten,
        3,
        'one reopen call after mutating parents and flattening out of order'
      );
    }

    '@test removed listeners are removed from the underlying structure GH#1112213'(assert) {
      // this is using private API to confirm the underlying data structure is properly maintained
      // and should be changed to match the data structure as needed

      class Class1 {}
      let class1Meta = meta(Class1.prototype);
      class1Meta.addToListeners('hello', null, 'm', 0);

      let instance1 = new Class1();
      let m1 = meta(instance1);

      function listenerFunc() {}

      m1.removeFromListeners('hello', null, 'm', 0);

      m1.addToListeners('stringListener', null, 'm', 0);
      m1.addToListeners('functionListener', null, listenerFunc, 0);

      m1.removeFromListeners('functionListener', null, listenerFunc, 0);
      m1.removeFromListeners('stringListener', null, 'm', 0);

      assert.equal(
        m1.flattenedListeners().length,
        1,
        'instance listeners correctly removed, inherited listeners remain'
      );
    }
  }
);
<|endoftext|>


<commit_before>
exports.tagMap = {
  targetTagMap: {
    'cover-view': {
      wx: 'cover-view',
      web: 'div',
      weex: 'div',
      alipay: 'view',
      baidu: 'cover-view'
    },
    'view': {
      wx: 'view',
      web: 'div',
      weex: 'div',
      alipay: 'view',
      baidu: 'view'
    },
    'text': {
      wx: 'text',
      web: 'span',
      weex: 'text',
      alipay: 'text',
      baidu: 'text'
    },
    'image': {
      wx: 'image',
      web: 'img',
      weex: 'image',
      alipay: 'image',
      baidu: 'image'
    },
    'input': {
      wx: 'input',
      web: 'input',
      weex: 'input',
      alipay: 'input',
      baidu: 'input'
    },
    'button': {
      wx: 'button',
      web: 'div',
      weex: 'div',
      alipay: 'button',
      baidu: 'button'
    },
    'cell': {
      wx: 'view',
      web: 'cell',
      weex: 'cell',
      alipay: 'view',
      baidu: 'view'
    },
    'slider-item': {
      wx: 'swiper-item',
      web: 'div',
      weex: 'div',
      alipay: 'swiper-item',
      baidu: 'swiper-item'

    }
  },
  afterTagMap: {
    // 在最后处理的标签，因为template标签在jsdom中不识别
    'block': {
      wx: 'block',
      web: 'template',
      weex: 'template',
      alipay: 'block',
      baidu: 'block'
    }
  },
  diffTagMap: {
    wx: ['cml-wx'],
    web: ['cml-web', 'cml-web-weex'],
    weex: ['cml-weex', 'cml-web-weex'],
    alipay: ['cml-ali'],
    baidu: ['cml-baidu']
  },
  wxTagMap: {
    "carousel": "swiper",
    "carousel-item": "swiper-item"
  }
}
exports.conditionMap = {
  'c-if': {
    web: 'v-if',
    weex: 'v-if',
    wx: 'wx:if',
    alipay: 'a:if',
    baidu: 's-if'
  },
  'c-else-if': {
    web: 'v-else-if',
    weex: 'v-else-if',
    wx: 'wx:elif',
    alipay: 'a:elif',
    baidu: 's-elif'
  },
  'c-else': {
    web: 'v-else',
    weex: 'v-else',
    wx: 'wx:else',
    alipay: 'a:else',
    baidu: 's-else'
  }
}
exports.interationMap = {
  'c-for': {
    wx: 'wx:for',
    alipay: 'a:for',
    baidu: 's-for'
  },
  'c-key': {
    wx: 'wx:key',
    alipay: 'a:key',
    baidu: 's-key'// 百度文档没有提到这个，黑人问号脸
  },
  'c-for-item': {
    wx: 'wx:for-item',
    alipay: 'a:for-item',
    baidu: 's-for-item'
  },
  'c-for-index': {
    wx: 'wx:for-index',
    alipay: 'a:for-index',
    baidu: 's-for-index'
  }
}
exports.eventMap = {
  "touchstart": "touchStart",
  "touchmove": "touchMove",
  "touchend": "touchEnd",
  "touchcancel": "touchCancel",
  "longtap": "longTap"
}
exports.conditionMapVue2Wx = {
  'v-if': {
    wx: 'wx:if',
    alipay: 'a:if',
    baidu: 's-if'
  },
  'v-else-if': {
    wx: 'wx:elif',
    alipay: 'a:elif',
    baidu: 's-elif'
  },
  'v-else': {
    wx: 'wx:else',
    alipay: 'a:else',
    baidu: 's-else'
  }
}
<commit_msg>cover-view<commit_after>
exports.tagMap = {
  targetTagMap: {
    'cover-view': {
      wx: 'cover-view',
      web: 'div',
      weex: 'div',
      alipay: 'cover-view',
      baidu: 'cover-view'
    },
    'view': {
      wx: 'view',
      web: 'div',
      weex: 'div',
      alipay: 'view',
      baidu: 'view'
    },
    'text': {
      wx: 'text',
      web: 'span',
      weex: 'text',
      alipay: 'text',
      baidu: 'text'
    },
    'image': {
      wx: 'image',
      web: 'img',
      weex: 'image',
      alipay: 'image',
      baidu: 'image'
    },
    'input': {
      wx: 'input',
      web: 'input',
      weex: 'input',
      alipay: 'input',
      baidu: 'input'
    },
    'button': {
      wx: 'button',
      web: 'div',
      weex: 'div',
      alipay: 'button',
      baidu: 'button'
    },
    'cell': {
      wx: 'view',
      web: 'cell',
      weex: 'cell',
      alipay: 'view',
      baidu: 'view'
    },
    'slider-item': {
      wx: 'swiper-item',
      web: 'div',
      weex: 'div',
      alipay: 'swiper-item',
      baidu: 'swiper-item'

    }
  },
  afterTagMap: {
    // 在最后处理的标签，因为template标签在jsdom中不识别
    'block': {
      wx: 'block',
      web: 'template',
      weex: 'template',
      alipay: 'block',
      baidu: 'block'
    }
  },
  diffTagMap: {
    wx: ['cml-wx'],
    web: ['cml-web', 'cml-web-weex'],
    weex: ['cml-weex', 'cml-web-weex'],
    alipay: ['cml-ali'],
    baidu: ['cml-baidu']
  },
  wxTagMap: {
    "carousel": "swiper",
    "carousel-item": "swiper-item"
  }
}
exports.conditionMap = {
  'c-if': {
    web: 'v-if',
    weex: 'v-if',
    wx: 'wx:if',
    alipay: 'a:if',
    baidu: 's-if'
  },
  'c-else-if': {
    web: 'v-else-if',
    weex: 'v-else-if',
    wx: 'wx:elif',
    alipay: 'a:elif',
    baidu: 's-elif'
  },
  'c-else': {
    web: 'v-else',
    weex: 'v-else',
    wx: 'wx:else',
    alipay: 'a:else',
    baidu: 's-else'
  }
}
exports.interationMap = {
  'c-for': {
    wx: 'wx:for',
    alipay: 'a:for',
    baidu: 's-for'
  },
  'c-key': {
    wx: 'wx:key',
    alipay: 'a:key',
    baidu: 's-key'// 百度文档没有提到这个，黑人问号脸
  },
  'c-for-item': {
    wx: 'wx:for-item',
    alipay: 'a:for-item',
    baidu: 's-for-item'
  },
  'c-for-index': {
    wx: 'wx:for-index',
    alipay: 'a:for-index',
    baidu: 's-for-index'
  }
}
exports.eventMap = {
  "touchstart": "touchStart",
  "touchmove": "touchMove",
  "touchend": "touchEnd",
  "touchcancel": "touchCancel",
  "longtap": "longTap"
}
exports.conditionMapVue2Wx = {
  'v-if': {
    wx: 'wx:if',
    alipay: 'a:if',
    baidu: 's-if'
  },
  'v-else-if': {
    wx: 'wx:elif',
    alipay: 'a:elif',
    baidu: 's-elif'
  },
  'v-else': {
    wx: 'wx:else',
    alipay: 'a:else',
    baidu: 's-else'
  }
}
<|endoftext|>


<commit_before>"use strict";

const should = require("should");

const MessageSecurityMode = require("node-opcua-service-secure-channel").MessageSecurityMode;
const SecurityPolicy = require("node-opcua-secure-channel").SecurityPolicy;
const EndpointDescription = require("node-opcua-service-endpoints").EndpointDescription;
const extractFullyQualifiedDomainName = require("node-opcua-hostname").extractFullyQualifiedDomainName;

const crypto_utils = require("node-opcua-crypto");
const it_with_crypto = it;

const default_port = 1234;

const OPCUAServerEndPoint = require("..").OPCUAServerEndPoint;

// eslint-disable-next-line import/order
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("OPCUAServerEndpoint#addEndpointDescription", function () {
    let server_endpoint;
    before(async () => {
        await extractFullyQualifiedDomainName();
    });

    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: default_port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
    });

    const param = {};
    afterEach(function () {
        server_endpoint = null;
    });

    it("should  accept  to add endpoint endMessageSecurityMode.None and SecurityPolicy.None", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        }).not.throwError();
    });

    it("should  accept  to add endpoint endMessageSecurityMode.None and SecurityPolicy.None twice", function () {
        server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        }).throwError();
    });

    it("should not accept to add endpoint with MessageSecurityMode.None and SecurityPolicy.Basic128", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.Basic128);
        }).throwError();
    });
    it("should not accept  to add endpoint  MessageSecurityMode.Sign and SecurityPolicy.None", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.None);
        }).throwError();
    });
});

describe("OPCUAServerEndpoint#addStandardEndpointDescriptions", function () {
    let server_endpoint;
    before(async () => {
        await extractFullyQualifiedDomainName();
    });
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: default_port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
        server_endpoint.addStandardEndpointDescriptions();
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it("should find a endpoint matching MessageSecurityMode.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(endpoint_desc).be.instanceOf(EndpointDescription);
    });

    it_with_crypto("should find a endpoint matching SIGNANDENCRYPT / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
    it_with_crypto("should find a endpoint matching SIGN / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
});

describe("OPCUAServerEndpoint#addStandardEndpointDescriptions extra secure", function () {
    let server_endpoint;
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: default_port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
        server_endpoint.addStandardEndpointDescriptions({
            securityModes: [MessageSecurityMode.SignAndEncrypt],
            disableDiscovery: true
        });
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it("should not find a endpoint matching MessageSecurityMode.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });

    it_with_crypto("should not find a endpoint matching Sign / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.eql(null);
    });

    it_with_crypto("should find a endpoint matching SignAndEncrypt / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
});

describe("OPCUAServerEndpoint#getEndpointDescription", function () {
    let server_endpoint;
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: default_port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it_with_crypto("should not find a endpoint matching MessageSecurityMode.SIGN and SecurityPolicy.Basic128", function () {
        let endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        should(endpoint_desc).be.eql(null);

        server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);

        endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        should(endpoint_desc).be.instanceof(EndpointDescription);

        endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });

    it("should not find a endpoint matching MessageSecurityMode.Sign and SecurityPolicy.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });
    it("should not find a endpoint matching MessageSecurityMode.SignAndEncrypt and SecurityPolicy.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });
});
<commit_msg>chore(server): change port in test to avoid collision<commit_after>"use strict";

const should = require("should");

const MessageSecurityMode = require("node-opcua-service-secure-channel").MessageSecurityMode;
const SecurityPolicy = require("node-opcua-secure-channel").SecurityPolicy;
const EndpointDescription = require("node-opcua-service-endpoints").EndpointDescription;
const extractFullyQualifiedDomainName = require("node-opcua-hostname").extractFullyQualifiedDomainName;

const crypto_utils = require("node-opcua-crypto");
const it_with_crypto = it;

const port = 2042;

const OPCUAServerEndPoint = require("..").OPCUAServerEndPoint;

// eslint-disable-next-line import/order
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("OPCUAServerEndpoint#addEndpointDescription", function () {
    let server_endpoint;
    before(async () => {
        await extractFullyQualifiedDomainName();
    });

    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
    });

    const param = {};
    afterEach(function () {
        server_endpoint = null;
    });

    it("should  accept  to add endpoint endMessageSecurityMode.None and SecurityPolicy.None", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        }).not.throwError();
    });

    it("should  accept  to add endpoint endMessageSecurityMode.None and SecurityPolicy.None twice", function () {
        server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        }).throwError();
    });

    it("should not accept to add endpoint with MessageSecurityMode.None and SecurityPolicy.Basic128", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.None, SecurityPolicy.Basic128);
        }).throwError();
    });
    it("should not accept  to add endpoint  MessageSecurityMode.Sign and SecurityPolicy.None", function () {
        should(function () {
            server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.None);
        }).throwError();
    });
});

describe("OPCUAServerEndpoint#addStandardEndpointDescriptions", function () {
    let server_endpoint;
    before(async () => {
        await extractFullyQualifiedDomainName();
    });
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
        server_endpoint.addStandardEndpointDescriptions();
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it("should find a endpoint matching MessageSecurityMode.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(endpoint_desc).be.instanceOf(EndpointDescription);
    });

    it_with_crypto("should find a endpoint matching SIGNANDENCRYPT / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
    it_with_crypto("should find a endpoint matching SIGN / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
});

describe("OPCUAServerEndpoint#addStandardEndpointDescriptions extra secure", function () {
    let server_endpoint;
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
        server_endpoint.addStandardEndpointDescriptions({
            securityModes: [MessageSecurityMode.SignAndEncrypt],
            disableDiscovery: true
        });
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it("should not find a endpoint matching MessageSecurityMode.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.None, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });

    it_with_crypto("should not find a endpoint matching Sign / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.eql(null);
    });

    it_with_crypto("should find a endpoint matching SignAndEncrypt / Basic256", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });
});

describe("OPCUAServerEndpoint#getEndpointDescription", function () {
    let server_endpoint;
    beforeEach(function () {
        server_endpoint = new OPCUAServerEndPoint({
            port: port,
            serverInfo: {},
            certificateChain: null,
            privateKey: ""
        });
    });
    afterEach(function () {
        server_endpoint = null;
    });

    it_with_crypto("should not find a endpoint matching MessageSecurityMode.SIGN and SecurityPolicy.Basic128", function () {
        let endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        should(endpoint_desc).be.eql(null);

        server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        server_endpoint.addEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);

        endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic128);
        should(endpoint_desc).be.instanceof(EndpointDescription);

        endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.Basic256);
        should(endpoint_desc).be.instanceof(EndpointDescription);
    });

    it("should not find a endpoint matching MessageSecurityMode.Sign and SecurityPolicy.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.Sign, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });
    it("should not find a endpoint matching MessageSecurityMode.SignAndEncrypt and SecurityPolicy.None", function () {
        const endpoint_desc = server_endpoint.getEndpointDescription(MessageSecurityMode.SignAndEncrypt, SecurityPolicy.None);
        should(endpoint_desc).be.eql(null);
    });
});
<|endoftext|>


<commit_before>const assert = require("assert");
const sinon = require("sinon");
const CompilerSupplier = require("../../compilerSupplier");
const {
  Docker,
  Native,
  Local,
  Bundled,
  VersionRange
} = require("../../compilerSupplier/loadingStrategies");
let supplier, config;

describe("CompilerSupplier", () => {
  describe("load()", () => {
    describe("when a docker tag is specified in the config", () => {
      beforeEach(() => {
        config = {
          docker: "randoDockerTagzzz",
          version: "0.4.25"
        };
        supplier = new CompilerSupplier(config);
        sinon.stub(Docker.prototype, "load").returns("called Docker");
      });
      afterEach(() => {
        Docker.prototype.load.restore();
      });

      it("calls load on the Docker strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Docker");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe(`when the version is set to a specific word I can't write here`, () => {
      // HACK: Because of how the test script is set up, the word 'native' cannot be a
      // part of the it/describe strings above and below
      beforeEach(() => {
        config = { version: "native" };
        supplier = new CompilerSupplier(config);
        sinon.stub(Native.prototype, "load").returns("called Native");
      });
      afterEach(() => {
        Native.prototype.load.restore();
      });

      it("calls load on the Native strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Native");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when no version is specified in the config", () => {
      beforeEach(() => {
        supplier = new CompilerSupplier();
        sinon.stub(Bundled.prototype, "load").returns("called Bundled");
      });
      afterEach(() => {
        Bundled.prototype.load.restore();
      });

      it("calls load on the Bundled strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Bundled");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a solc version is specified in the config", () => {
      beforeEach(() => {
        config = { version: "0.4.11" };
        supplier = new CompilerSupplier(config);
        sinon
          .stub(VersionRange.prototype, "load")
          .returns("called VersionRange");
      });
      afterEach(() => {
        VersionRange.prototype.load.restore();
      });

      it("calls load on the VersionRange strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called VersionRange");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a user specifies the compiler url root", () => {
      beforeEach(() => {
        sinon.stub(VersionRange.prototype, "versionIsCached").returns(false);
      });
      afterEach(() => {
        VersionRange.prototype.versionIsCached.restore();
      });

      it("Uses the user specified url", done => {
        // This doesn't really verify that user provided list is being used but this in combination with next test does.
        // I am not sure what's the best way to check if user specified list is being used.
        config = {
          version: "0.4.11",
          compilerRoots: [
            "https://f00dbabe",
            "https://ethereum.github.io/solc-bin/bin/"
          ]
        };
        supplier = new CompilerSupplier(config);
        supplier
          .load()
          .then(() => {
            assert(true);
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });

      it("throws an error on incorrect user url", done => {
        config = { version: "0.4.12", compilerRoots: ["https://f00dbabe"] };
        supplier = new CompilerSupplier(config);
        supplier
          .load()
          .then(() => {
            assert(false);
            done();
          })
          .catch(error => {
            let expectedMessageSnippet = "Could not find a compiler version";
            assert(error.message.includes(expectedMessageSnippet));
            done();
          });
      });
    });

    describe("when a solc version range is specified", () => {
      beforeEach(() => {
        config = { version: "^0.4.11" };
        supplier = new CompilerSupplier(config);
        sinon
          .stub(VersionRange.prototype, "load")
          .returns("called VersionRange");
      });
      afterEach(() => {
        VersionRange.prototype.load.restore();
      });

      it("calls load on the VersionRange strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called VersionRange");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a path is specified in the config", () => {
      beforeEach(() => {
        config = { version: "./some/path" };
        supplier = new CompilerSupplier(config);
        sinon.stub(supplier, "fileExists").returns(true);
        sinon.stub(Local.prototype, "load").returns("called Local");
      });
      afterEach(() => {
        supplier.fileExists.restore();
        Local.prototype.load.restore();
      });

      it("calls load on the Local strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Local");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when no valid values are specified", () => {
      beforeEach(() => {
        config = { version: "globbity gloop" };
        supplier = new CompilerSupplier(config);
      });

      it("throws an error", done => {
        supplier
          .load()
          .then(() => {
            assert(false);
            done();
          })
          .catch(error => {
            let expectedMessageSnippet = "version matching globbity gloop";
            assert(error.message.includes(expectedMessageSnippet));
            done();
          });
      });
    });
  });
});
<commit_msg>update compilerSupplier test<commit_after>const assert = require("assert");
const sinon = require("sinon");
const CompilerSupplier = require("../../compilerSupplier");
const {
  Docker,
  Native,
  Local,
  VersionRange
} = require("../../compilerSupplier/loadingStrategies");
let supplier, config;

describe("CompilerSupplier", () => {
  describe("load()", () => {
    describe("when a docker tag is specified in the config", () => {
      beforeEach(() => {
        config = {
          docker: "randoDockerTagzzz",
          version: "0.4.25"
        };
        supplier = new CompilerSupplier(config);
        sinon.stub(Docker.prototype, "load").returns("called Docker");
      });
      afterEach(() => {
        Docker.prototype.load.restore();
      });

      it("calls load on the Docker strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Docker");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe(`when the version is set to a specific word I can't write here`, () => {
      // HACK: Because of how the test script is set up, the word 'native' cannot be a
      // part of the it/describe strings above and below
      beforeEach(() => {
        config = { version: "native" };
        supplier = new CompilerSupplier(config);
        sinon.stub(Native.prototype, "load").returns("called Native");
      });
      afterEach(() => {
        Native.prototype.load.restore();
      });

      it("calls load on the Native strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Native");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when no version is specified in the config", () => {
      beforeEach(() => {
        supplier = new CompilerSupplier();
        sinon
          .stub(VersionRange.prototype, "load")
          .returns("called VersionRange");
      });
      afterEach(() => {
        VersionRange.prototype.load.restore();
      });

      it("calls load on the VersionRange strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called VersionRange");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a solc version is specified in the config", () => {
      beforeEach(() => {
        config = { version: "0.4.11" };
        supplier = new CompilerSupplier(config);
        sinon
          .stub(VersionRange.prototype, "load")
          .returns("called VersionRange");
      });
      afterEach(() => {
        VersionRange.prototype.load.restore();
      });

      it("calls load on the VersionRange strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called VersionRange");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a user specifies the compiler url root", () => {
      beforeEach(() => {
        sinon.stub(VersionRange.prototype, "versionIsCached").returns(false);
      });
      afterEach(() => {
        VersionRange.prototype.versionIsCached.restore();
      });

      it("Uses the user specified url", done => {
        // This doesn't really verify that user provided list is being used but this in combination with next test does.
        // I am not sure what's the best way to check if user specified list is being used.
        config = {
          version: "0.4.11",
          compilerRoots: [
            "https://f00dbabe",
            "https://ethereum.github.io/solc-bin/bin/"
          ]
        };
        supplier = new CompilerSupplier(config);
        supplier
          .load()
          .then(() => {
            assert(true);
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });

      it("throws an error on incorrect user url", done => {
        config = { version: "0.4.12", compilerRoots: ["https://f00dbabe"] };
        supplier = new CompilerSupplier(config);
        supplier
          .load()
          .then(() => {
            assert(false);
            done();
          })
          .catch(error => {
            let expectedMessageSnippet = "Could not find a compiler version";
            assert(error.message.includes(expectedMessageSnippet));
            done();
          });
      });
    });

    describe("when a solc version range is specified", () => {
      beforeEach(() => {
        config = { version: "^0.4.11" };
        supplier = new CompilerSupplier(config);
        sinon
          .stub(VersionRange.prototype, "load")
          .returns("called VersionRange");
      });
      afterEach(() => {
        VersionRange.prototype.load.restore();
      });

      it("calls load on the VersionRange strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called VersionRange");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when a path is specified in the config", () => {
      beforeEach(() => {
        config = { version: "./some/path" };
        supplier = new CompilerSupplier(config);
        sinon.stub(supplier, "fileExists").returns(true);
        sinon.stub(Local.prototype, "load").returns("called Local");
      });
      afterEach(() => {
        supplier.fileExists.restore();
        Local.prototype.load.restore();
      });

      it("calls load on the Local strategy", done => {
        supplier
          .load()
          .then(result => {
            assert(result === "called Local");
            done();
          })
          .catch(() => {
            assert(false);
            done();
          });
      });
    });

    describe("when no valid values are specified", () => {
      beforeEach(() => {
        config = { version: "globbity gloop" };
        supplier = new CompilerSupplier(config);
      });

      it("throws an error", done => {
        supplier
          .load()
          .then(() => {
            assert(false);
            done();
          })
          .catch(error => {
            let expectedMessageSnippet = "version matching globbity gloop";
            assert(error.message.includes(expectedMessageSnippet));
            done();
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @file PointStep component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import PointStepItem from '../_PointStepItem';

class PointStep extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            activatedStep: props.activatedStep,
            finishedStep: props.finishedStep
        };

        this.touchTapHandler = ::this.touchTapHandler;

    }

    touchTapHandler(activatedStep) {

        const {onChange} = this.props;

        this.setState({
            activatedStep
        }, () => {
            onChange && onChange({
                activatedStep,
                finishedStep: this.state.finishedStep
            });
        });

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.activatedStep !== this.state.activatedStep
            || nextProps.finishedStep !== this.state.finishedStep) {
            this.setState({
                activatedStep: nextProps.activatedStep,
                finishedStep: nextProps.finishedStep
            });
        }
    }

    render() {

        const {className, style, steps, showFinishedStepIcon, finishedStepIconCls, disabled} = this.props,
            {activatedStep, finishedStep} = this.state,

            stepClassName = classNames('point-step', {
                [className]: className
            });

        return (

                {
                    steps && steps.map((item, index) =>
                        <PointStepItem key={index}
                                       index={index}
                                       className={item.className}
                                       style={{
                                           ...item.style,
                                           width: `${100 / steps.length}%`,
                                           zIndex: steps.length - index
                                       }}
                                       activatedStep={activatedStep}
                                       finishedStep={finishedStep}
                                       value={item}
                                       isFirst={index === 0}
                                       isLast={index === steps.length - 1}
                                       showFinishedStepIcon={showFinishedStepIcon}
                                       finishedStepIconCls={finishedStepIconCls}
                                       disabled={disabled}
                                       onClick={this.touchTapHandler}/>
                    )
                }

        );

    }
}

PointStep.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The render content of step.
     */
    steps: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The CSS class name of step element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the step element.
         */
        style: PropTypes.object,

        /**
         * The text value of step.
         */
        title: PropTypes.string

    })).isRequired,

    /**
     * Sets the step as active.
     */
    activatedStep: PropTypes.number,

    /**
     * The final step.
     */
    finishedStep: PropTypes.number,

    showFinishedStepIcon: PropTypes.bool,
    finishedStepIconCls: PropTypes.string,

    disabled: PropTypes.bool,

    /**
     * Callback function fired when step change.
     */
    onChange: PropTypes.func

};

PointStep.defaultProps = {

    activatedStep: 0,
    finishedStep: 0,

    showFinishedStepIcon: true,
    finishedStepIconCls: 'fas fa-check',
    disabled: false

};

export default PointStep;<commit_msg>update PointStep<commit_after>/**
 * @file PointStep component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import PointStepItem from '../_PointStepItem';

class PointStep extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            activatedStep: props.activatedStep,
            finishedStep: props.finishedStep
        };

    }

    touchTapHandler = activatedStep => {

        const {onChange} = this.props;

        this.setState({
            activatedStep
        }, () => {
            onChange && onChange({
                activatedStep,
                finishedStep: this.state.finishedStep
            });
        });

    };

    componentWillReceiveProps(nextProps) {
        if (nextProps.activatedStep !== this.state.activatedStep
            || nextProps.finishedStep !== this.state.finishedStep) {
            this.setState({
                activatedStep: nextProps.activatedStep,
                finishedStep: nextProps.finishedStep
            });
        }
    }

    render() {

        const {className, style, steps, showFinishedStepIcon, finishedStepIconCls, disabled} = this.props,
            {activatedStep, finishedStep} = this.state,

            stepClassName = classNames('point-step', {
                [className]: className
            });

        return (

                {
                    steps && steps.map((item, index) =>
                        <PointStepItem key={index}
                                       index={index}
                                       className={item.className}
                                       style={{
                                           ...item.style,
                                           width: `${100 / steps.length}%`,
                                           zIndex: steps.length - index
                                       }}
                                       activatedStep={activatedStep}
                                       finishedStep={finishedStep}
                                       value={item}
                                       isFirst={index === 0}
                                       isLast={index === steps.length - 1}
                                       showFinishedStepIcon={showFinishedStepIcon}
                                       finishedStepIconCls={finishedStepIconCls}
                                       disabled={disabled}
                                       onClick={this.touchTapHandler}/>
                    )
                }

        );

    }
}

PointStep.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The render content of step.
     */
    steps: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The CSS class name of step element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the step element.
         */
        style: PropTypes.object,

        /**
         * The text value of step.
         */
        title: PropTypes.string

    })).isRequired,

    /**
     * Sets the step as active.
     */
    activatedStep: PropTypes.number,

    /**
     * The final step.
     */
    finishedStep: PropTypes.number,

    showFinishedStepIcon: PropTypes.bool,
    finishedStepIconCls: PropTypes.string,

    disabled: PropTypes.bool,

    /**
     * Callback function fired when step change.
     */
    onChange: PropTypes.func

};

PointStep.defaultProps = {

    activatedStep: 0,
    finishedStep: 0,

    showFinishedStepIcon: true,
    finishedStepIconCls: 'fas fa-check',
    disabled: false

};

export default PointStep;<|endoftext|>


<commit_before>// A test of all the features in Elemental.js, GitHub.com/AppIns/Elemental.js
// Licensed under the MIT license

// Please load this file after Elemental.js

// This is to be used as an example of Elemental.js, not a test
window.onload = function(){
  var showcase = new Element("DIV");
    showcase.eAppendTo(document.body);
    showcase.eStyle("paddingTop", "10px");
    showcase.eStyle("marginTop", "20px");
    showcase.eStyle("marginLeft", "auto");
    showcase.eStyle("marginRight", "auto");
    showcase.eStyle("width", "40em");
    showcase.eStyle("borderRadius", "20px");
    showcase.eStyle("color", "#3c3c3c");
    showcase.eStyle("backgroundColor", "#e3e3e3");
    showcase.eStyle("textAlign", "center");
    showcase.eIdentify("ShowcaseEl", undefined);
  var jsIMG = new Element("IMG");
    jsIMG.eProperty("src", "Showcase/IMG/JavaScript.png");
    jsIMG.eAppendTo(eSel("#ShowcaseEl"));
    jsIMG.eStyle("width", "70px");
    jsIMG.eStyle("height", "70px");
  var Test1 = new Element("P");
    Test1.eQuick("Quick test", eSel("#ShowcaseEl"), "Elemental.JS");
    Test1.eStyle("fontSize", "40px");
  new Element("P").eQuick("Welcome", eSel("#ShowcaseEl"), "Elemental.js makes DOM manipulation easy and simple");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("P").eQuick("Ins1", eSel("#ShowcaseEl"), "To install ElementalJS in YOUR project,
 just download it to your code and use");
  new Element("CODE").eQuick("Ins2", eSel("#ShowcaseEl"), "<scirpt src=\"Elemental.min.js\"></script>");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("A").eQuick("link", eSel("#ShowcaseEl"), "GitHub").eProperty("href", "https://github.com/AppIns/Elemental.js").eStyle("color", "#606060");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
}
<commit_msg>Small fix<commit_after>// A test of all the features in Elemental.js, GitHub.com/AppIns/Elemental.js
// Licensed under the MIT license

// Please load this file after Elemental.js

// This is to be used as an example of Elemental.js, not a test
window.onload = function(){
  var showcase = new Element("DIV");
    showcase.eAppendTo(document.body);
    showcase.eStyle("paddingTop", "10px");
    showcase.eStyle("marginTop", "20px");
    showcase.eStyle("marginLeft", "auto");
    showcase.eStyle("marginRight", "auto");
    showcase.eStyle("width", "40em");
    showcase.eStyle("borderRadius", "20px");
    showcase.eStyle("color", "#3c3c3c");
    showcase.eStyle("backgroundColor", "#e3e3e3");
    showcase.eStyle("textAlign", "center");
    showcase.eIdentify("ShowcaseEl", undefined);
  var jsIMG = new Element("IMG");
    jsIMG.eProperty("src", "Showcase/IMG/JavaScript.png");
    jsIMG.eAppendTo(eSel("#ShowcaseEl"));
    jsIMG.eStyle("width", "70px");
    jsIMG.eStyle("height", "70px");
  var Test1 = new Element("P");
    Test1.eQuick("Quick test", eSel("#ShowcaseEl"), "Elemental.JS");
    Test1.eStyle("fontSize", "40px");
  new Element("P").eQuick("Welcome", eSel("#ShowcaseEl"), "Elemental.js makes DOM manipulation easy and simple");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("P").eQuick("Ins1", eSel("#ShowcaseEl"), "To install ElementalJS in YOUR project,
 just download it to your code and use");
  new Element("CODE").eQuick("Ins2", eSel("#ShowcaseEl"), "<scirpt src=\"Elemental.min.js\"></script>");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("A").eQuick("link", eSel("#ShowcaseEl"), "GitHub").eProperty("href", "https://github.com/AppIns/Elemental.js").eStyle("color", "#606060");
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
  new Element("BR").eAppendTo(eSel("#ShowcaseEl"));
};
<|endoftext|>