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

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        /*
         * apply arguemnts to constructor
         *
         * @param constructor
         * @param args
         */
        this.applyConstructor   = function(constructor, args) {
            var F = function () {
                return constructor.apply(this, args);
            };

            F.prototype = constructor.prototype;
            return new F();
        };

        /**
         * Функция ищет в имени файла расширение
         * и если находит возвращает true
         * @param name - получает имя файла
         * @param ext - расширение
         */
        this.checkExt           = function(name, ext) {
            var isMatch, str,
                type        = Util.type(ext),
                regStr      = '\\.({{ exts }})$',
                regExp;

            switch(type) {
            case 'string':
                regStr      = Util.render(regStr, {
                    exts: ext
                });

                regExp      = new RegExp(regStr, 'i');
                isMatch     = regExp.test(name);

                break;

            case 'array':
                str         = ext.join('|');
                isMatch     = Util.checkExt(name, str);

                break;
            }

            return isMatch;
        };

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?\\');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var str, regExp,
                result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    str     = view[param];
                    regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');
                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [],
                isArray = Util.type.array(arr);

            if (arr && !isArray)
                arr = arr.data;

            if (arr)
                arr.forEach(function(item) {
                    ret.push(item.name || item);
                });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret,
                isArray = Util.type.array(array);

            if (isArray) {
                array.some(function(item) {
                    var is = item.name === name,
                        isArray = Util.type.array(item);

                    if (is)
                        ret = item;
                    else if (isArray)
                        item.some(function(item) {
                            is = item.name === name;

                            if (is)
                                ret = item.data;
                        });

                    return is;
                });
            }

            return ret;
        };

        /**
         * Gets current time in format hh:mm:ss
         */
        this.getTime                    = function() {
            var ret,
                date        = new Date(),
                hours       = date.getHours(),
                minutes     = date.getMinutes(),
                seconds     = date.getSeconds();

            minutes         = minutes < 10 ? '0' + minutes : minutes;
            seconds         = seconds < 10 ? '0' + seconds : seconds;

            ret            = hours + ':' + minutes + ':' + seconds;

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<commit_msg>fix(util) some: add return<commit_after>(function(scope) {
    'use strict';

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        /*
         * apply arguemnts to constructor
         *
         * @param constructor
         * @param args
         */
        this.applyConstructor   = function(constructor, args) {
            var F = function () {
                return constructor.apply(this, args);
            };

            F.prototype = constructor.prototype;
            return new F();
        };

        /**
         * Функция ищет в имени файла расширение
         * и если находит возвращает true
         * @param name - получает имя файла
         * @param ext - расширение
         */
        this.checkExt           = function(name, ext) {
            var isMatch, str,
                type        = Util.type(ext),
                regStr      = '\\.({{ exts }})$',
                regExp;

            switch(type) {
            case 'string':
                regStr      = Util.render(regStr, {
                    exts: ext
                });

                regExp      = new RegExp(regStr, 'i');
                isMatch     = regExp.test(name);

                break;

            case 'array':
                str         = ext.join('|');
                isMatch     = Util.checkExt(name, str);

                break;
            }

            return isMatch;
        };

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?\\');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var str, regExp,
                result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    str     = view[param];
                    regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');
                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [],
                isArray = Util.type.array(arr);

            if (arr && !isArray)
                arr = arr.data;

            if (arr)
                arr.forEach(function(item) {
                    ret.push(item.name || item);
                });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret,
                isArray = Util.type.array(array);

            if (isArray) {
                array.some(function(item) {
                    var is = item.name === name,
                        isArray = Util.type.array(item);

                    if (is)
                        ret = item;
                    else if (isArray)
                        item.some(function(item) {
                            is = item.name === name;

                            if (is)
                                ret = item.data;

                            return is;
                        });

                    return is;
                });
            }

            return ret;
        };

        /**
         * Gets current time in format hh:mm:ss
         */
        this.getTime                    = function() {
            var ret,
                date        = new Date(),
                hours       = date.getHours(),
                minutes     = date.getMinutes(),
                seconds     = date.getSeconds();

            minutes         = minutes < 10 ? '0' + minutes : minutes;
            seconds         = seconds < 10 ? '0' + seconds : seconds;

            ret            = hours + ':' + minutes + ':' + seconds;

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview These stubs emulate backend functionality and allows
 * DevTools frontend to function as a standalone web app.
 */

/**
 * @constructor
 */
RemoteDebuggerAgentStub = function() {
  this.activeProfilerModules_ =
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_NONE;
  this.profileLogPos_ = 0;
  this.heapProfSample_ = 0;
  this.heapProfLog_ = '';
};

RemoteDebuggerAgentStub.prototype.GetContextId = function() {
  RemoteDebuggerAgent.SetContextId(3);
};

RemoteDebuggerAgentStub.prototype.StopProfiling = function(modules) {
  this.activeProfilerModules_ &= ~modules;
};

RemoteDebuggerAgentStub.prototype.StartProfiling = function(modules) {
  var profModules = devtools.DebuggerAgent.ProfilerModules;
  if (modules & profModules.PROFILER_MODULE_HEAP_SNAPSHOT) {
    if (modules & profModules.PROFILER_MODULE_HEAP_STATS) {
      this.heapProfLog_ +=
          'heap-sample-begin,"Heap","allocated",' +
              (new Date()).getTime() + '\n' +
          'heap-sample-stats,"Heap","allocated",10000,1000\n';
      this.heapProfLog_ +=
          'heap-sample-item,STRING_TYPE,100,1000\n' +
          'heap-sample-item,CODE_TYPE,10,200\n' +
          'heap-sample-item,MAP_TYPE,20,350\n';
      this.heapProfLog_ += RemoteDebuggerAgentStub.HeapSamples[this.heapProfSample_++];
      this.heapProfSample_ %= RemoteDebuggerAgentStub.HeapSamples.length;
      this.heapProfLog_ +=
          'heap-sample-end,"Heap","allocated"\n';
    }
  } else {
    this.activeProfilerModules_ |= modules;
  }
};

RemoteDebuggerAgentStub.prototype.GetActiveProfilerModules = function() {
  var self = this;
  setTimeout(function() {
      RemoteDebuggerAgent.DidGetActiveProfilerModules(
          self.activeProfilerModules_);
  }, 100);
};

RemoteDebuggerAgentStub.prototype.GetNextLogLines = function() {
  var profModules = devtools.DebuggerAgent.ProfilerModules;
  var logLines = '';
  if (this.activeProfilerModules_ & profModules.PROFILER_MODULE_CPU) {
    if (this.profileLogPos_ < RemoteDebuggerAgentStub.ProfilerLogBuffer.length) {
      this.profileLogPos_ += RemoteDebuggerAgentStub.ProfilerLogBuffer.length;
      logLines += RemoteDebuggerAgentStub.ProfilerLogBuffer;
    }
  }
  if (this.heapProfLog_) {
    logLines += this.heapProfLog_;
    this.heapProfLog_ = '';
  }
  setTimeout(function() {
    RemoteDebuggerAgent.DidGetNextLogLines(logLines);
  }, 100);
};

/**
 * @constructor
 */
RemoteToolsAgentStub = function() {
};

RemoteToolsAgentStub.prototype.DispatchOnInjectedScript = function() {
};

RemoteToolsAgentStub.prototype.DispatchOnInspectorController = function() {
};

RemoteToolsAgentStub.prototype.ExecuteVoidJavaScript = function() {
};

RemoteDebuggerAgentStub.ProfilerLogBuffer =
  'profiler,begin,1\n' +
  'profiler,resume\n' +
  'code-creation,LazyCompile,0x1000,256,"test1 http://aaa.js:1"\n' +
  'code-creation,LazyCompile,0x2000,256,"test2 http://bbb.js:2"\n' +
  'code-creation,LazyCompile,0x3000,256,"test3 http://ccc.js:3"\n' +
  'tick,0x1010,0x0,3\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x3010,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2030,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x1010,0x0,3\n' +
  'profiler,pause\n';

RemoteDebuggerAgentStub.HeapSamples = [
  'heap-js-cons-item,foo,1,100\n' +
  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,Object,5,100\n' +
  'heap-js-ret-item,foo,bar;3\n' +
  'heap-js-ret-item,bar,foo;5\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1\n',

  'heap-js-cons-item,foo,2000,200000\n' +
  'heap-js-cons-item,bar,10,1000\n' +
  'heap-js-cons-item,Object,6,120\n' +
  'heap-js-ret-item,foo,bar;7,Object:0x1234;10\n' +
  'heap-js-ret-item,bar,foo;10,Object:0x1234;10\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1\n',

  'heap-js-cons-item,foo,15,1500\n' +
  'heap-js-cons-item,bar,15,1500\n' +
  'heap-js-cons-item,Object,5,100\n' +
  'heap-js-cons-item,Array,3,1000\n' +
  'heap-js-ret-item,foo,bar;3,Array:0x5678;1\n' +
  'heap-js-ret-item,bar,foo;5,Object:0x1234;8,Object:0x5678;2\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1,Object:0x5678;2\n' +
  'heap-js-ret-item,Object:0x5678,(global property);3,Object:0x1234;5\n' +
  'heap-js-ret-item,Array:0x5678,(global property);3,Array:0x5678;2\n',

  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,Object,6,120\n' +
  'heap-js-ret-item,bar,foo;5,Object:0x1234;1,Object:0x1235;3\n' +
  'heap-js-ret-item,Object:0x1234,(global property);3\n' +
  'heap-js-ret-item,Object:0x1235,(global property);5\n',

  'heap-js-cons-item,foo,15,1500\n' +
  'heap-js-cons-item,bar,15,1500\n' +
  'heap-js-cons-item,Array,10,1000\n' +
  'heap-js-ret-item,foo,bar;1,Array:0x5678;1\n' +
  'heap-js-ret-item,bar,foo;5\n' +
  'heap-js-ret-item,Array:0x5678,(roots);3\n',

  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,baz,15,1500\n' +
  'heap-js-ret-item,bar,baz;3\n' +
  'heap-js-ret-item,baz,bar;3\n'
];

/**
 * @constructor
 */
RemoteDebuggerCommandExecutorStub = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerCommand = function(cmd) {
  if ('{"seq":2,"type":"request","command":"scripts","arguments":{"' +
      'includeSource":false}}' == cmd) {
    var response1 =
        '{"seq":5,"request_seq":2,"type":"response","command":"scripts","' +
        'success":true,"body":[{"handle":61,"type":"script","name":"' +
        'http://www/~test/t.js","id":59,"lineOffset":0,"columnOffset":0,' +
        '"lineCount":1,"sourceStart":"function fib(n) {","sourceLength":300,' +
        '"scriptType":2,"compilationType":0,"context":{"ref":60}}],"refs":[{' +
        '"handle":60,"type":"context","data":"page,3"}],"running":false}';
    this.sendResponse_(response1);
  } else if ('{"seq":3,"type":"request","command":"scripts","arguments":{' +
             '"ids":[59],"includeSource":true}}' == cmd) {
    this.sendResponse_(
        '{"seq":8,"request_seq":3,"type":"response","command":"scripts",' +
        '"success":true,"body":[{"handle":1,"type":"script","name":' +
        '"http://www/~test/t.js","id":59,"lineOffset":0,"columnOffset":0,' +
        '"lineCount":1,"source":"function fib(n) {return n+1;}",' +
        '"sourceLength":244,"scriptType":2,"compilationType":0,"context":{' +
        '"ref":0}}],"refs":[{"handle":0,"type":"context","data":"page,3}],"' +
        '"running":false}');
  } else {
    debugPrint('Unexpected command: ' + cmd);
  }
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerPauseScript = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.sendResponse_ = function(response) {
  setTimeout(function() {
    RemoteDebuggerAgent.DebuggerOutput(response);
  }, 0);
};

/**
 * @constructor
 */
DevToolsHostStub = function() {
  this.isStub = true;
  window.domAutomationController = {
    send: function(text) {
        debugPrint(text);
    }
  };
};

function addDummyResource() {
  var payload = {
    requestHeaders : {},
    requestURL: 'http://google.com/simple_page.html',
    host: 'google.com',
    path: 'simple_page.html',
    lastPathComponent: 'simple_page.html',
    isMainResource: true,
    cached: false,
    mimeType: 'text/html',
    suggestedFilename: 'simple_page.html',
    expectedContentLength: 10000,
    statusCode: 200,
    contentLength: 10000,
    responseHeaders: {},
    type: WebInspector.Resource.Type.Document,
    finished: true,
    startTime: new Date(),

    didResponseChange: true,
    didCompletionChange: true,
    didTypeChange: true
  };

  WebInspector.addResource(1, payload);
  WebInspector.updateResource(1, payload);
}

DevToolsHostStub.prototype.loaded = function() {
  addDummyResource();
};

DevToolsHostStub.prototype.reset = function() {
};

DevToolsHostStub.prototype.getPlatform = function() {
  return "windows";
};

DevToolsHostStub.prototype.hiddenPanels = function() {
  return "";
};

DevToolsHostStub.prototype.addResourceSourceToFrame = function(
    identifier, mimeType, element) {
};

DevToolsHostStub.prototype.addSourceToFrame = function(mimeType, source,
    element) {
};

DevToolsHostStub.prototype.getApplicationLocale = function() {
  return "en-US";
};

if (!window['DevToolsHost']) {
  window['RemoteDebuggerAgent'] = new RemoteDebuggerAgentStub();
  window['RemoteDebuggerCommandExecutor'] =
      new RemoteDebuggerCommandExecutorStub();
  window['RemoteToolsAgent'] = new RemoteToolsAgentStub();
  window['DevToolsHost'] = new DevToolsHostStub();
}
<commit_msg>Add documentURL property to dummy resource payload<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview These stubs emulate backend functionality and allows
 * DevTools frontend to function as a standalone web app.
 */

/**
 * @constructor
 */
RemoteDebuggerAgentStub = function() {
  this.activeProfilerModules_ =
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_NONE;
  this.profileLogPos_ = 0;
  this.heapProfSample_ = 0;
  this.heapProfLog_ = '';
};

RemoteDebuggerAgentStub.prototype.GetContextId = function() {
  RemoteDebuggerAgent.SetContextId(3);
};

RemoteDebuggerAgentStub.prototype.StopProfiling = function(modules) {
  this.activeProfilerModules_ &= ~modules;
};

RemoteDebuggerAgentStub.prototype.StartProfiling = function(modules) {
  var profModules = devtools.DebuggerAgent.ProfilerModules;
  if (modules & profModules.PROFILER_MODULE_HEAP_SNAPSHOT) {
    if (modules & profModules.PROFILER_MODULE_HEAP_STATS) {
      this.heapProfLog_ +=
          'heap-sample-begin,"Heap","allocated",' +
              (new Date()).getTime() + '\n' +
          'heap-sample-stats,"Heap","allocated",10000,1000\n';
      this.heapProfLog_ +=
          'heap-sample-item,STRING_TYPE,100,1000\n' +
          'heap-sample-item,CODE_TYPE,10,200\n' +
          'heap-sample-item,MAP_TYPE,20,350\n';
      this.heapProfLog_ += RemoteDebuggerAgentStub.HeapSamples[this.heapProfSample_++];
      this.heapProfSample_ %= RemoteDebuggerAgentStub.HeapSamples.length;
      this.heapProfLog_ +=
          'heap-sample-end,"Heap","allocated"\n';
    }
  } else {
    this.activeProfilerModules_ |= modules;
  }
};

RemoteDebuggerAgentStub.prototype.GetActiveProfilerModules = function() {
  var self = this;
  setTimeout(function() {
      RemoteDebuggerAgent.DidGetActiveProfilerModules(
          self.activeProfilerModules_);
  }, 100);
};

RemoteDebuggerAgentStub.prototype.GetNextLogLines = function() {
  var profModules = devtools.DebuggerAgent.ProfilerModules;
  var logLines = '';
  if (this.activeProfilerModules_ & profModules.PROFILER_MODULE_CPU) {
    if (this.profileLogPos_ < RemoteDebuggerAgentStub.ProfilerLogBuffer.length) {
      this.profileLogPos_ += RemoteDebuggerAgentStub.ProfilerLogBuffer.length;
      logLines += RemoteDebuggerAgentStub.ProfilerLogBuffer;
    }
  }
  if (this.heapProfLog_) {
    logLines += this.heapProfLog_;
    this.heapProfLog_ = '';
  }
  setTimeout(function() {
    RemoteDebuggerAgent.DidGetNextLogLines(logLines);
  }, 100);
};

/**
 * @constructor
 */
RemoteToolsAgentStub = function() {
};

RemoteToolsAgentStub.prototype.DispatchOnInjectedScript = function() {
};

RemoteToolsAgentStub.prototype.DispatchOnInspectorController = function() {
};

RemoteToolsAgentStub.prototype.ExecuteVoidJavaScript = function() {
};

RemoteDebuggerAgentStub.ProfilerLogBuffer =
  'profiler,begin,1\n' +
  'profiler,resume\n' +
  'code-creation,LazyCompile,0x1000,256,"test1 http://aaa.js:1"\n' +
  'code-creation,LazyCompile,0x2000,256,"test2 http://bbb.js:2"\n' +
  'code-creation,LazyCompile,0x3000,256,"test3 http://ccc.js:3"\n' +
  'tick,0x1010,0x0,3\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x3010,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2030,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x1010,0x0,3\n' +
  'profiler,pause\n';

RemoteDebuggerAgentStub.HeapSamples = [
  'heap-js-cons-item,foo,1,100\n' +
  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,Object,5,100\n' +
  'heap-js-ret-item,foo,bar;3\n' +
  'heap-js-ret-item,bar,foo;5\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1\n',

  'heap-js-cons-item,foo,2000,200000\n' +
  'heap-js-cons-item,bar,10,1000\n' +
  'heap-js-cons-item,Object,6,120\n' +
  'heap-js-ret-item,foo,bar;7,Object:0x1234;10\n' +
  'heap-js-ret-item,bar,foo;10,Object:0x1234;10\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1\n',

  'heap-js-cons-item,foo,15,1500\n' +
  'heap-js-cons-item,bar,15,1500\n' +
  'heap-js-cons-item,Object,5,100\n' +
  'heap-js-cons-item,Array,3,1000\n' +
  'heap-js-ret-item,foo,bar;3,Array:0x5678;1\n' +
  'heap-js-ret-item,bar,foo;5,Object:0x1234;8,Object:0x5678;2\n' +
  'heap-js-ret-item,Object:0x1234,(roots);1,Object:0x5678;2\n' +
  'heap-js-ret-item,Object:0x5678,(global property);3,Object:0x1234;5\n' +
  'heap-js-ret-item,Array:0x5678,(global property);3,Array:0x5678;2\n',

  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,Object,6,120\n' +
  'heap-js-ret-item,bar,foo;5,Object:0x1234;1,Object:0x1235;3\n' +
  'heap-js-ret-item,Object:0x1234,(global property);3\n' +
  'heap-js-ret-item,Object:0x1235,(global property);5\n',

  'heap-js-cons-item,foo,15,1500\n' +
  'heap-js-cons-item,bar,15,1500\n' +
  'heap-js-cons-item,Array,10,1000\n' +
  'heap-js-ret-item,foo,bar;1,Array:0x5678;1\n' +
  'heap-js-ret-item,bar,foo;5\n' +
  'heap-js-ret-item,Array:0x5678,(roots);3\n',

  'heap-js-cons-item,bar,20,2000\n' +
  'heap-js-cons-item,baz,15,1500\n' +
  'heap-js-ret-item,bar,baz;3\n' +
  'heap-js-ret-item,baz,bar;3\n'
];

/**
 * @constructor
 */
RemoteDebuggerCommandExecutorStub = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerCommand = function(cmd) {
  if ('{"seq":2,"type":"request","command":"scripts","arguments":{"' +
      'includeSource":false}}' == cmd) {
    var response1 =
        '{"seq":5,"request_seq":2,"type":"response","command":"scripts","' +
        'success":true,"body":[{"handle":61,"type":"script","name":"' +
        'http://www/~test/t.js","id":59,"lineOffset":0,"columnOffset":0,' +
        '"lineCount":1,"sourceStart":"function fib(n) {","sourceLength":300,' +
        '"scriptType":2,"compilationType":0,"context":{"ref":60}}],"refs":[{' +
        '"handle":60,"type":"context","data":"page,3"}],"running":false}';
    this.sendResponse_(response1);
  } else if ('{"seq":3,"type":"request","command":"scripts","arguments":{' +
             '"ids":[59],"includeSource":true}}' == cmd) {
    this.sendResponse_(
        '{"seq":8,"request_seq":3,"type":"response","command":"scripts",' +
        '"success":true,"body":[{"handle":1,"type":"script","name":' +
        '"http://www/~test/t.js","id":59,"lineOffset":0,"columnOffset":0,' +
        '"lineCount":1,"source":"function fib(n) {return n+1;}",' +
        '"sourceLength":244,"scriptType":2,"compilationType":0,"context":{' +
        '"ref":0}}],"refs":[{"handle":0,"type":"context","data":"page,3}],"' +
        '"running":false}');
  } else {
    debugPrint('Unexpected command: ' + cmd);
  }
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerPauseScript = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.sendResponse_ = function(response) {
  setTimeout(function() {
    RemoteDebuggerAgent.DebuggerOutput(response);
  }, 0);
};

/**
 * @constructor
 */
DevToolsHostStub = function() {
  this.isStub = true;
  window.domAutomationController = {
    send: function(text) {
        debugPrint(text);
    }
  };
};

function addDummyResource() {
  var payload = {
    requestHeaders : {},
    requestURL: 'http://google.com/simple_page.html',
    host: 'google.com',
    documentURL: 'http://google.com/simple_page.html',
    path: 'simple_page.html',
    lastPathComponent: 'simple_page.html',
    isMainResource: true,
    cached: false,
    mimeType: 'text/html',
    suggestedFilename: 'simple_page.html',
    expectedContentLength: 10000,
    statusCode: 200,
    contentLength: 10000,
    responseHeaders: {},
    type: WebInspector.Resource.Type.Document,
    finished: true,
    startTime: new Date(),

    didResponseChange: true,
    didCompletionChange: true,
    didTypeChange: true
  };

  WebInspector.addResource(1, payload);
  WebInspector.updateResource(1, payload);
}

DevToolsHostStub.prototype.loaded = function() {
  addDummyResource();
};

DevToolsHostStub.prototype.reset = function() {
};

DevToolsHostStub.prototype.getPlatform = function() {
  return "windows";
};

DevToolsHostStub.prototype.hiddenPanels = function() {
  return "";
};

DevToolsHostStub.prototype.addResourceSourceToFrame = function(
    identifier, mimeType, element) {
};

DevToolsHostStub.prototype.addSourceToFrame = function(mimeType, source,
    element) {
};

DevToolsHostStub.prototype.getApplicationLocale = function() {
  return "en-US";
};

if (!window['DevToolsHost']) {
  window['RemoteDebuggerAgent'] = new RemoteDebuggerAgentStub();
  window['RemoteDebuggerCommandExecutor'] =
      new RemoteDebuggerCommandExecutorStub();
  window['RemoteToolsAgent'] = new RemoteToolsAgentStub();
  window['DevToolsHost'] = new DevToolsHostStub();
}
<|endoftext|>


<commit_before>'use strict'

var write = require('../write')
var fastfall = require('fastfall')
var Packet = require('aedes-packet')
var through = require('through2')
var topicActions = fastfall([
  authorize,
  storeSubscriptions,
  subTopic
])

function SubscribeState (client, packet, finish, granted) {
  this.client = client
  this.packet = packet
  this.finish = finish
  this.granted = granted
}

function handleSubscribe (client, packet, done) {
  var broker = client.broker
  var subs = packet.subscriptions
  var granted = []

  broker._parallel(
    new SubscribeState(client, packet, done, granted),
    doSubscribe,
    subs,
    completeSubscribe)
}

function doSubscribe (sub, done) {
  // TODO this function should not be needed
  topicActions.call(this, sub, done)
}

function authorize (sub, done) {
  var client = this.client
  client.broker.authorizeSubscribe(client, sub, done)
}

function blockSys (func) {
  return function deliverSharp (packet, cb) {
    if (packet.topic.indexOf('$SYS') === 0) {
      cb()
    } else {
      func(packet, cb)
    }
  }
}

function Subscription (qos, func) {
  this.qos = qos
  this.func = func
}

function storeSubscriptions (sub, done) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var perst = broker.persistence

  if (sub && packet.subscriptions[0].topic !== sub.topic) {
    // don't call addSubscriptions per topic,
    // TODO change aedes subscribe handle, but this is a fast & dirty fix for now
    return done(null, sub)
  }

  if (packet.restore) {
    return done(null, sub)
  }

  perst.addSubscriptions(client, packet.subscriptions, function (err) {
    done(err, sub)
  })
}

function subTopic (sub, done) {
  if (!sub) {
    this.granted.push(128)
    return done()
  }

  var client = this.client
  var broker = client.broker
  var func = nop

  switch (sub.qos) {
    case 2:
    case 1:
      func = client.deliverQoS
      break
    default:
      func = client.deliver0
      break
  }

  if (sub.topic === '#') {
    func = blockSys(func)
  }

  this.granted.push(sub.qos)

  if (!client.subscriptions[sub.topic]) {
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else if (client.subscriptions[sub.topic].qos !== sub.qos) {
    broker.unsubscribe(sub.topic, client.subscriptions[sub.topic].func)
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else {
    done()
  }
}

function completeSubscribe (err) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var granted = this.granted
  var done = this.finish

  if (err) {
    return done(err)
  }

  if (!packet.restore) {
    broker.emit('subscribe', packet.subscriptions, client)
  }

  if (packet.messageId) {
    write(client, new SubAck(packet, granted), done)
  } else {
    done()
  }

  var persistence = broker.persistence
  var topics = packet.subscriptions.map(function (s) { return s.topic })
  var stream = persistence.createRetainedStreamCombi(topics)
  stream.pipe(through.obj(function sendRetained (packet, enc, cb) {
    packet = new Packet(packet)
    // this should not be deduped
    packet.brokerId = null
    client.deliver0(packet, cb)
  }))
}

function SubAck (packet, granted) {
  this.cmd = 'suback'
  this.messageId = packet.messageId
  this.granted = granted
}

function nop () {}

module.exports = handleSubscribe
<commit_msg>change map to for loop<commit_after>'use strict'

var write = require('../write')
var fastfall = require('fastfall')
var Packet = require('aedes-packet')
var through = require('through2')
var topicActions = fastfall([
  authorize,
  storeSubscriptions,
  subTopic
])

function SubscribeState (client, packet, finish, granted) {
  this.client = client
  this.packet = packet
  this.finish = finish
  this.granted = granted
}

function handleSubscribe (client, packet, done) {
  var broker = client.broker
  var subs = packet.subscriptions
  var granted = []

  broker._parallel(
    new SubscribeState(client, packet, done, granted),
    doSubscribe,
    subs,
    completeSubscribe)
}

function doSubscribe (sub, done) {
  // TODO this function should not be needed
  topicActions.call(this, sub, done)
}

function authorize (sub, done) {
  var client = this.client
  client.broker.authorizeSubscribe(client, sub, done)
}

function blockSys (func) {
  return function deliverSharp (packet, cb) {
    if (packet.topic.indexOf('$SYS') === 0) {
      cb()
    } else {
      func(packet, cb)
    }
  }
}

function Subscription (qos, func) {
  this.qos = qos
  this.func = func
}

function storeSubscriptions (sub, done) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var perst = broker.persistence

  if (sub && packet.subscriptions[0].topic !== sub.topic) {
    // don't call addSubscriptions per topic,
    // TODO change aedes subscribe handle, but this is a fast & dirty fix for now
    return done(null, sub)
  }

  if (packet.restore) {
    return done(null, sub)
  }

  perst.addSubscriptions(client, packet.subscriptions, function (err) {
    done(err, sub)
  })
}

function subTopic (sub, done) {
  if (!sub) {
    this.granted.push(128)
    return done()
  }

  var client = this.client
  var broker = client.broker
  var func = nop

  switch (sub.qos) {
    case 2:
    case 1:
      func = client.deliverQoS
      break
    default:
      func = client.deliver0
      break
  }

  if (sub.topic === '#') {
    func = blockSys(func)
  }

  this.granted.push(sub.qos)

  if (!client.subscriptions[sub.topic]) {
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else if (client.subscriptions[sub.topic].qos !== sub.qos) {
    broker.unsubscribe(sub.topic, client.subscriptions[sub.topic].func)
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else {
    done()
  }
}

function completeSubscribe (err) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var granted = this.granted
  var done = this.finish

  if (err) {
    return done(err)
  }

  if (!packet.restore) {
    broker.emit('subscribe', packet.subscriptions, client)
  }

  if (packet.messageId) {
    write(client, new SubAck(packet, granted), done)
  } else {
    done()
  }

  var persistence = broker.persistence
  var topics = []
  for (var i = 0; i < packet.subscriptions.length; i++) {
    topics.push(packet.subscriptions[i].topic)
  }
  var stream = persistence.createRetainedStreamCombi(topics)
  stream.pipe(through.obj(function sendRetained (packet, enc, cb) {
    packet = new Packet(packet)
    // this should not be deduped
    packet.brokerId = null
    client.deliver0(packet, cb)
  }))
}

function SubAck (packet, granted) {
  this.cmd = 'suback'
  this.messageId = packet.messageId
  this.granted = granted
}

function nop () {}

module.exports = handleSubscribe
<|endoftext|>


<commit_before>/*
 * NTwitBot - util.js
 * Copyright (C) 2016-2017 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* eslint no-unused-vars: 'off' */
/* eslint no-console: 'off' */

const colors = require('colors'),
      fs     = require('fs');

/**
 * Utilities class. Contains logging and helper methods.
 */
module.exports = class Util {

    constructor() {
        this.debug = false;
    }

    /**
     * Logs a normal message to console.
     * @param {string} message - The message to log.
     */
    log(message) {
        if (process.env.NODE_ENV !== 'test') {
            console.log(this.getFormattedTime() + ' ' + ' INFO '.black.bgWhite + ' %s', message);
        }
    }

    /**
     * Logs an error message to console.
     * @param {string} message - The message to log.
     * @param {Error} [error] - An optional Error object to log the details of.
     */
    logError(message, error) {
        if (process.env.NODE_ENV !== 'test') {
            console.error(this.getFormattedTime() + ' ' + ' ERROR '.black.bgRed + ' %s'.red, message);

            if (error) {
                console.error(this.getFormattedTime() + ' ' + ' ERROR '.black.bgRed + '     %s'.red, error.stack);
            }
        }
    }

    /**
     * Logs a debug message to console.
     * @param {string} message - The message to log.
     */
    logDebug(message) {
        if (process.env.NODE_ENV !== 'test' && this.debug) {
            console.log(this.getFormattedTime() + ' ' + ' DEBUG '.black.bgCyan + ' %s'.cyan, message);
        }
    }

    /**
     * Sets the debug flag for logging.
     * @param {boolean} debug - The new status of the debug flag.
     */
    setDebug(debug) {
        this.debug = debug;

        if (debug) {
            this.logDebug('Debug flag set');
        }
    }

    /**
     * Gets the current date & time to the minute.
     * @return {int} The current time in form: YYYYMMDDhhmm
     */
    getTime() {
        let result = '';
        const date = new Date();

        const year = date.getFullYear();
        result += year;

        const month = date.getMonth() + 1;
        result += (month < 10 ? '0' : '') + month;

        const day = date.getDate();
        result += (day < 10 ? '0' : '') + day;

        const hour = date.getHours();
        result += (hour < 10 ? '0' : '') + hour;

        const minute = date.getMinutes();
        result += (minute < 10 ? '0' : '') + minute;

        return parseInt(result);
    }

    /**
     * Gets the current date & time to the second.
     * @return {string} The current time in form: 'MM/DD/YYYY hh:mm:ss'
     */
    getFormattedTime() {
        let result = '';
        const date = new Date();

        const month = date.getMonth() + 1;
        result += (month < 10 ? '0' : '') + month + '/';

        const day = date.getDate();
        result += (day < 10 ? '0' : '') + day + '/';

        const year = date.getFullYear();
        result += year + ' ';

        const hour = date.getHours();
        result += (hour < 10 ? '0' : '') + hour + ':';

        const minute = date.getMinutes();
        result += (minute < 10 ? '0' : '') + minute + ':';

        const seconds = date.getSeconds();
        result += (seconds < 10 ? '0' : '') + seconds;

        return result;
    }

    /**
     * Capitalizes the first letter of a word.
     * @param {string} word - The word to capitalize.
     * @return {string} The capitalized word.
     */
    capitalize(word) {
        return word.charAt(0).toUpperCase() + word.slice(1);
    }

    /**
     * Checks if a character in upper case.
     * @param {char} char - The letter to check.
     * @return {boolean} True if the character is upper case.
     */
    isUpperCase(char) {
        return char == char.toUpperCase();
    }

    /**
     * Check if an object is in an array.
     * @param {Array} array - The array to check.
     * @param {Object} object - The object to check.
     * @return {boolean} True if object in in the array.
     */
    isInArray(array, object) {
        return array.indexOf(object) !== -1;
    }

    /**
     * Generates an array with elements 0 to n - 1 elements of length n in random order.
     * @param {int} n - The length of the array.
     * @return {Array} The randomly shuffled array.
     */
    generateShuffledArray(n) {
        let array = [];

        // Initialize the array
        for (let i = 0; i < n; i++) {
            array.push(i);
        }

        return this.shuffleArray(array);
    }

    /**
     * Shuffles the elements of an array. Does not alter original array.
     * @param {Array} array - The array to shuffle.
     * @return {Array} The shuffled array.
     */
    shuffleArray(array) {
        const shuffleArray = array.slice(0);
        let swap, temp;

        for (let i = shuffleArray.length; i > 0; i--) {
            swap = Math.floor(Math.random() * i);
            temp = shuffleArray[i - 1];
            shuffleArray[i - 1] = shuffleArray[swap];
            shuffleArray[swap] = temp;
        }

        return shuffleArray;
    }

    /**
     * Check if the end of a string ends with a punctuation symbol.
     * @param {string} string - The string to check.
     * @return {boolean} True if the string ends with a punctuation symbol.
     */
    endsWithPunc(string) {
        return string.endsWith('.') || string.endsWith('!') || string.endsWith('?');
    }

};
<commit_msg>Only ignore 'colors' require for ESLint unused-vars in utils<commit_after>/*
 * NTwitBot - util.js
 * Copyright (C) 2016-2017 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* eslint no-unused-vars: ['error', { 'varsIgnorePattern': 'colors' }] */
/* eslint no-console: 'off' */

const colors = require('colors');

/**
 * Utilities class. Contains logging and helper methods.
 */
module.exports = class Util {

    constructor() {
        this.debug = false;
    }

    /**
     * Logs a normal message to console.
     * @param {string} message - The message to log.
     */
    log(message) {
        if (process.env.NODE_ENV !== 'test') {
            console.log(this.getFormattedTime() + ' ' + ' INFO '.black.bgWhite + ' %s', message);
        }
    }

    /**
     * Logs an error message to console.
     * @param {string} message - The message to log.
     * @param {Error} [error] - An optional Error object to log the details of.
     */
    logError(message, error) {
        if (process.env.NODE_ENV !== 'test') {
            console.error(this.getFormattedTime() + ' ' + ' ERROR '.black.bgRed + ' %s'.red, message);

            if (error) {
                console.error(this.getFormattedTime() + ' ' + ' ERROR '.black.bgRed + '     %s'.red, error.stack);
            }
        }
    }

    /**
     * Logs a debug message to console.
     * @param {string} message - The message to log.
     */
    logDebug(message) {
        if (process.env.NODE_ENV !== 'test' && this.debug) {
            console.log(this.getFormattedTime() + ' ' + ' DEBUG '.black.bgCyan + ' %s'.cyan, message);
        }
    }

    /**
     * Sets the debug flag for logging.
     * @param {boolean} debug - The new status of the debug flag.
     */
    setDebug(debug) {
        this.debug = debug;

        if (debug) {
            this.logDebug('Debug flag set');
        }
    }

    /**
     * Gets the current date & time to the minute.
     * @return {int} The current time in form: YYYYMMDDhhmm
     */
    getTime() {
        let result = '';
        const date = new Date();

        const year = date.getFullYear();
        result += year;

        const month = date.getMonth() + 1;
        result += (month < 10 ? '0' : '') + month;

        const day = date.getDate();
        result += (day < 10 ? '0' : '') + day;

        const hour = date.getHours();
        result += (hour < 10 ? '0' : '') + hour;

        const minute = date.getMinutes();
        result += (minute < 10 ? '0' : '') + minute;

        return parseInt(result);
    }

    /**
     * Gets the current date & time to the second.
     * @return {string} The current time in form: 'MM/DD/YYYY hh:mm:ss'
     */
    getFormattedTime() {
        let result = '';
        const date = new Date();

        const month = date.getMonth() + 1;
        result += (month < 10 ? '0' : '') + month + '/';

        const day = date.getDate();
        result += (day < 10 ? '0' : '') + day + '/';

        const year = date.getFullYear();
        result += year + ' ';

        const hour = date.getHours();
        result += (hour < 10 ? '0' : '') + hour + ':';

        const minute = date.getMinutes();
        result += (minute < 10 ? '0' : '') + minute + ':';

        const seconds = date.getSeconds();
        result += (seconds < 10 ? '0' : '') + seconds;

        return result;
    }

    /**
     * Capitalizes the first letter of a word.
     * @param {string} word - The word to capitalize.
     * @return {string} The capitalized word.
     */
    capitalize(word) {
        return word.charAt(0).toUpperCase() + word.slice(1);
    }

    /**
     * Checks if a character in upper case.
     * @param {char} char - The letter to check.
     * @return {boolean} True if the character is upper case.
     */
    isUpperCase(char) {
        return char == char.toUpperCase();
    }

    /**
     * Check if an object is in an array.
     * @param {Array} array - The array to check.
     * @param {Object} object - The object to check.
     * @return {boolean} True if object in in the array.
     */
    isInArray(array, object) {
        return array.indexOf(object) !== -1;
    }

    /**
     * Generates an array with elements 0 to n - 1 elements of length n in random order.
     * @param {int} n - The length of the array.
     * @return {Array} The randomly shuffled array.
     */
    generateShuffledArray(n) {
        let array = [];

        // Initialize the array
        for (let i = 0; i < n; i++) {
            array.push(i);
        }

        return this.shuffleArray(array);
    }

    /**
     * Shuffles the elements of an array. Does not alter original array.
     * @param {Array} array - The array to shuffle.
     * @return {Array} The shuffled array.
     */
    shuffleArray(array) {
        const shuffleArray = array.slice(0);
        let swap, temp;

        for (let i = shuffleArray.length; i > 0; i--) {
            swap = Math.floor(Math.random() * i);
            temp = shuffleArray[i - 1];
            shuffleArray[i - 1] = shuffleArray[swap];
            shuffleArray[swap] = temp;
        }

        return shuffleArray;
    }

    /**
     * Check if the end of a string ends with a punctuation symbol.
     * @param {string} string - The string to check.
     * @return {boolean} True if the string ends with a punctuation symbol.
     */
    endsWithPunc(string) {
        return string.endsWith('.') || string.endsWith('!') || string.endsWith('?');
    }

};
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview These stubs emulate backend functionality and allows
 * DevTools frontend to function as a standalone web app.
 */

/**
 * @constructor
 */
RemoteDebuggerAgentStub = function() {
  this.isProfiling_ = false;
  this.profileLogPos_ = 0;
};

RemoteDebuggerAgentStub.prototype.DebugBreak = function() {
};

RemoteDebuggerAgentStub.prototype.GetContextId = function() {
  RemoteDebuggerAgent.DidGetContextId(3);
};

RemoteDebuggerAgentStub.prototype.StopProfiling = function() {
  this.isProfiling_ = false;
};

RemoteDebuggerAgentStub.prototype.StartProfiling = function() {
  this.isProfiling_ = true;
};

RemoteDebuggerAgentStub.prototype.IsProfilingStarted = function() {
  var self = this;
  setTimeout(function() {
      RemoteDebuggerAgent.DidIsProfilingStarted(self.isProfiling_);
  }, 100);
};

RemoteDebuggerAgentStub.prototype.GetNextLogLines = function() {
  if (this.profileLogPos_ < RemoteDebuggerAgentStub.ProfilerLogBuffer.length) {
    this.profileLogPos_ += RemoteDebuggerAgentStub.ProfilerLogBuffer.length;
    setTimeout(function() {
        RemoteDebuggerAgent.DidGetNextLogLines(
            RemoteDebuggerAgentStub.ProfilerLogBuffer);
        },
        100);
  } else {
    setTimeout(function() { RemoteDebuggerAgent.DidGetNextLogLines(''); }, 100);
  }
};

/**
 * @constructor
 */
RemoteDomAgentStub = function() {
};

RemoteDomAgentStub.sendDocumentElement_ = function() {
  RemoteDomAgent.SetDocumentElement([
    1,       // id
    1,       // type = Node.ELEMENT_NODE,
    'HTML',  // nodeName
    '',      // nodeValue
    ['foo','bar'],  // attributes
    2,       // childNodeCount
  ]);
};

RemoteDomAgentStub.sendChildNodes_ = function(id) {
  if (id == 1) {
    RemoteDomAgent.SetChildNodes(id,
      [
        [
         2,       // id
         1,       // type = Node.ELEMENT_NODE,
         'DIV',   // nodeName
         '',      // nodeValue
         ['foo','bar'],  // attributes
         1,       // childNodeCount
        ],
        [
         3,  // id
         3,  // type = Node.TEXT_NODE,
         '', // nodeName
         'Text', // nodeValue
        ]
      ]);
  } else if (id == 2) {
    RemoteDomAgent.SetChildNodes(id,
      [
        [
        4,       // id
        1,       // type = Node.ELEMENT_NODE,
        'span',   // nodeName
        '',      // nodeValue
        ['foo','bar'],  // attributes
        0,       // childNodeCount
      ]
    ]);
  }
};

RemoteDomAgentStub.prototype.GetDocumentElement = function(callId) {
  setTimeout(function() {
    RemoteDomAgentStub.sendDocumentElement_();
  }, 0);
};

RemoteDomAgentStub.prototype.GetChildNodes = function(callId, id) {
  setTimeout(function() {
    RemoteDomAgentStub.sendChildNodes_(id);
    RemoteDomAgent.DidGetChildNodes(callId);
  }, 0);
};

RemoteDomAgentStub.prototype.SetAttribute = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.RemoveAttribute = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.SetTextNodeValue = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.PerformSearch = function(callId, query) {
  setTimeout(function() {
    RemoteDomAgent.DidPerformSearch(callId, [1]);
  }, 0);
};

RemoteDomAgentStub.prototype.DiscardBindings = function() {
};

/**
 * @constructor
 */
RemoteToolsAgentStub = function() {
};

RemoteToolsAgentStub.prototype.HideDOMNodeHighlight = function() {
};

RemoteToolsAgentStub.prototype.HighlightDOMNode = function() {
};

RemoteToolsAgentStub.prototype.evaluate = function(expr) {
  window.eval(expr);
};

RemoteToolsAgentStub.prototype.EvaluateJavaScript = function(callId, script) {
  setTimeout(function() {
    var result = eval(script);
    RemoteToolsAgent.DidEvaluateJavaScript(callId, result);
  }, 0);
};

RemoteToolsAgentStub.prototype.ExecuteUtilityFunction = function(callId,
    functionName, nodeId, args) {
  setTimeout(function() {
    var result = [];
    if (functionName == 'getProperties') {
      result = [
        'undefined', 'undefined_key', undefined,
        'string', 'string_key', 'value',
        'function', 'func', undefined,
        'array', 'array_key', [10],
        'object', 'object_key', undefined,
        'boolean', 'boolean_key', true,
        'number', 'num_key', 911,
        'date', 'date_key', new Date() ];
    } else if (functionName == 'getPrototypes') {
      result = ['Proto1', 'Proto2', 'Proto3'];
    } else if (functionName == 'getStyles') {
      result = {
        'computedStyle' : [0, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
        'inlineStyle' : [1, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
        'styleAttributes' : {
           attr: [2, '0px', '0px', null, null, null, ['display', false, false, '', 'none']]
        },
        'matchedCSSRules' : [
          { 'selector' : 'S',
            'style' : [3, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
            'parentStyleSheet' : { 'href' : 'http://localhost',
                                   'ownerNodeName' : 'DIV' }
          }
        ]
      };
    } else if (functionName == 'toggleNodeStyle' ||
        functionName == 'applyStyleText' ||
        functionName == 'setStyleProperty') {
      alert(functionName + '(' + nodeId + ', ' + args + ')');
    } else {
      alert('Unexpected utility function:' + functionName);
    }
    RemoteToolsAgent.DidExecuteUtilityFunction(callId,
        JSON.stringify(result), '');
  }, 0);
};

RemoteToolsAgentStub.prototype.GetNodePrototypes = function(callId, nodeId) {
  setTimeout(function() {
    RemoteToolsAgent.DidGetNodePrototypes(callId,
        JSON.stringify());
  }, 0);
};

RemoteToolsAgentStub.prototype.ClearConsoleMessages = function() {
};

RemoteToolsAgentStub.prototype.SetResourceTrackingEnabled = function(enabled, always) {
  RemoteToolsAgent.SetResourcesPanelEnabled(enabled);
  if (enabled) {
    WebInspector.resourceTrackingWasEnabled();
  } else {
    WebInspector.resourceTrackingWasDisabled();
  }
  addDummyResource();
};

RemoteDebuggerAgentStub.ProfilerLogBuffer =
  'profiler,begin,1\n' +
  'profiler,resume\n' +
  'code-creation,LazyCompile,0x1000,256,"test1 http://aaa.js:1"\n' +
  'code-creation,LazyCompile,0x2000,256,"test2 http://bbb.js:2"\n' +
  'code-creation,LazyCompile,0x3000,256,"test3 http://ccc.js:3"\n' +
  'tick,0x1010,0x0,3\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x3010,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2030,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x1010,0x0,3\n' +
  'profiler,pause\n';

/**
 * @constructor
 */
RemoteDebuggerCommandExecutorStub = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerCommand = function(cmd) {
};

/**
 * @constructor
 */
DevToolsHostStub = function() {
  this.isStub = true;
  window.domAutomationController = {
    send: function(text) {
        debugPrint(text);
    }
  };
};

function addDummyResource() {
  var payload = {
    requestHeaders : {},
    requestURL: 'http://google.com/simple_page.html',
    host: 'google.com',
    path: 'simple_page.html',
    lastPathComponent: 'simple_page.html',
    isMainResource: true,
    cached: false,
    mimeType: 'text/html',
    suggestedFilename: 'simple_page.html',
    expectedContentLength: 10000,
    statusCode: 200,
    contentLength: 10000,
    responseHeaders: {},
    type: WebInspector.Resource.Type.Document,
    finished: true,
    startTime: new Date(),

    didResponseChange: true,
    didCompletionChange: true,
    didTypeChange: true
  };

  WebInspector.addResource(1, payload);
  WebInspector.updateResource(1, payload);
}

DevToolsHostStub.prototype.loaded = function() {
  RemoteDomAgentStub.sendDocumentElement_();
  RemoteDomAgentStub.sendChildNodes_(1);
  RemoteDomAgentStub.sendChildNodes_(2);
  devtools.tools.updateFocusedNode_(4);
  addDummyResource();

  uiTests.runAllTests();
};

DevToolsHostStub.prototype.reset = function() {
};

DevToolsHostStub.prototype.getPlatform = function() {
  return "windows";
};

DevToolsHostStub.prototype.addResourceSourceToFrame = function(
    identifier, mimeType, element) {
};

if (!window['DevToolsHost']) {
  window['RemoteDebuggerAgent'] = new RemoteDebuggerAgentStub();
  window['RemoteDebuggerCommandExecutor'] =
      new RemoteDebuggerCommandExecutorStub();
  window['RemoteDomAgent'] = new RemoteDomAgentStub();
  window['RemoteToolsAgent'] = new RemoteToolsAgentStub();
  window['DevToolsHost'] = new DevToolsHostStub();
}
<commit_msg>DevTools: Fix standalone devtools app mode.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview These stubs emulate backend functionality and allows
 * DevTools frontend to function as a standalone web app.
 */

/**
 * @constructor
 */
RemoteDebuggerAgentStub = function() {
  this.isProfiling_ = false;
  this.profileLogPos_ = 0;
};

RemoteDebuggerAgentStub.prototype.DebugBreak = function() {
};

RemoteDebuggerAgentStub.prototype.GetContextId = function() {
  RemoteDebuggerAgent.DidGetContextId(3);
};

RemoteDebuggerAgentStub.prototype.StopProfiling = function() {
  this.isProfiling_ = false;
};

RemoteDebuggerAgentStub.prototype.StartProfiling = function() {
  this.isProfiling_ = true;
};

RemoteDebuggerAgentStub.prototype.IsProfilingStarted = function() {
  var self = this;
  setTimeout(function() {
      RemoteDebuggerAgent.DidIsProfilingStarted(self.isProfiling_);
  }, 100);
};

RemoteDebuggerAgentStub.prototype.GetNextLogLines = function() {
  if (this.profileLogPos_ < RemoteDebuggerAgentStub.ProfilerLogBuffer.length) {
    this.profileLogPos_ += RemoteDebuggerAgentStub.ProfilerLogBuffer.length;
    setTimeout(function() {
        RemoteDebuggerAgent.DidGetNextLogLines(
            RemoteDebuggerAgentStub.ProfilerLogBuffer);
        },
        100);
  } else {
    setTimeout(function() { RemoteDebuggerAgent.DidGetNextLogLines(''); }, 100);
  }
};

/**
 * @constructor
 */
RemoteDomAgentStub = function() {
};

RemoteDomAgentStub.sendDocumentElement_ = function() {
  RemoteDomAgent.SetDocumentElement([
    1,       // id
    1,       // type = Node.ELEMENT_NODE,
    'HTML',  // nodeName
    '',      // nodeValue
    ['foo','bar'],  // attributes
    2,       // childNodeCount
  ]);
};

RemoteDomAgentStub.sendChildNodes_ = function(id) {
  if (id == 1) {
    RemoteDomAgent.SetChildNodes(id,
      [
        [
         2,       // id
         1,       // type = Node.ELEMENT_NODE,
         'DIV',   // nodeName
         '',      // nodeValue
         ['foo','bar'],  // attributes
         1,       // childNodeCount
        ],
        [
         3,  // id
         3,  // type = Node.TEXT_NODE,
         '', // nodeName
         'Text', // nodeValue
        ]
      ]);
  } else if (id == 2) {
    RemoteDomAgent.SetChildNodes(id,
      [
        [
        4,       // id
        1,       // type = Node.ELEMENT_NODE,
        'span',   // nodeName
        '',      // nodeValue
        ['foo','bar'],  // attributes
        0,       // childNodeCount
      ]
    ]);
  }
};

RemoteDomAgentStub.prototype.GetDocumentElement = function(callId) {
  setTimeout(function() {
    RemoteDomAgentStub.sendDocumentElement_();
  }, 0);
};

RemoteDomAgentStub.prototype.GetChildNodes = function(callId, id) {
  setTimeout(function() {
    RemoteDomAgentStub.sendChildNodes_(id);
    RemoteDomAgent.DidGetChildNodes(callId);
  }, 0);
};

RemoteDomAgentStub.prototype.SetAttribute = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.RemoveAttribute = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.SetTextNodeValue = function(callId) {
  setTimeout(function() {
    RemoteDomAgent.DidApplyDomChange(callId, true);
  }, 0);
};

RemoteDomAgentStub.prototype.PerformSearch = function(callId, query) {
  setTimeout(function() {
    RemoteDomAgent.DidPerformSearch(callId, [1]);
  }, 0);
};

RemoteDomAgentStub.prototype.DiscardBindings = function() {
};

/**
 * @constructor
 */
RemoteToolsAgentStub = function() {
};

RemoteToolsAgentStub.prototype.HideDOMNodeHighlight = function() {
};

RemoteToolsAgentStub.prototype.HighlightDOMNode = function() {
};

RemoteToolsAgentStub.prototype.evaluate = function(expr) {
  window.eval(expr);
};

RemoteToolsAgentStub.prototype.EvaluateJavaScript = function(callId, script) {
  setTimeout(function() {
    var result = eval(script);
    RemoteToolsAgent.DidEvaluateJavaScript(callId, result);
  }, 0);
};

RemoteToolsAgentStub.prototype.ExecuteUtilityFunction = function(callId,
    functionName, args) {
  setTimeout(function() {
    var result = [];
    if (functionName == 'getProperties') {
      result = [
        'undefined', 'undefined_key', undefined,
        'string', 'string_key', 'value',
        'function', 'func', undefined,
        'array', 'array_key', [10],
        'object', 'object_key', undefined,
        'boolean', 'boolean_key', true,
        'number', 'num_key', 911,
        'date', 'date_key', new Date() ];
    } else if (functionName == 'getPrototypes') {
      result = ['Proto1', 'Proto2', 'Proto3'];
    } else if (functionName == 'getStyles') {
      result = {
        'computedStyle' : [0, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
        'inlineStyle' : [1, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
        'styleAttributes' : {
           attr: [2, '0px', '0px', null, null, null, ['display', false, false, '', 'none']]
        },
        'matchedCSSRules' : [
          { 'selector' : 'S',
            'style' : [3, '0px', '0px', null, null, null, ['display', false, false, '', 'none']],
            'parentStyleSheet' : { 'href' : 'http://localhost',
                                   'ownerNodeName' : 'DIV' }
          }
        ]
      };
    } else if (functionName == 'toggleNodeStyle' ||
        functionName == 'applyStyleText' ||
        functionName == 'setStyleProperty') {
      alert(functionName + '(' + args + ')');
    } else if (functionName == 'evaluate') {
      try {
        result = [ window.eval(JSON.parse(args)[0]), false ];
      } catch (e) {
        result = [ e.toString(), true ];
      }
    } else {
      alert('Unexpected utility function:' + functionName);
    }
    RemoteToolsAgent.DidExecuteUtilityFunction(callId,
        JSON.stringify(result), '');
  }, 0);
};

RemoteToolsAgentStub.prototype.GetNodePrototypes = function(callId, nodeId) {
  setTimeout(function() {
    RemoteToolsAgent.DidGetNodePrototypes(callId,
        JSON.stringify());
  }, 0);
};

RemoteToolsAgentStub.prototype.ClearConsoleMessages = function() {
};

RemoteToolsAgentStub.prototype.SetResourceTrackingEnabled = function(enabled, always) {
  RemoteToolsAgent.SetResourcesPanelEnabled(enabled);
  if (enabled) {
    WebInspector.resourceTrackingWasEnabled();
  } else {
    WebInspector.resourceTrackingWasDisabled();
  }
  addDummyResource();
};

RemoteDebuggerAgentStub.ProfilerLogBuffer =
  'profiler,begin,1\n' +
  'profiler,resume\n' +
  'code-creation,LazyCompile,0x1000,256,"test1 http://aaa.js:1"\n' +
  'code-creation,LazyCompile,0x2000,256,"test2 http://bbb.js:2"\n' +
  'code-creation,LazyCompile,0x3000,256,"test3 http://ccc.js:3"\n' +
  'tick,0x1010,0x0,3\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x3010,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x2030,0x0,3,0x2020, 0x1010\n' +
  'tick,0x2020,0x0,3,0x1010\n' +
  'tick,0x1010,0x0,3\n' +
  'profiler,pause\n';

/**
 * @constructor
 */
RemoteDebuggerCommandExecutorStub = function() {
};

RemoteDebuggerCommandExecutorStub.prototype.DebuggerCommand = function(cmd) {
};

/**
 * @constructor
 */
DevToolsHostStub = function() {
  this.isStub = true;
  window.domAutomationController = {
    send: function(text) {
        debugPrint(text);
    }
  };
};

function addDummyResource() {
  var payload = {
    requestHeaders : {},
    requestURL: 'http://google.com/simple_page.html',
    host: 'google.com',
    path: 'simple_page.html',
    lastPathComponent: 'simple_page.html',
    isMainResource: true,
    cached: false,
    mimeType: 'text/html',
    suggestedFilename: 'simple_page.html',
    expectedContentLength: 10000,
    statusCode: 200,
    contentLength: 10000,
    responseHeaders: {},
    type: WebInspector.Resource.Type.Document,
    finished: true,
    startTime: new Date(),

    didResponseChange: true,
    didCompletionChange: true,
    didTypeChange: true
  };

  WebInspector.addResource(1, payload);
  WebInspector.updateResource(1, payload);
}

DevToolsHostStub.prototype.loaded = function() {
  RemoteDomAgentStub.sendDocumentElement_();
  RemoteDomAgentStub.sendChildNodes_(1);
  RemoteDomAgentStub.sendChildNodes_(2);
  devtools.tools.updateFocusedNode_(4);
  addDummyResource();

  uiTests.runAllTests();
};

DevToolsHostStub.prototype.reset = function() {
};

DevToolsHostStub.prototype.getPlatform = function() {
  return "windows";
};

DevToolsHostStub.prototype.addResourceSourceToFrame = function(
    identifier, mimeType, element) {
};

if (!window['DevToolsHost']) {
  window['RemoteDebuggerAgent'] = new RemoteDebuggerAgentStub();
  window['RemoteDebuggerCommandExecutor'] =
      new RemoteDebuggerCommandExecutorStub();
  window['RemoteDomAgent'] = new RemoteDomAgentStub();
  window['RemoteToolsAgent'] = new RemoteToolsAgentStub();
  window['DevToolsHost'] = new DevToolsHostStub();
}
<|endoftext|>