<commit_before>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(callback) {
        var Name        = 'Edit',
            Loading     = true,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Files       = DOM.Files,
            type        = Util.type,
            join        = CloudCmd.join,

            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Events      = DOM.Events,
            RESTful     = DOM.RESTful,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig,
            ConfigView  = {
                beforeClose: function() {
                    isChanged();

                    if (Menu)
                        Menu.hide();
                },
                afterShow: function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                }
            };

       function init(callback) {
            Util.exec.series([
                CloudCmd.View,
                load,
                Edit.show.bind(null, callback)
            ]);
        }

        this.show                       = function(callback) {
            var func    = Util.exec.ret(callback);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    initAce();

                    Events.add(Element, {
                            contextmenu :   setMenu,
                            drop        :   onDrop,
                            dragover    :   Events.preventDefault
                        });
                }

                getData(function(error, data) {
                    Edit.setValue(data);

                    ConfigView.beforeShow = func;

                    CloudCmd.View.show(Element, ConfigView);
                });
            }
        };

        this.setValue                   = function(value) {
            var UndoManager = ace.require('ace/undomanager').UndoManager;

            Value           = value;

            Ace.setValue(value);
            Session.setUndoManager(new UndoManager());
        };

        this.hide                       = function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function getData(callback) {
            var name        = Info.name,
                isDir       = Info.isDir;

            Util.checkArgs(arguments, ['callback']);

            if (isDir)
                Edit.setMode('json');
            else
                Edit.setModeForPath(name);

            Info.getData(function(error, data) {
                callback(error, data);
            });
        }

        this.setModeForPath             = function(name) {
            var modesByName = Modelist.modesByName,
                mode        = Modelist.getModeForPath(name).mode,

                htmlMode    = modesByName.html.mode,
                jsMode      = modesByName.javascript.mode,

                isHTML      = mode === htmlMode,
                isJS        = mode === jsMode;

            Session.setMode(mode);
            setUseOfWorker(mode);

            if (isHTML)
                setEmmet();

            if (isJS && Session.getUseWorker())
                setJsHintConfig();
        };

        this.setMode                    = function(mode) {
            var ext,
                modesByName = Modelist.modesByName;

            if (modesByName[mode]) {
                ext = modesByName[mode].extensions.split('|')[0];
                Edit.setModeForPath('.' + ext);
            }
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet() {
            DOM.Files.get('edit', function(error, config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    Util.exec.if(Emmet, function() {
                        Ace.setOption('enableEmmet', true);
                    }, function(callback) {
                        var url;

                        url = join([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.load.js(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);

                            callback();
                        });
                    });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = type.string(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = regExp.test(mode);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Files.get('edit', function(error, config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            DOM.Files.get('config', function(error, config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = type.string(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.exec.if(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var url = join([
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ]);

            DOM.load.js(url, function(error) {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (error) {
                    Dialog.alert(error);
                } else {
                    if (!Diff)
                        Diff        = new DiffProto(diff_match_patch);

                    Util.exec.if(!isAllowed, function() {
                        patch       = Diff.createPatch(Value, newValue);
                        Util.exec(callback, patch);
                    }, function(func) {
                        var path = Info.path;

                        DOM.getDataFromStorage(path, function(error, data) {
                            if (data)
                                Value   = data;

                            func();
                        });
                    });
                }
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                url             = join([
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ]);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = CloudCmd.PREFIX + '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.json.parse(data);
                        func();
                    }
                });
            });
        }

        function setMenu() {
            if (!Menu) {
                DOM.loadMenu(function(error) {
                    var position    = CloudCmd.MousePosition,
                        options     = {
                            beforeShow: function(params) {
                                params.x -= 18;
                                params.y -= 27;
                            },
                            afterClick: function() {
                                Ace.focus();
                            }
                    },
                    menuData    = {
                        'Save           Ctrl+S' : save,
                        'Go To Line     Ctrl+G' : function() {
                            Edit.goToLine();
                        },
                        'Select All     Ctrl+A' : function() {
                            Ace.selectAll();
                        },
                        'Delete         Del'    : function() {
                            Ace.remove('right');
                        },
                        'Close          Esc'    : Edit.hide
                    };

                    if (error) {
                        Dialog.alert(error);
                    } else if (!Menu) {
                        Menu        = new MenuIO(Element, options, menuData);
                        Menu.show(position.x, position.y);

                        Events.remove('contextMenu', Element, setMenu);
                    }
                });
            }
        }

        function load(callback) {
            var url     = join([
                    'theme-tomorrow_night_blue',
                    'ext-language_tools',
                    'ext-searchbox',
                    'ext-modelist'
                ].map(function(name) {
                    return DIR + name + '.js';
                }));

            Util.time(Name + ' load');

            DOM.loadRemote('ace', function() {
                DOM.load.js(url, function() {
                    Loading = false;

                    Util.timeEnd(Name + ' load');
                    Util.exec(callback);
                });

                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
            });
        }

        function onSave(text) {
            var ret,
                size    = Format.size(Value.length),
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(size);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            Util.forEach(files, function(file) {
                reader  = new FileReader();
                Events.addLoad(reader, onLoad);
                reader.readAsBinaryString(file);
            });
        }

        this.showMessage    = function(text) {
            var msg, HIDE_TIME = 2000;

            /*
             * Msg should be created and removed
             * if it's not and just inner text
             * is changing, and hide and show of DOM
             * is called - bug occures: empty box
             * with no text inside.
             */
            msg = DOM.load({
                name        : 'div',
                className   : 'msg',
                parent      : Element,
                inner       : text,
                func        : alert
            });

            setTimeout(function() {
                DOM.remove(msg, Element);
            }, HIDE_TIME);
        };

        init(callback);
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>refactor(edit) DOM.Files -> Files<commit_after>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(callback) {
        var Name        = 'Edit',
            Loading     = true,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Files       = DOM.Files,
            type        = Util.type,
            join        = CloudCmd.join,

            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Events      = DOM.Events,
            RESTful     = DOM.RESTful,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig,
            ConfigView  = {
                beforeClose: function() {
                    isChanged();

                    if (Menu)
                        Menu.hide();
                },
                afterShow: function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                }
            };

       function init(callback) {
            Util.exec.series([
                CloudCmd.View,
                load,
                Edit.show.bind(null, callback)
            ]);
        }

        this.show                       = function(callback) {
            var func    = Util.exec.ret(callback);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    initAce();

                    Events.add(Element, {
                            contextmenu :   setMenu,
                            drop        :   onDrop,
                            dragover    :   Events.preventDefault
                        });
                }

                getData(function(error, data) {
                    Edit.setValue(data);

                    ConfigView.beforeShow = func;

                    CloudCmd.View.show(Element, ConfigView);
                });
            }
        };

        this.setValue                   = function(value) {
            var UndoManager = ace.require('ace/undomanager').UndoManager;

            Value           = value;

            Ace.setValue(value);
            Session.setUndoManager(new UndoManager());
        };

        this.hide                       = function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function getData(callback) {
            var name        = Info.name,
                isDir       = Info.isDir;

            Util.checkArgs(arguments, ['callback']);

            if (isDir)
                Edit.setMode('json');
            else
                Edit.setModeForPath(name);

            Info.getData(function(error, data) {
                callback(error, data);
            });
        }

        this.setModeForPath             = function(name) {
            var modesByName = Modelist.modesByName,
                mode        = Modelist.getModeForPath(name).mode,

                htmlMode    = modesByName.html.mode,
                jsMode      = modesByName.javascript.mode,

                isHTML      = mode === htmlMode,
                isJS        = mode === jsMode;

            Session.setMode(mode);
            setUseOfWorker(mode);

            if (isHTML)
                setEmmet();

            if (isJS && Session.getUseWorker())
                setJsHintConfig();
        };

        this.setMode                    = function(mode) {
            var ext,
                modesByName = Modelist.modesByName;

            if (modesByName[mode]) {
                ext = modesByName[mode].extensions.split('|')[0];
                Edit.setModeForPath('.' + ext);
            }
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet() {
            Files.get('edit', function(error, config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    Util.exec.if(Emmet, function() {
                        Ace.setOption('enableEmmet', true);
                    }, function(callback) {
                        var url;

                        url = join([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.load.js(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);

                            callback();
                        });
                    });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = type.string(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = regExp.test(mode);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Files.get('edit', function(error, config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            Files.get('config', function(error, config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = type.string(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.exec.if(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var url = join([
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ]);

            DOM.load.js(url, function(error) {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (error) {
                    Dialog.alert(error);
                } else {
                    if (!Diff)
                        Diff        = new DiffProto(diff_match_patch);

                    Util.exec.if(!isAllowed, function() {
                        patch       = Diff.createPatch(Value, newValue);
                        Util.exec(callback, patch);
                    }, function(func) {
                        var path = Info.path;

                        DOM.getDataFromStorage(path, function(error, data) {
                            if (data)
                                Value   = data;

                            func();
                        });
                    });
                }
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                url             = join([
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ]);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = CloudCmd.PREFIX + '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.json.parse(data);
                        func();
                    }
                });
            });
        }

        function setMenu() {
            if (!Menu) {
                DOM.loadMenu(function(error) {
                    var position    = CloudCmd.MousePosition,
                        options     = {
                            beforeShow: function(params) {
                                params.x -= 18;
                                params.y -= 27;
                            },
                            afterClick: function() {
                                Ace.focus();
                            }
                    },
                    menuData    = {
                        'Save           Ctrl+S' : save,
                        'Go To Line     Ctrl+G' : function() {
                            Edit.goToLine();
                        },
                        'Select All     Ctrl+A' : function() {
                            Ace.selectAll();
                        },
                        'Delete         Del'    : function() {
                            Ace.remove('right');
                        },
                        'Close          Esc'    : Edit.hide
                    };

                    if (error) {
                        Dialog.alert(error);
                    } else if (!Menu) {
                        Menu        = new MenuIO(Element, options, menuData);
                        Menu.show(position.x, position.y);

                        Events.remove('contextMenu', Element, setMenu);
                    }
                });
            }
        }

        function load(callback) {
            var url     = join([
                    'theme-tomorrow_night_blue',
                    'ext-language_tools',
                    'ext-searchbox',
                    'ext-modelist'
                ].map(function(name) {
                    return DIR + name + '.js';
                }));

            Util.time(Name + ' load');

            DOM.loadRemote('ace', function() {
                DOM.load.js(url, function() {
                    Loading = false;

                    Util.timeEnd(Name + ' load');
                    Util.exec(callback);
                });

                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
            });
        }

        function onSave(text) {
            var ret,
                size    = Format.size(Value.length),
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(size);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            Util.forEach(files, function(file) {
                reader  = new FileReader();
                Events.addLoad(reader, onLoad);
                reader.readAsBinaryString(file);
            });
        }

        this.showMessage    = function(text) {
            var msg, HIDE_TIME = 2000;

            /*
             * Msg should be created and removed
             * if it's not and just inner text
             * is changing, and hide and show of DOM
             * is called - bug occures: empty box
             * with no text inside.
             */
            msg = DOM.load({
                name        : 'div',
                className   : 'msg',
                parent      : Element,
                inner       : text,
                func        : alert
            });

            setTimeout(function() {
                DOM.remove(msg, Element);
            }, HIDE_TIME);
        };

        init(callback);
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>


<commit_before>var File = require('./file');
var Cache = require('./cache');
var Module = require('./module');
var utils = require('./client/utils');

var composition_cache = Cache('compositions');

/**
 * Get module instance composition.
 */
module.exports = function (name, role, callback) {

    // get composition from cache
    var composition = composition_cache.get(name);
    if (composition) {

        if (composition === 'INVALID') {
            return callback(new Error('Invalid composition "' + name + '".'));
        }

        // check access for cached item
        if (!utils.roleAccess(composition, role)) {
            return callback(new Error('Access denied for composition "' + name + '"'));
        }

        // return if composition is complete
        if (!composition.LOAD) {
            return callback(null, composition);
        }
    }

    // read the composition json
    File.json(engine.paths.app_composition + name + '.json', function (err, config) {

        // handle error
        if ((err = err || checkComposition(name, role, config))) {
            return callback(err);
        }

        // create mandatory package infos to custom module
        if (typeof config.module === 'object') {
            config.module.name = name;
            config.module.version = 'custom';
            config.module._id = name + '@custom';
            module._base = engine.repo;
        }

        Module(config.module, function (err, modulePackage) {

            // handle module package error
            if (err) {
                return callback(err);
            }

            // prepare instance components
            if (config.client && (config.client.styles || config.client.markup)) {

                // send module id and module base
                var components = {
                    base: modulePackage._base,
                    module: modulePackage._id,
                    styles: config.client.styles,
                    markup: config.client.markup
                };

                File.prepare(components, function (err, files) {

                    // update file paths in module package
                    if (files.styles) {
                        config.client.styles = files.styles;
                    }

                    if (files.markup) {
                        config.client.markup = files.markup;
                    }

                    finish(name, modulePackage, config, callback);
                });
                return;
            }

            finish(name, modulePackage, config, callback);
        });
    });
};

function finish (name, modulePackage, config, callback) {

    // merge package data into config
    if (modulePackage.composition) {
        config = mergePackage(modulePackage.version, modulePackage.composition, config);
    }

    // save composition in cache
    composition_cache.set(name, config);

    // return composition config
    callback(null, config);
}

/**
 * Check composition config.
 */
function checkComposition (name, role, config) {

    // handle not found
    if (!config) {
        return new Error('composition "' + name +'" not found.');
    }

    // check if composition has a module
    if (!config.module) {

        // save as invalid in cache
        composition_cache.set(name, 'INVALID');
        return new Error('No module info in composition "' + name + '".');
    }

    // check access
    if (!utils.roleAccess(config, role)) {

        // save access information in cache, to check access without loading the hole file again
        composition_cache.set(name, {roles: config.roles, LOAD: true});
        return new Error('Access denied: Role "' + role + '", Composition "' + name + '".');
    }

    // set composition name as custom module name
    if (typeof config.module === 'object' && !config.module.name) {
        config.module.name = config.name;
    }
}

/**
 * Merge package config into composition config.
 */
function mergePackage (version, package_instance, config) {

    // merge client related options
    if (package_instance.client) {

        // ensure client config object
        config.client = config.client || {};
        config.client.name = config.name;
        config.client.version = version;

        // set client module scripts
        if (package_instance.client.module) {
            config.client.module = package_instance.client.module;
        }

        // config
        if (package_instance.client.config) {
            for (var key in package_instance.client.config) {
                if (typeof config.client.config[key] === 'undefined') {
                    config.client.config[key] = package_instance.client.config[key];
                }
            }
        }

        // flow
        if (package_instance.client.flow) {
            config.client.flow = (config.client.flow || []).concat(package_instance.client.flow);
        }

        // markup
        if (package_instance.client.markup) {
            config.client.markup = (config.client.markup || []).concat(package_instance.client.markup);
        }

        // styles
        if (package_instance.client.styles) {
            config.client.styles = (config.client.styles || []).concat(package_instance.client.styles);
        }
    }

    // server flow
    if (package_instance.flow) {
        config.flow = (config.flow || []).concat(package_instance.flow);
    }

    // merge server config
    if (package_instance.config) {
        for (var prop in package_instance.config) {
            if (typeof config.config[prop] === 'undefined') {
                config.config[prop] = package_instance.config[prop];
            }
        }
    }

    return config;
}
<commit_msg>collect related cache items<commit_after>var File = require('./file');
var Cache = require('./cache');
var Module = require('./module');
var utils = require('./client/utils');

var composition_cache = Cache('compositions');

/**
 * Get module instance composition.
 */
module.exports = function (name, related, role, callback) {

    // get composition from cache
    var path = engine.paths.app_composition + name + '.json';
    var composition = composition_cache.get(path);
    if (composition) {

        if (composition === 'INVALID') {
            return callback(new Error('Invalid composition "' + name + '".'));
        }

        // check access for cached item
        if (!utils.roleAccess(composition, role)) {
            return callback(new Error('Access denied for composition "' + name + '"'));
        }

        // add related instances to composition and update cache
        if (related) {
            composition = File.relate(related, composition);
            composition_cache.set(path, composition);
        }

        return process.nextTick(callback, null, composition);
    }

    // read the composition json
    File.json(path, function (err, config) {

        // handle error
        if ((err = err || checkComposition(name, path, role, config))) {
            return callback(err);
        }

        // merge related items to update cache on item change
        if (related) {
            config = File.relate(related, config);
        }

        // create mandatory package infos to custom module
        if (typeof config.module === 'object') {
            config.module.name = name;
            config.module.version = 'custom';
            config.module._id = name + '@custom';
            module._base = engine.repo;
        }

        // add composition to related items
        related = related || {};
        related.compositions = related.compositions || {};
        related.compositions[path] = true;

        Module(config.module, related, function (err, modulePackage) {

            // handle module package error
            if (err) {
                return callback(err);
            }

            // prepare instance components
            if (config.client && (config.client.styles || config.client.markup)) {

                // send module id and module base
                var components = {
                    base: modulePackage._base,
                    module: modulePackage._id,
                    styles: config.client.styles,
                    markup: config.client.markup,
                    related: related
                };

                File.prepare(components, function (err, files) {

                    // update file paths in module package
                    if (files.styles) {
                        config.client.styles = files.styles;
                    }

                    if (files.markup) {
                        config.client.markup = files.markup;
                    }

                    finish(name, path, modulePackage, config, callback);
                });
                return;
            }

            finish(name, path, modulePackage, config, callback);
        });
    }, 'compositions');
};

function finish (name, path, modulePackage, config, callback) {

    // merge package data into config
    if (modulePackage.composition) {
        config = mergePackage(modulePackage.version, modulePackage.composition, config);
    }

    // save composition in cache
    composition_cache.set(path, config);

    // return composition configc
    callback(null, config);
}

/**
 * Check composition config.
 */
function checkComposition (name, path, role, config) {

    // handle not found
    if (!config) {
        return new Error('composition "' + name +'" not found.');
    }

    // check if composition has a module
    if (!config.module) {

        // save as invalid in cache
        composition_cache.set(path, 'INVALID');
        return new Error('No module info in composition "' + name + '".');
    }

    // check access
    if (!utils.roleAccess(config, role)) {

        // save access information in cache, to check access without loading the hole file again
        composition_cache.set(path, {roles: config.roles, LOAD: true});
        return new Error('Access denied: Role "' + role + '", Composition "' + name + '".');
    }

    // set composition name as custom module name
    if (typeof config.module === 'object' && !config.module.name) {
        config.module.name = config.name;
    }
}

/**
 * Merge package config into composition config.
 */
function mergePackage (version, package_instance, config) {

    // merge client related options
    if (package_instance.client) {

        // ensure client config object
        config.client = config.client || {};
        config.client.name = config.name;
        config.client.version = version;

        // set client module scripts
        if (package_instance.client.module) {
            config.client.module = package_instance.client.module;
        }

        // config
        if (package_instance.client.config) {
            for (var key in package_instance.client.config) {
                if (typeof config.client.config[key] === 'undefined') {
                    config.client.config[key] = package_instance.client.config[key];
                }
            }
        }

        // flow
        if (package_instance.client.flow) {
            config.client.flow = (config.client.flow || []).concat(package_instance.client.flow);
        }

        // markup
        if (package_instance.client.markup) {
            config.client.markup = (config.client.markup || []).concat(package_instance.client.markup);
        }

        // styles
        if (package_instance.client.styles) {
            config.client.styles = (config.client.styles || []).concat(package_instance.client.styles);
        }
    }

    // server flow
    if (package_instance.flow) {
        config.flow = (config.flow || []).concat(package_instance.flow);
    }

    // merge server config
    if (package_instance.config) {
        for (var prop in package_instance.config) {
            if (typeof config.config[prop] === 'undefined') {
                config.config[prop] = package_instance.config[prop];
            }
        }
    }

    return config;
}
<|endoftext|>


<commit_before>/**
 * @author Toru Nagashima
 * See LICENSE file in root directory for full license.
 */
"use strict"

const { merge } = require("../utils")
const moduleConfig = require("./+modules")

module.exports = {
    overrides: [
        merge({ files: ["*.ts", "*.tsx"] }, moduleConfig, {
            parser: require.resolve("@typescript-eslint/parser"),
            parserOptions: {
                loggerFn: false,
                project: "tsconfig.json",
            },
            rules: {
                // Enabled rules
                "@mysticatea/ts/adjacent-overload-signatures": "error",
                "@mysticatea/ts/array-type": "error",
                "@mysticatea/ts/await-thenable": "error",
                "@mysticatea/ts/ban-ts-ignore": "error",
                "@mysticatea/ts/class-name-casing": "error",
                "@mysticatea/ts/explicit-member-accessibility": "error",
                "@mysticatea/ts/interface-name-prefix": "error",
                "@mysticatea/ts/member-naming": "error",
                "@mysticatea/ts/no-angle-bracket-type-assertion": "error",
                "@mysticatea/ts/no-array-constructor": "error",
                "@mysticatea/ts/no-empty-interface": "error",
                "@mysticatea/ts/no-extraneous-class": "error",
                "@mysticatea/ts/no-for-in-array": "error",
                "@mysticatea/ts/no-inferrable-types": "error",
                "@mysticatea/ts/no-misused-new": "error",
                "@mysticatea/ts/no-object-literal-type-assertion": "error",
                "@mysticatea/ts/no-parameter-properties": "error",
                "@mysticatea/ts/no-require-imports": "error",
                "@mysticatea/ts/no-this-alias": [
                    "error",
                    { allowDestructuring: true },
                ],
                "@mysticatea/ts/no-triple-slash-reference": "error",
                "@mysticatea/ts/no-unnecessary-qualifier": "error",
                // https://github.com/typescript-eslint/typescript-eslint/issues/453
                "@mysticatea/ts/no-unnecessary-type-assertion": "off",
                "@mysticatea/ts/no-useless-constructor": "error",
                "@mysticatea/ts/no-var-requires": "error",
                "@mysticatea/ts/prefer-function-type": "error",
                "@mysticatea/ts/prefer-includes": "error",
                "@mysticatea/ts/prefer-namespace-keyword": "error",
                "@mysticatea/ts/prefer-string-starts-ends-with": "error",
                "@mysticatea/ts/restrict-plus-operands": "error",
                "@mysticatea/ts/require-array-sort-compare": "error",
                "@mysticatea/ts/unbound-method": [
                    // https://github.com/typescript-eslint/typescript-eslint/issues/451
                    "off",
                    { ignoreStatic: true },
                ],
                // https://github.com/typescript-eslint/typescript-eslint/issues/452
                "@mysticatea/ts/unified-signatures": "off",
                "@mysticatea/prettier": [
                    "error",
                    {
                        tabWidth: 4,
                        semi: false,
                        trailingComma: "all",
                        parser: "typescript",
                    },
                    {
                        usePrettierrc: false,
                    },
                ],

                // Disabled rules
                "func-style": "off",
                "init-declarations": "off",
                "lines-between-class-members": "off",
                "no-dupe-class-members": "off",
                "no-invalid-this": "off",
                "no-loop-func": "off",
                "no-redeclare": "off",
                "no-undef": "off",
                "no-unused-vars": "off",
                "no-use-before-define": "off",
                "one-var": "off",
                "@mysticatea/ts/ban-types": "off",
                "@mysticatea/ts/camelcase": "off", // ?
                "@mysticatea/ts/explicit-function-return-type": "off", // I want but this is not so...
                "@mysticatea/ts/generic-type-naming": "off",
                "@mysticatea/ts/indent": "off", // favor of Prettier.
                "@mysticatea/ts/member-delimiter-style": "off", // favor of Prettier.
                "@mysticatea/ts/member-ordering": "off",
                "@mysticatea/ts/no-explicit-any": "off",
                "@mysticatea/ts/no-extra-parens": "off", // favor of Prettier.
                "@mysticatea/ts/no-namespace": "off", // I like the namespace for interfaces (type only things).
                "@mysticatea/ts/no-non-null-assertion": "off",
                "@mysticatea/ts/no-type-alias": "off",
                "@mysticatea/ts/no-unused-vars": "off", // tsc verifies it.
                "@mysticatea/ts/no-use-before-define": "off", // tsc verifies it.
                "@mysticatea/ts/prefer-for-of": "off",
                "@mysticatea/ts/prefer-interface": "off",
                "@mysticatea/ts/promise-function-async": "off",
                "@mysticatea/ts/type-annotation-spacing": "off", // favor of Prettier.
            },
            settings: {
                node: {
                    tryExtensions: [
                        ".ts",
                        ".tsx",
                        ".mjs",
                        ".js",
                        ".json",
                        ".node",
                    ],
                },
            },
        }),
        {
            files: ["*.d.ts"],
            rules: {
                strict: "off",
            },
        },
    ],
}
<commit_msg>🐛 disable ts/prefer-function-type for bug<commit_after>/**
 * @author Toru Nagashima
 * See LICENSE file in root directory for full license.
 */
"use strict"

const { merge } = require("../utils")
const moduleConfig = require("./+modules")

module.exports = {
    overrides: [
        merge({ files: ["*.ts", "*.tsx"] }, moduleConfig, {
            parser: require.resolve("@typescript-eslint/parser"),
            parserOptions: {
                loggerFn: false,
                project: "tsconfig.json",
            },
            rules: {
                // Enabled rules
                "@mysticatea/ts/adjacent-overload-signatures": "error",
                "@mysticatea/ts/array-type": "error",
                "@mysticatea/ts/await-thenable": "error",
                "@mysticatea/ts/ban-ts-ignore": "error",
                "@mysticatea/ts/class-name-casing": "error",
                "@mysticatea/ts/explicit-member-accessibility": "error",
                "@mysticatea/ts/interface-name-prefix": "error",
                "@mysticatea/ts/member-naming": "error",
                "@mysticatea/ts/no-angle-bracket-type-assertion": "error",
                "@mysticatea/ts/no-array-constructor": "error",
                "@mysticatea/ts/no-empty-interface": "error",
                "@mysticatea/ts/no-extraneous-class": "error",
                "@mysticatea/ts/no-for-in-array": "error",
                "@mysticatea/ts/no-inferrable-types": "error",
                "@mysticatea/ts/no-misused-new": "error",
                "@mysticatea/ts/no-object-literal-type-assertion": "error",
                "@mysticatea/ts/no-parameter-properties": "error",
                "@mysticatea/ts/no-require-imports": "error",
                "@mysticatea/ts/no-this-alias": [
                    "error",
                    { allowDestructuring: true },
                ],
                "@mysticatea/ts/no-triple-slash-reference": "error",
                "@mysticatea/ts/no-unnecessary-qualifier": "error",
                // https://github.com/typescript-eslint/typescript-eslint/issues/453
                "@mysticatea/ts/no-unnecessary-type-assertion": "off",
                "@mysticatea/ts/no-useless-constructor": "error",
                "@mysticatea/ts/no-var-requires": "error",
                // https://github.com/typescript-eslint/typescript-eslint/issues/454
                "@mysticatea/ts/prefer-function-type": "off",
                "@mysticatea/ts/prefer-includes": "error",
                "@mysticatea/ts/prefer-namespace-keyword": "error",
                "@mysticatea/ts/prefer-string-starts-ends-with": "error",
                "@mysticatea/ts/restrict-plus-operands": "error",
                "@mysticatea/ts/require-array-sort-compare": "error",
                "@mysticatea/ts/unbound-method": [
                    // https://github.com/typescript-eslint/typescript-eslint/issues/451
                    "off",
                    { ignoreStatic: true },
                ],
                // https://github.com/typescript-eslint/typescript-eslint/issues/452
                "@mysticatea/ts/unified-signatures": "off",
                "@mysticatea/prettier": [
                    "error",
                    {
                        tabWidth: 4,
                        semi: false,
                        trailingComma: "all",
                        parser: "typescript",
                    },
                    {
                        usePrettierrc: false,
                    },
                ],

                // Disabled rules
                "func-style": "off",
                "init-declarations": "off",
                "lines-between-class-members": "off",
                "no-dupe-class-members": "off",
                "no-invalid-this": "off",
                "no-loop-func": "off",
                "no-redeclare": "off",
                "no-undef": "off",
                "no-unused-vars": "off",
                "no-use-before-define": "off",
                "one-var": "off",
                "@mysticatea/ts/ban-types": "off",
                "@mysticatea/ts/camelcase": "off", // ?
                "@mysticatea/ts/explicit-function-return-type": "off", // I want but this is not so...
                "@mysticatea/ts/generic-type-naming": "off",
                "@mysticatea/ts/indent": "off", // favor of Prettier.
                "@mysticatea/ts/member-delimiter-style": "off", // favor of Prettier.
                "@mysticatea/ts/member-ordering": "off",
                "@mysticatea/ts/no-explicit-any": "off",
                "@mysticatea/ts/no-extra-parens": "off", // favor of Prettier.
                "@mysticatea/ts/no-namespace": "off", // I like the namespace for interfaces (type only things).
                "@mysticatea/ts/no-non-null-assertion": "off",
                "@mysticatea/ts/no-type-alias": "off",
                "@mysticatea/ts/no-unused-vars": "off", // tsc verifies it.
                "@mysticatea/ts/no-use-before-define": "off", // tsc verifies it.
                "@mysticatea/ts/prefer-for-of": "off",
                "@mysticatea/ts/prefer-interface": "off",
                "@mysticatea/ts/promise-function-async": "off",
                "@mysticatea/ts/type-annotation-spacing": "off", // favor of Prettier.
            },
            settings: {
                node: {
                    tryExtensions: [
                        ".ts",
                        ".tsx",
                        ".mjs",
                        ".js",
                        ".json",
                        ".node",
                    ],
                },
            },
        }),
        {
            files: ["*.d.ts"],
            rules: {
                strict: "off",
            },
        },
    ],
}
<|endoftext|>


<commit_before>var _ = require('lodash');

var alias = {
    'PORT': 'CODEBOX_PORT'
}

var parseEnv = function (env, parent, prefix) {
    var k, v, envVar, parsedEnv;

    if (!parent) {
        parent = {};
    }

    for(k in parent) {
        v = parent[k];

        envVar = prefix? prefix + '_': '';
        envVar += k.toUpperCase();

        if (_.isObject(v) && !_.isArray(v) && !_.isFunction(v)) {
            parseEnv(env, v, envVar);
        }
        else {
            if (envVar in env) {
                if (_.isArray(v) && (v.length == 0 || _.isString(v[0]))) {
                    parent[k] = _.compact(env[envVar].split(","));
                } else if (_.isNumber(v)) {
            		parent[k] = parseInt(env[envVar]);
            	} else if (_.isBoolean(v)) {
            		parent[k] = (env[envVar] == "false"? false : true);
            	} else {
            		parent[k] = env[envVar]
            	}
            }
        }
    }

    return parent;
};

// Extend configuration with environment variables
module.exports = function(options) {
    var env = _.clone(process.env);
    _.each(alias, function(to, from) {
        env[to] = env[from] || env[to];
    })

    return parseEnv(env, options, 'CODEBOX');
};<commit_msg>Fix default port<commit_after>var _ = require('lodash');

var alias = {
    'PORT': 'CODEBOX_PORT'
}

var parseEnv = function (env, parent, prefix) {
    var k, v, envVar, parsedEnv;

    if (!parent) {
        parent = {};
    }

    for(k in parent) {
        v = parent[k];

        envVar = prefix? prefix + '_': '';
        envVar += k.toUpperCase();

        if (_.isObject(v) && !_.isArray(v) && !_.isFunction(v)) {
            parseEnv(env, v, envVar);
        }
        else {
            if (envVar in env) {
                if (_.isArray(v) && (v.length == 0 || _.isString(v[0]))) {
                    parent[k] = _.compact(env[envVar].split(","));
                } else if (_.isNumber(v)) {
            		parent[k] = parseInt(env[envVar]);
            	} else if (_.isBoolean(v)) {
            		parent[k] = (env[envVar] == "false"? false : true);
            	} else {
            		parent[k] = env[envVar]
            	}
            }
        }
    }

    return parent;
};

// Extend configuration with environment variables
module.exports = function(options) {
    var env = _.clone(process.env);
    _.each(alias, function(to, from) {
        if (env[from]) env[to] = env[from] || env[to];
    });

    return parseEnv(env, options, 'CODEBOX');
};<|endoftext|>


<commit_before>THREE.Asset = function () {

	THREE.Loader.call( this );

};

THREE.Asset.prototype = {

	constructor: THREE.Asset,

	load: function ( source, callback ) {
		// variables
		var loader, src, ext;
		var self = this;
		// save callback for later...
		this._callback = callback;
		// get file
		var file = ( source instanceof Array ) ? source[0]: source;

		ext = file.substr( file.lastIndexOf(".")+1 );
		src = file.substr( 0, file.lastIndexOf(".") );
		// based on the extension initiate the appropriate loader
		switch( ext ){
			case "bin":
				loader = new THREE.BinaryLoader( true );
				loader.load( src+'.js', function(){ self._loaded.apply(self, arguments); });
			break;
			case "obj":
				var obj = file;
				var mtl = src+'.mtl';
				loader = new THREE.OBJMTLLoader();
				loader.load( obj, mtl, function(){ self._loaded.apply(self, arguments); });
			break;
			case "js":
				// assume this is the uncompressed version (lookup for a bin to make sure?)
				loader = new THREE.JSONLoader( true );
				loader.load( file, function(){ self._loaded.apply(self, arguments); });
			break;
		}

	},

	parse: function ( json ) {

	},

	_loaded: function ( geometry, materials ) {

		var object = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(materials) );

		if( typeof this._callback == "function" ) this._callback( object );
	}

};<commit_msg>#4 using LOD for an array of sources<commit_after>THREE.Asset = function () {

	THREE.Loader.call( this );

};

THREE.Asset.prototype = {

	constructor: THREE.Asset,

	load: function ( source, callback ) {
		// variables
		var self = this;
		var loaded = 0;
		var distance = 10; // distance between each LOD level (make this variable...)
		// level of detail
		var lod = new THREE.LOD();
		// save callback for later...
		this._callback = ( typeof this._callback == "function" ) ? callback : function(){};
		// sources should be an array
		source = ( source instanceof Array ) ? source : [source];
		for(var i in source ){
			var file = source[i];
			this.loadSource(file, function( geometry, materials ){
				var object = self.getObject( geometry, materials );
				lod.addLevel( object, loaded*distance);
				loaded++;
				// exit if all done
				if( loaded == source.length ){
					return lod;
				}
			});
		}

	},

	parse: function ( json ) {

	},

	loadSource: function ( geometry, callback ) {
		// variables
		var self = this;
		var loader, src, ext;
		//
		ext = file.substr( file.lastIndexOf(".")+1 );
		src = file.substr( 0, file.lastIndexOf(".") );
		// based on the extension initiate the appropriate loader
		switch( ext ){
			case "bin":
				loader = new THREE.BinaryLoader( true );
				loader.load( src+'.js', function(){ self.callback.apply(self, arguments); });
			break;
			case "obj":
				var obj = file;
				var mtl = src+'.mtl';
				loader = new THREE.OBJMTLLoader();
				loader.load( obj, mtl, function(){ self.callback.apply(self, arguments); });
			break;
			case "js":
				// assume this is the uncompressed version (lookup for a bin to make sure?)
				loader = new THREE.JSONLoader( true );
				loader.load( file, function(){ self.callback.apply(self, arguments); });
			break;
		}

	},

	getObject: function ( geometry, materials ) {

		var object = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(materials) );

		return object;
	}

};<|endoftext|>


<commit_before>'use strict';

const chalk = require('chalk');
const puppeteer = require('puppeteer');
const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

module.exports = async function() {
  console.log(chalk.green('Setup Puppeteer'));
  const browser = await puppeteer.launch({});
  global.__BROWSER__ = browser;
  mkdirp.sync(DIR);
  fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};
<commit_msg>Fix Puppeteer not working in a Travis env (docker)<commit_after>'use strict';

const chalk = require('chalk');
const puppeteer = require('puppeteer');
const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

module.exports = async function() {
  console.log(chalk.green('Setup Puppeteer'));
  const browser = await puppeteer.launch({
    // workaround for Puppeteer not launching correctly on Travis-CI
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });
  global.__BROWSER__ = browser;
  mkdirp.sync(DIR);
  fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};
<|endoftext|>


<commit_before>var deployTool = {},
    extend = require('util')._extend,
    constants = {},
    sshTool = require('./ssh-tool.js');

// constants
var COMPARE_MODE = 'checksum';

module.exports = function ( gulp ) {
    var that = Object.create(deployTool);
    that.gulp = gulp;
    return that;
};

deployTool.options = {};

deployTool.environments = function ( options ) {
    var that = this;

    if ( options && options.default ) {
        that.options = extend(that.options, options.default);
        delete options.default;
    }
    that.options.compareMode = COMPARE_MODE;

    that.environments = options.environments;

    _defineCurrentEnvironment.call(that);

    require('./gulp-tasks.js')(that);

    return that;
};

function _defineCurrentEnvironment() {
    var that = this,
        list = process.argv[2].split(':'),
        env = (list.length > 0) ? list[0] : '';

    if ( that.environments[env] ) {
        that.env = env;
        that.current = that.environments[env];
    }
}

function _extendCallback( func ) {
    var that = this;
    return function ( cb ) {
        that.cb = cb;
        func(cb);
    };
};

deployTool.ssh = function ( options ) {
    var that = this;

    options = extend({
        host: that.current.host.split('@')[1],
        user: that.current.host.split('@')[0],
        agent: process.env.SSH_AUTH_SOCK,
        agentForward: true
    }, options);

    return sshTool().connect( options, that.cb );
};

deployTool.task = function () {
    var that = this;
    arguments[0] = that.env + ':' + arguments[0];
    if ( typeof arguments[1] === 'function' ) {
        arguments[1] = _extendCallback.call(that, arguments[1]);
    } else {
        arguments[2] = _extendCallback.call(that, arguments[2]);
    }
    that.gulp.task.apply(that.gulp, arguments);
};<commit_msg>sshTool export<commit_after>var deployTool = {},
    extend = require('util')._extend,
    constants = {},
    sshTool = require('./ssh-tool.js');

// constants
var COMPARE_MODE = 'checksum';

module.exports = function ( gulp ) {
    var that = Object.create(deployTool);
    that.gulp = gulp;
    return that;
};

deployTool.sshTool = sshTool;

deployTool.options = {};

deployTool.environments = function ( options ) {
    var that = this;

    if ( options && options.default ) {
        that.options = extend(that.options, options.default);
        delete options.default;
    }
    that.options.compareMode = COMPARE_MODE;

    that.environments = options.environments;

    _defineCurrentEnvironment.call(that);

    require('./gulp-tasks.js')(that);

    return that;
};

function _defineCurrentEnvironment() {
    var that = this,
        list = process.argv[2].split(':'),
        env = (list.length > 0) ? list[0] : '';

    if ( that.environments[env] ) {
        that.env = env;
        that.current = that.environments[env];
    }
}

function _extendCallback( func ) {
    var that = this;
    return function ( cb ) {
        that.cb = cb;
        func(cb);
    };
};

deployTool.ssh = function ( options ) {
    var that = this;

    options = extend({
        host: that.current.host.split('@')[1],
        user: that.current.host.split('@')[0],
        agent: process.env.SSH_AUTH_SOCK,
        agentForward: true
    }, options);

    return sshTool().connect( options, that.cb );
};

deployTool.task = function () {
    var that = this;
    arguments[0] = that.env + ':' + arguments[0];
    if ( typeof arguments[1] === 'function' ) {
        arguments[1] = _extendCallback.call(that, arguments[1]);
    } else {
        arguments[2] = _extendCallback.call(that, arguments[2]);
    }
    that.gulp.task.apply(that.gulp, arguments);
};
<|endoftext|>