<commit_before>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },
/*
    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        if (local){
            console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/User/me/MyCoolApplication')");
            prompt.get (['folder'], function (err, results){
                config.applicationDirectory = results['folder'];
                done ();
            });
        }
        else{
            done ();
        }
    },
*/
    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    } /*,

    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key
            try { ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null;}
            if (!ssh_file){
                done ("/tssh key not generated, please exit generate one, and re-run");
            }
            else{
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            var dir = std.split ("Cloning into ");
                            dir = dir && dir[1] && dir[1].replace ("'", "").replace ("...", "");
                            if (dir){
                                config.applicationDirectory = '/home/ec2-user/' + dir;
                            }
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }
*/
], function (err){
    if (!err){
        var data = JSON.stringify (config);
        //fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        if (!local){
            console.log ("To Launch the application type 'sudo start " + (config.applicationName || "node-aws-deploy") + "'");
            // rename the upstart file to the applicaiton name
            if (config.applicationName){
                var child = exec ("sudo mv /etc/init/node-aws-deploy.conf /etc/init/" + config.applicationName + ".conf", function (err, std, ster){
                    process.exit (0);
                });
            }
            else{
                process.exit (0);
            }
        }
        else{
            process.exit (0);
        }
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<commit_msg>Initial<commit_after>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },

    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        if (local){
            console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/User/me/MyCoolApplication')");
            prompt.get (['folder'], function (err, results){
                config.applicationDirectory = results['folder'];
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    },

    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key
            try { ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null;}
            if (!ssh_file){
                done ("/tssh key not generated, please exit generate one, and re-run");
            }
            else{
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            var dir = std.split ("Cloning into ");
                            dir = dir && dir[1] && dir[1].replace ("'", "").replace ("...", "");
                            if (dir){
                                config.applicationDirectory = '/home/ec2-user/' + dir;
                            }
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }

], function (err){
    if (!err){
        var data = JSON.stringify (config);
        //fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        if (!local){
            console.log ("To Launch the application type 'sudo start " + (config.applicationName || "node-aws-deploy") + "'");
            // rename the upstart file to the applicaiton name
            if (config.applicationName){
                var child = exec ("sudo mv /etc/init/node-aws-deploy.conf /etc/init/" + config.applicationName + ".conf", function (err, std, ster){
                    process.exit (0);
                });
            }
            else{
                process.exit (0);
            }
        }
        else{
            process.exit (0);
        }
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<|endoftext|>


<commit_before>/*global describe, it*/
const expect = require('../unexpected-with-plugins');
const AssetGraph = require('../../lib/AssetGraph');
const sinon = require('sinon');

describe('assets/JavaScript', function () {
    it('should handle a test case that has a parse error in an inline JavaScript asset', async function () {
        let firstWarning;
        await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .on('warn', err => firstWarning = firstWarning || err)
            .loadAssets('parseErrorInInlineJavaScript.html');

        expect(firstWarning, 'to be an', Error);
        expect(firstWarning.message, 'to match', /parseErrorInInlineJavaScript\.html/);
        expect(firstWarning.message, 'to match', /line 2\b/);
    });

    it('should handle a test case that has a parse error in an external JavaScript asset', async function () {
        let firstWarning;
        await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .on('warn', err => firstWarning = firstWarning || err)
            .loadAssets('parseErrorInExternalJavaScript.html')
            .populate();

        expect(firstWarning, 'to be an', Error);
        expect(firstWarning.message, 'to match', /parseError\.js/);
        expect(firstWarning.message, 'to match', /line 6\b/);
    });

    it('should handle a test case that has a parse error in an asset not in an assetgraph', function () {
        expect(() => new AssetGraph.JavaScript({ text: 'var test)' }).parseTree, 'to throw');
    });

    it('should handle setting a new parseTree', function () {
        const one = new AssetGraph.JavaScript({ text: 'var test = "true";' });
        const two = new AssetGraph.JavaScript({ text: 'var test = "false";' });

        expect(one, 'not to have the same AST as', two);

        two.parseTree = one.parseTree;

        expect(one, 'to have the same AST as', two);
    });

    it('should handle minification', function () {
        const one = new AssetGraph.JavaScript({ text: 'function test (argumentName) { return argumentName; }' });
        const two = new AssetGraph.JavaScript({ text: 'function test (argumentName) { return argumentName; }' });

        expect(one, 'to have the same AST as', two);

        two.minify();

        expect(one.text, 'not to equal', two.text);
        expect(two.text, 'to equal', 'function test(argumentName){return argumentName}');
    });

    it('should handle invalid arguments for Amd define call', async function () {
        sinon.stub(console, 'info');

        const invalidArgument = new AssetGraph.JavaScript({
            isRequired: true,
            text: 'define([1], function () {})'
        });

        invalidArgument.findOutgoingRelationsInParseTree();

        await new AssetGraph({ root: '.' })
            .loadAssets([
                invalidArgument
            ])
            .populate();
    });

    it('should preserve the copyright notice in a JavaScript asset', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('copyrightNotice.js');

        const javaScript = assetGraph.findAssets({type: 'JavaScript'})[0];
        javaScript.parseTree.body.push({
            type: 'VariableDeclaration',
            kind: 'var',
            declarations: [
                {
                    type: 'VariableDeclarator',
                    id: {
                        type: 'Identifier',
                        name: 'foo'
                    },
                    init: { type: 'Literal', value: 'quux' }
                }
            ]
        });
        javaScript.markDirty();

        expect(javaScript.text, 'to match', /Copyright blablabla/);
    });

    it('should handle a test case with JavaScript assets that have regular comments as the first non-whitespace tokens', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('initialComment*.js');

        for (const javaScript of assetGraph.findAssets({type: 'JavaScript'})) {
            javaScript.parseTree.body.push({
                type: 'VariableDeclaration',
                declarations: [
                    {
                        type: 'VariableDeclarator',
                        id: {
                            type: 'Identifier',
                            name: 'foo'
                        },
                        kind: 'var',
                        init: { type: 'Literal', value: 'quux' }
                    }
                ]
            });
            javaScript.minify();
        }

        const javaScripts = assetGraph.findAssets({type: 'JavaScript'});
        expect(javaScripts[0].text, 'not to match', /Initial comment/);
        expect(javaScripts[1].text, 'not to match', /Initial comment/);
    });

    it('should handle a test case with a JavaScript asset that has comments right before EOF, then marking it as dirty', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('commentsBeforeEof.js')
            .populate();

        const javaScript = assetGraph.findAssets({type: 'JavaScript'})[0];
        // The reserialized JavaScript asset should still contain @preserve comment before eof, but not the quux one

        javaScript.markDirty();

        expect(javaScript.text, 'to match', /@preserve/);
        expect(javaScript.text, 'to match', /quux/);

        javaScript.minify();

        // The reserialized JavaScript asset should contain both the @preserve and the quux comment when pretty printed
        expect(javaScript.text, 'to match', /@preserve/);
        expect(javaScript.text, 'not to match', /quux/);
    });

    it('should handle a test case with conditional compilation (@cc_on)', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('conditionalCompilation.js');

        for (const javaScript of assetGraph.findAssets({type: 'JavaScript'})) {
            javaScript.markDirty();
        }

        expect(assetGraph.findAssets({type: 'JavaScript'})[0].text, 'to match', /@cc_on/);

        await assetGraph.compressJavaScript();

        // The @cc_on comment should still be in the serialization of the asset
        expect(assetGraph.findAssets({type: 'JavaScript'})[0].text, 'to match', /@cc_on/);
    });

    it('should handle a test case with global strict mode', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('globalstrict.html')
            .populate();

        expect(assetGraph.findAssets({fileName: 'globalstrict.js'})[0].strict, 'to equal', true);
        expect(assetGraph.findAssets({fileName: 'nonstrict.js'})[0].strict, 'to equal', false);
    });

    it('should tolerate ES6 syntax', function () {
        const es6Text = 'import gql from \'graphql-tag\';\nlet a = 123;';
        const javaScript = new AssetGraph.JavaScript({
            text: es6Text
        });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                { type: 'ImportDeclaration' },
                { type: 'VariableDeclaration', kind: 'let' }
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', es6Text);
    });

    it.skip('should tolerate Object spread syntax', function () {
        const text = 'const foo = { ...bar };';
        const javaScript = new AssetGraph.JavaScript({ text });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', text);
    });

    it('should tolerate JSX syntax', function () {
        const jsxText = 'function render() { return (<MyComponent />); }';
        const javaScript = new AssetGraph.JavaScript({
            text: jsxText
        });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                {
                    type: 'FunctionDeclaration',
                    body: {
                        type: 'BlockStatement',
                        body: [
                            {
                                type: 'ReturnStatement',
                                argument: {
                                    type: 'JSXElement',
                                    openingElement: {
                                        type: 'JSXOpeningElement',
                                        name: {
                                            type: 'JSXIdentifier',
                                            name: 'MyComponent'
                                        }
                                    },
                                    children: [],
                                    closingElement: null
                                }
                            }
                        ]
                    }
                }
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        // This doesn't work because escodegen doesn't support JSX:
        // expect(javaScript.text, 'to equal', jsxText);
    });

    it('should fall back to "script" mode when a parse error is encountered', function () {
        const text = 'await = 123;';
        const javaScript = new AssetGraph.JavaScript({ text });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                {
                    type: 'ExpressionStatement',
                    expression: {
                        type: 'AssignmentExpression',
                        operator: '=',
                        left: { type: 'Identifier', name: 'await' },
                        right: { type: 'Literal', value: 123 }
                    }
                }
            ],
            sourceType: 'script'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', text);
    });

    it('should emit an info event (and no warn events) when falling back to script mode', async function () {
        const errorSpy = sinon.spy().named('error');
        const warnSpy = sinon.spy().named('warn');
        const infoSpy = sinon.spy().named('info');
        await new AssetGraph()
            .on('error', errorSpy)
            .on('warn', warnSpy)
            .on('info', infoSpy)
            .loadAssets(new AssetGraph.JavaScript({
                url: 'http://example.com/script.js',
                text: 'await = 123;'
            }))
            .populate();

        expect([errorSpy, warnSpy, infoSpy], 'to have calls satisfying', () => {
            infoSpy('Could not parse http://example.com/script.js as a module, fall back to script mode\nLine 1: Unexpected identifier');
        });
    });

    it('should emit one warn event (and no other events) when neither module nor script mode works', async function () {
        const errorSpy = sinon.spy().named('error');
        const warnSpy = sinon.spy().named('warn');
        const infoSpy = sinon.spy().named('info');
        await new AssetGraph()
            .on('error', errorSpy)
            .on('warn', warnSpy)
            .on('info', infoSpy)
            .loadAssets(new AssetGraph.JavaScript({
                url: 'http://example.com/script.js',
                text: 'qwvce)'
            }))
            .populate();

        expect([errorSpy, warnSpy, infoSpy], 'to have calls satisfying', () => {
            warnSpy('Parse error in http://example.com/script.js\nLine 1: Unexpected token ) (line 1)');
        });
    });
});
<commit_msg>Add comment about object spread in test<commit_after>/*global describe, it*/
const expect = require('../unexpected-with-plugins');
const AssetGraph = require('../../lib/AssetGraph');
const sinon = require('sinon');

describe('assets/JavaScript', function () {
    it('should handle a test case that has a parse error in an inline JavaScript asset', async function () {
        let firstWarning;
        await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .on('warn', err => firstWarning = firstWarning || err)
            .loadAssets('parseErrorInInlineJavaScript.html');

        expect(firstWarning, 'to be an', Error);
        expect(firstWarning.message, 'to match', /parseErrorInInlineJavaScript\.html/);
        expect(firstWarning.message, 'to match', /line 2\b/);
    });

    it('should handle a test case that has a parse error in an external JavaScript asset', async function () {
        let firstWarning;
        await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .on('warn', err => firstWarning = firstWarning || err)
            .loadAssets('parseErrorInExternalJavaScript.html')
            .populate();

        expect(firstWarning, 'to be an', Error);
        expect(firstWarning.message, 'to match', /parseError\.js/);
        expect(firstWarning.message, 'to match', /line 6\b/);
    });

    it('should handle a test case that has a parse error in an asset not in an assetgraph', function () {
        expect(() => new AssetGraph.JavaScript({ text: 'var test)' }).parseTree, 'to throw');
    });

    it('should handle setting a new parseTree', function () {
        const one = new AssetGraph.JavaScript({ text: 'var test = "true";' });
        const two = new AssetGraph.JavaScript({ text: 'var test = "false";' });

        expect(one, 'not to have the same AST as', two);

        two.parseTree = one.parseTree;

        expect(one, 'to have the same AST as', two);
    });

    it('should handle minification', function () {
        const one = new AssetGraph.JavaScript({ text: 'function test (argumentName) { return argumentName; }' });
        const two = new AssetGraph.JavaScript({ text: 'function test (argumentName) { return argumentName; }' });

        expect(one, 'to have the same AST as', two);

        two.minify();

        expect(one.text, 'not to equal', two.text);
        expect(two.text, 'to equal', 'function test(argumentName){return argumentName}');
    });

    it('should handle invalid arguments for Amd define call', async function () {
        sinon.stub(console, 'info');

        const invalidArgument = new AssetGraph.JavaScript({
            isRequired: true,
            text: 'define([1], function () {})'
        });

        invalidArgument.findOutgoingRelationsInParseTree();

        await new AssetGraph({ root: '.' })
            .loadAssets([
                invalidArgument
            ])
            .populate();
    });

    it('should preserve the copyright notice in a JavaScript asset', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('copyrightNotice.js');

        const javaScript = assetGraph.findAssets({type: 'JavaScript'})[0];
        javaScript.parseTree.body.push({
            type: 'VariableDeclaration',
            kind: 'var',
            declarations: [
                {
                    type: 'VariableDeclarator',
                    id: {
                        type: 'Identifier',
                        name: 'foo'
                    },
                    init: { type: 'Literal', value: 'quux' }
                }
            ]
        });
        javaScript.markDirty();

        expect(javaScript.text, 'to match', /Copyright blablabla/);
    });

    it('should handle a test case with JavaScript assets that have regular comments as the first non-whitespace tokens', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('initialComment*.js');

        for (const javaScript of assetGraph.findAssets({type: 'JavaScript'})) {
            javaScript.parseTree.body.push({
                type: 'VariableDeclaration',
                declarations: [
                    {
                        type: 'VariableDeclarator',
                        id: {
                            type: 'Identifier',
                            name: 'foo'
                        },
                        kind: 'var',
                        init: { type: 'Literal', value: 'quux' }
                    }
                ]
            });
            javaScript.minify();
        }

        const javaScripts = assetGraph.findAssets({type: 'JavaScript'});
        expect(javaScripts[0].text, 'not to match', /Initial comment/);
        expect(javaScripts[1].text, 'not to match', /Initial comment/);
    });

    it('should handle a test case with a JavaScript asset that has comments right before EOF, then marking it as dirty', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('commentsBeforeEof.js')
            .populate();

        const javaScript = assetGraph.findAssets({type: 'JavaScript'})[0];
        // The reserialized JavaScript asset should still contain @preserve comment before eof, but not the quux one

        javaScript.markDirty();

        expect(javaScript.text, 'to match', /@preserve/);
        expect(javaScript.text, 'to match', /quux/);

        javaScript.minify();

        // The reserialized JavaScript asset should contain both the @preserve and the quux comment when pretty printed
        expect(javaScript.text, 'to match', /@preserve/);
        expect(javaScript.text, 'not to match', /quux/);
    });

    it('should handle a test case with conditional compilation (@cc_on)', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('conditionalCompilation.js');

        for (const javaScript of assetGraph.findAssets({type: 'JavaScript'})) {
            javaScript.markDirty();
        }

        expect(assetGraph.findAssets({type: 'JavaScript'})[0].text, 'to match', /@cc_on/);

        await assetGraph.compressJavaScript();

        // The @cc_on comment should still be in the serialization of the asset
        expect(assetGraph.findAssets({type: 'JavaScript'})[0].text, 'to match', /@cc_on/);
    });

    it('should handle a test case with global strict mode', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/assets/JavaScript/'})
            .loadAssets('globalstrict.html')
            .populate();

        expect(assetGraph.findAssets({fileName: 'globalstrict.js'})[0].strict, 'to equal', true);
        expect(assetGraph.findAssets({fileName: 'nonstrict.js'})[0].strict, 'to equal', false);
    });

    it('should tolerate ES6 syntax', function () {
        const es6Text = 'import gql from \'graphql-tag\';\nlet a = 123;';
        const javaScript = new AssetGraph.JavaScript({
            text: es6Text
        });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                { type: 'ImportDeclaration' },
                { type: 'VariableDeclaration', kind: 'let' }
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', es6Text);
    });

    // Awaiting https://github.com/jquery/esprima/issues/1588 (due for Esprima 5)
    it.skip('should tolerate Object spread syntax', function () {
        const text = 'const foo = { ...bar };';
        const javaScript = new AssetGraph.JavaScript({ text });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', text);
    });

    it('should tolerate JSX syntax', function () {
        const jsxText = 'function render() { return (<MyComponent />); }';
        const javaScript = new AssetGraph.JavaScript({
            text: jsxText
        });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                {
                    type: 'FunctionDeclaration',
                    body: {
                        type: 'BlockStatement',
                        body: [
                            {
                                type: 'ReturnStatement',
                                argument: {
                                    type: 'JSXElement',
                                    openingElement: {
                                        type: 'JSXOpeningElement',
                                        name: {
                                            type: 'JSXIdentifier',
                                            name: 'MyComponent'
                                        }
                                    },
                                    children: [],
                                    closingElement: null
                                }
                            }
                        ]
                    }
                }
            ],
            sourceType: 'module'
        });
        javaScript.markDirty();
        // This doesn't work because escodegen doesn't support JSX:
        // expect(javaScript.text, 'to equal', jsxText);
    });

    it('should fall back to "script" mode when a parse error is encountered', function () {
        const text = 'await = 123;';
        const javaScript = new AssetGraph.JavaScript({ text });
        expect(javaScript.parseTree, 'to satisfy', {
            type: 'Program',
            body: [
                {
                    type: 'ExpressionStatement',
                    expression: {
                        type: 'AssignmentExpression',
                        operator: '=',
                        left: { type: 'Identifier', name: 'await' },
                        right: { type: 'Literal', value: 123 }
                    }
                }
            ],
            sourceType: 'script'
        });
        javaScript.markDirty();
        expect(javaScript.text, 'to equal', text);
    });

    it('should emit an info event (and no warn events) when falling back to script mode', async function () {
        const errorSpy = sinon.spy().named('error');
        const warnSpy = sinon.spy().named('warn');
        const infoSpy = sinon.spy().named('info');
        await new AssetGraph()
            .on('error', errorSpy)
            .on('warn', warnSpy)
            .on('info', infoSpy)
            .loadAssets(new AssetGraph.JavaScript({
                url: 'http://example.com/script.js',
                text: 'await = 123;'
            }))
            .populate();

        expect([errorSpy, warnSpy, infoSpy], 'to have calls satisfying', () => {
            infoSpy('Could not parse http://example.com/script.js as a module, fall back to script mode\nLine 1: Unexpected identifier');
        });
    });

    it('should emit one warn event (and no other events) when neither module nor script mode works', async function () {
        const errorSpy = sinon.spy().named('error');
        const warnSpy = sinon.spy().named('warn');
        const infoSpy = sinon.spy().named('info');
        await new AssetGraph()
            .on('error', errorSpy)
            .on('warn', warnSpy)
            .on('info', infoSpy)
            .loadAssets(new AssetGraph.JavaScript({
                url: 'http://example.com/script.js',
                text: 'qwvce)'
            }))
            .populate();

        expect([errorSpy, warnSpy, infoSpy], 'to have calls satisfying', () => {
            warnSpy('Parse error in http://example.com/script.js\nLine 1: Unexpected token ) (line 1)');
        });
    });
});
<|endoftext|>


<commit_before>// Copyright 2012 The Obvious Corporation.

/*
 * This simply fetches the right version of phantom for the current platform.
 */

'use strict'

var requestProgress = require('request-progress')
var progress = require('progress')
var AdmZip = require('adm-zip')
var cp = require('child_process')
var fs = require('fs')
var helper = require('./lib/phantomjs')
var kew = require('kew')
var mkdirp = require('mkdirp')
var ncp = require('ncp')
var npmconf = require('npmconf')
var path = require('path')
var request = require('request')
var rimraf = require('rimraf')
var urlLib = require('url')
var util = require('util')
var which = require('which')

// allow to specify a completely custom download url
var customDownloadUrl = process.env.PHANTOMJS2_DOWNLOAD_URL || false
var url = 'https://bitbucket.org/ariya/phantomjs/downloads';
var cdnUrl = process.env.PHANTOMJS_CDNURL || url
var phantomVersion = process.env.PHANTOMJS2_VERSION || helper.version
var downloadUrl = cdnUrl + '/phantomjs-' + phantomVersion + '-'

var originalPath = process.env.PATH

// If the process exits without going through exit(), then we did not complete.
var validExit = false

process.on('exit', function () {
  if (!validExit) {
    console.log('Install exited unexpectedly')
    exit(1)
  }
})

// NPM adds bin directories to the path, which will cause `which` to find the
// bin for this package not the actual phantomjs bin.  Also help out people who
// put ./bin on their path
process.env.PATH = helper.cleanPath(originalPath)

var libPath = path.join(__dirname, 'lib')
var pkgPath = path.join(libPath, 'phantom')
var phantomPath = null
var tmpPath = null

// If the user manually installed PhantomJS, we want
// to use the existing version.
//
// Do not re-use a manually-installed PhantomJS with
// a different version.
//
// Do not re-use an npm-installed PhantomJS, because
// that can lead to weird circular dependencies between
// local versions and global versions.
// https://github.com/Obvious/phantomjs/issues/85
// https://github.com/Medium/phantomjs/pull/184
var whichDeferred = kew.defer()
which('phantomjs', whichDeferred.makeNodeResolver())
whichDeferred.promise
  .then(function (result) {
    phantomPath = result

    // Horrible hack to avoid problems during global install. We check to see if
    // the file `which` found is our own bin script.
    if (phantomPath.indexOf(path.join('npm', 'phantomjs')) !== -1) {
      console.log('Looks like an `npm install -g` on windows; unable to check for already installed version.')
      throw new Error('Global install')
    }

    var contents = fs.readFileSync(phantomPath, 'utf8')
    if (/NPM_INSTALL_MARKER/.test(contents)) {
      console.log('Looks like an `npm install -g`; unable to check for already installed version.')
      throw new Error('Global install')
    } else {
      var checkVersionDeferred = kew.defer()
      cp.execFile(phantomPath, ['--version'], checkVersionDeferred.makeNodeResolver())
      return checkVersionDeferred.promise
    }
  })
  .then(function (stdout) {
    var version = stdout.trim()
    if (phantomVersion == version) {
      writeLocationFile(phantomPath);
      console.log('PhantomJS is already installed at', phantomPath + '.')
      exit(0)

    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      throw new Error('Wrong version')
    }
  })
  .fail(function (err) {
    // Trying to use a local file failed, so initiate download and install
    // steps instead.
    var npmconfDeferred = kew.defer()
    npmconf.load(npmconfDeferred.makeNodeResolver())
    return npmconfDeferred.promise
  })
  .then(function (conf) {
    tmpPath = findSuitableTempDirectory(conf)

    // Can't use a global version so start a download.

    if (customDownloadUrl) {
      downloadUrl = customDownloadUrl
    } else if (process.platform === 'linux' && process.arch === 'x64') {
      downloadUrl += 'linux-x86_64.tar.bz2'
    } else if (process.platform === 'linux' && process.arch == 'ia32') {
      downloadUrl += 'linux-i686.tar.bz2'
    } else if (process.platform === 'darwin' || process.platform === 'openbsd' || process.platform === 'freebsd') {
      downloadUrl += 'macosx.zip'
    } else if (process.platform === 'win32') {
      downloadUrl += 'windows.zip'
    } else {
      console.error('Unexpected platform or architecture:', process.platform, process.arch)
      exit(1)
    }

    var fileName = downloadUrl.split('/').pop()
    var downloadedFile = path.join(tmpPath, fileName)

    // Start the install.
    if (!fs.existsSync(downloadedFile)) {
      console.log('Downloading', downloadUrl)
      console.log('Saving to', downloadedFile)
      return requestBinary(getRequestOptions(conf), downloadedFile)
    } else {
      console.log('Download already available at', downloadedFile)
      return downloadedFile
    }
  })
  .then(function (downloadedFile) {
    return extractDownload(downloadedFile)
  })
  .then(function (extractedPath) {
    return copyIntoPlace(extractedPath, pkgPath)
  })
  .then(function () {
    var location = process.platform === 'win32' ?
        path.join(pkgPath, 'phantomjs.exe') :
        path.join(pkgPath, 'bin' ,'phantomjs')
    var relativeLocation = path.relative(libPath, location)
    writeLocationFile(relativeLocation)

    // Ensure executable is executable by all users
    fs.chmodSync(location, '755')

    console.log('Done. Phantomjs binary available at', location)
    exit(0)
  })
  .fail(function (err) {
    console.error('Phantom installation failed', err, err.stack)
    exit(1)
  })

function writeLocationFile(location) {
  console.log('Writing location.js file')
  if (process.platform === 'win32') {
    location = location.replace(/\\/g, '\\\\')
  }
  fs.writeFileSync(path.join(libPath, 'location.js'),
      'module.exports.location = "' + location + '"')
}

function exit(code) {
  validExit = true
  process.env.PATH = originalPath
  process.exit(code || 0)
}

function findSuitableTempDirectory(npmConf) {
  var now = Date.now()
  var candidateTmpDirs = [
    process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
    '/tmp',
    path.join(process.cwd(), 'tmp')
  ]

  for (var i = 0; i < candidateTmpDirs.length; i++) {
    var candidatePath = path.join(candidateTmpDirs[i], 'phantomjs')

    try {
      mkdirp.sync(candidatePath, '0777')
      // Make double sure we have 0777 permissions; some operating systems
      // default umask does not allow write by default.
      fs.chmodSync(candidatePath, '0777')
      var testFile = path.join(candidatePath, now + '.tmp')
      fs.writeFileSync(testFile, 'test')
      fs.unlinkSync(testFile)
      return candidatePath
    } catch (e) {
      console.log(candidatePath, 'is not writable:', e.message)
    }
  }

  console.error('Can not find a writable tmp directory, please report issue ' +
      'on https://github.com/Obvious/phantomjs/issues/59 with as much ' +
      'information as possible.')
  exit(1)
}

function getRequestOptions(conf) {
  var options = {
    uri: downloadUrl,
    encoding: null, // Get response as a buffer
    followRedirect: true, // The default download path redirects to a CDN URL.
    headers: {},
    strictSSL: conf.get('strict-ssl')
  }

  var proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy')
  if (proxyUrl) {

    // Print using proxy
    var proxy = urlLib.parse(proxyUrl)
    if (proxy.auth) {
      // Mask password
      proxy.auth = proxy.auth.replace(/:.*$/, ':******')
    }
    console.log('Using proxy ' + urlLib.format(proxy))

    // Enable proxy
    options.proxy = proxyUrl

    // If going through proxy, spoof the User-Agent, since may commerical proxies block blank or unknown agents in headers
    options.headers['User-Agent'] = 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5'
  }

  return options
}

function requestBinary(requestOptions, filePath) {
  var deferred = kew.defer()

  var count = 0
  var notifiedCount = 0
  var writePath = filePath + '-download-' + Date.now()
  var outFile = fs.openSync(writePath, 'w')

  console.log('Receiving...')
  var bar = null
  requestProgress(request(requestOptions, function (error, response, body) {
    console.log('');
    if (!error && response.statusCode === 200) {
      fs.writeFileSync(writePath, body)
      console.log('Received ' + Math.floor(body.length / 1024) + 'K total.')
      fs.renameSync(writePath, filePath)
      deferred.resolve(filePath)

    } else if (response) {
      console.error('Error requesting archive.\n' +
          'Status: ' + response.statusCode + '\n' +
          'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
          'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
          'Make sure your network and proxy settings are correct.\n\n' +
          'If you continue to have issues, please report this full log at ' +
          'https://github.com/Medium/phantomjs')
      exit(1)
    } else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
      console.error('Error making request, SELF_SIGNED_CERT_IN_CHAIN. Please read https://github.com/Medium/phantomjs#i-am-behind-a-corporate-proxy-that-uses-self-signed-ssl-certificates-to-intercept-encrypted-traffic')
      exit(1)
    } else if (error) {
      console.error('Error making request.\n' + error.stack + '\n\n' +
          'Please report this full log at https://github.com/Medium/phantomjs')
      exit(1)
    } else {
      console.error('Something unexpected happened, please report this full ' +
          'log at https://github.com/Medium/phantomjs')
      exit(1)
    }
  })).on('progress', function (state) {
    if (!bar) {
      bar = new progress('  [:bar] :percent :etas', {total: state.total, width: 40})
    }
    bar.curr = state.received
    bar.tick(0)
  })

  return deferred.promise
}

function extractDownload(filePath) {
  var deferred = kew.defer()
  // extract to a unique directory in case multiple processes are
  // installing and extracting at once
  var extractedPath = filePath + '-extract-' + Date.now()
  var options = {cwd: extractedPath}

  mkdirp.sync(extractedPath, '0777')
  // Make double sure we have 0777 permissions; some operating systems
  // default umask does not allow write by default.
  fs.chmodSync(extractedPath, '0777')

  if (filePath.substr(-4) === '.zip') {
    console.log('Extracting zip contents')

    try {
      var zip = new AdmZip(filePath)
      zip.extractAllTo(extractedPath, true)
      deferred.resolve(extractedPath)
    } catch (err) {
      console.error('Error extracting zip')
      deferred.reject(err)
    }

  } else {
    console.log('Extracting tar contents (via spawned process)')
    cp.execFile('tar', ['jxf', filePath], options, function (err, stdout, stderr) {
      if (err) {
        console.error('Error extracting archive')
        deferred.reject(err)
      } else {
        deferred.resolve(extractedPath)
      }
    })
  }
  return deferred.promise
}

function copyIntoPlace(extractedPath, targetPath) {
  console.log('Removing', targetPath)
  return kew.nfcall(rimraf, targetPath).then(function () {
    // Look for the extracted directory, so we can rename it.
    var files = fs.readdirSync(extractedPath)
    for (var i = 0; i < files.length; i++) {
      var file = path.join(extractedPath, files[i])
      if (fs.statSync(file).isDirectory() && file.indexOf(phantomVersion) != -1) {
        console.log('Copying extracted folder', file, '->', targetPath)
        return kew.nfcall(ncp, file, targetPath)
      }
    }

    console.log('Could not find extracted file', files)
    throw new Error('Could not find extracted file')
  })
  .then(function () {
    // Cleanup extracted directory after it's been copied
    console.log('Removing', extractedPath)
    return kew.nfcall(rimraf, extractedPath).fail(function (e) {
      // Swallow the error quietly.
      console.warn(e)
      console.warn('Unable to remove temporary files at "' + extractedPath +
          '", see https://github.com/Obvious/phantomjs/issues/108 for details.')
    })
  })
}
<commit_msg>Use phantom 2.1.1 from bitbucket.org/ariya/phantomjs, closes #13<commit_after>// Copyright 2012 The Obvious Corporation.

/*
 * This simply fetches the right version of phantom for the current platform.
 */

'use strict'

var requestProgress = require('request-progress')
var progress = require('progress')
var AdmZip = require('adm-zip')
var cp = require('child_process')
var fs = require('fs')
var helper = require('./lib/phantomjs')
var kew = require('kew')
var mkdirp = require('mkdirp')
var ncp = require('ncp')
var npmconf = require('npmconf')
var path = require('path')
var request = require('request')
var rimraf = require('rimraf')
var urlLib = require('url')
var util = require('util')
var which = require('which')

// allow to specify a completely custom download url
var customDownloadUrl = process.env.PHANTOMJS2_DOWNLOAD_URL || false
var url = 'https://bitbucket.org/ariya/phantomjs/downloads';
var cdnUrl = process.env.PHANTOMJS_CDNURL || url
var phantomVersion = process.env.PHANTOMJS2_VERSION || helper.version
var downloadUrl = cdnUrl + '/phantomjs-' + phantomVersion + '-'

var originalPath = process.env.PATH

// If the process exits without going through exit(), then we did not complete.
var validExit = false

process.on('exit', function () {
  if (!validExit) {
    console.log('Install exited unexpectedly')
    exit(1)
  }
})

// NPM adds bin directories to the path, which will cause `which` to find the
// bin for this package not the actual phantomjs bin.  Also help out people who
// put ./bin on their path
process.env.PATH = helper.cleanPath(originalPath)

var libPath = path.join(__dirname, 'lib')
var pkgPath = path.join(libPath, 'phantom')
var phantomPath = null
var tmpPath = null

// If the user manually installed PhantomJS, we want
// to use the existing version.
//
// Do not re-use a manually-installed PhantomJS with
// a different version.
//
// Do not re-use an npm-installed PhantomJS, because
// that can lead to weird circular dependencies between
// local versions and global versions.
// https://github.com/Obvious/phantomjs/issues/85
// https://github.com/Medium/phantomjs/pull/184
var whichDeferred = kew.defer()
which('phantomjs', whichDeferred.makeNodeResolver())
whichDeferred.promise
  .then(function (result) {
    phantomPath = result

    // Horrible hack to avoid problems during global install. We check to see if
    // the file `which` found is our own bin script.
    if (phantomPath.indexOf(path.join('npm', 'phantomjs')) !== -1) {
      console.log('Looks like an `npm install -g` on windows; unable to check for already installed version.')
      throw new Error('Global install')
    }

    var contents = fs.readFileSync(phantomPath, 'utf8')
    if (/NPM_INSTALL_MARKER/.test(contents)) {
      console.log('Looks like an `npm install -g`; unable to check for already installed version.')
      throw new Error('Global install')
    } else {
      var checkVersionDeferred = kew.defer()
      cp.execFile(phantomPath, ['--version'], checkVersionDeferred.makeNodeResolver())
      return checkVersionDeferred.promise
    }
  })
  .then(function (stdout) {
    var version = stdout.trim()
    if (phantomVersion == version) {
      writeLocationFile(phantomPath);
      console.log('PhantomJS is already installed at', phantomPath + '.')
      exit(0)

    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      throw new Error('Wrong version')
    }
  })
  .fail(function (err) {
    // Trying to use a local file failed, so initiate download and install
    // steps instead.
    var npmconfDeferred = kew.defer()
    npmconf.load(npmconfDeferred.makeNodeResolver())
    return npmconfDeferred.promise
  })
  .then(function (conf) {
    tmpPath = findSuitableTempDirectory(conf)

    // Can't use a global version so start a download.

    if (customDownloadUrl) {
      downloadUrl = customDownloadUrl
    } else if (process.platform === 'linux' && process.arch === 'x64') {
      downloadUrl += 'linux-x86_64.tar.bz2'
    } else if (process.platform === 'linux' && process.arch == 'ia32') {
      downloadUrl += 'linux-i686.tar.bz2'
    } else if (process.platform === 'darwin' || process.platform === 'openbsd' || process.platform === 'freebsd') {
      downloadUrl += 'macosx.zip'
    } else if (process.platform === 'win32') {
      downloadUrl += 'windows.zip'
    } else {
      console.error('Unexpected platform or architecture:', process.platform, process.arch)
      exit(1)
    }

    var fileName = downloadUrl.split('/').pop()
    var downloadedFile = path.join(tmpPath, fileName)

    // Start the install.
    if (!fs.existsSync(downloadedFile)) {
      console.log('Downloading', downloadUrl)
      console.log('Saving to', downloadedFile)
      return requestBinary(getRequestOptions(conf), downloadedFile)
    } else {
      console.log('Download already available at', downloadedFile)
      return downloadedFile
    }
  })
  .then(function (downloadedFile) {
    return extractDownload(downloadedFile)
  })
  .then(function (extractedPath) {
    return copyIntoPlace(extractedPath, pkgPath)
  })
  .then(function () {
    var location = process.platform === 'win32' ?
        path.join(pkgPath, 'bin', 'phantomjs.exe') :
        path.join(pkgPath, 'bin' ,'phantomjs')
    var relativeLocation = path.relative(libPath, location)
    writeLocationFile(relativeLocation)

    // Ensure executable is executable by all users
    fs.chmodSync(location, '755')

    console.log('Done. Phantomjs binary available at', location)
    exit(0)
  })
  .fail(function (err) {
    console.error('Phantom installation failed', err, err.stack)
    exit(1)
  })

function writeLocationFile(location) {
  console.log('Writing location.js file')
  if (process.platform === 'win32') {
    location = location.replace(/\\/g, '\\\\')
  }
  fs.writeFileSync(path.join(libPath, 'location.js'),
      'module.exports.location = "' + location + '"')
}

function exit(code) {
  validExit = true
  process.env.PATH = originalPath
  process.exit(code || 0)
}

function findSuitableTempDirectory(npmConf) {
  var now = Date.now()
  var candidateTmpDirs = [
    process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
    '/tmp',
    path.join(process.cwd(), 'tmp')
  ]

  for (var i = 0; i < candidateTmpDirs.length; i++) {
    var candidatePath = path.join(candidateTmpDirs[i], 'phantomjs')

    try {
      mkdirp.sync(candidatePath, '0777')
      // Make double sure we have 0777 permissions; some operating systems
      // default umask does not allow write by default.
      fs.chmodSync(candidatePath, '0777')
      var testFile = path.join(candidatePath, now + '.tmp')
      fs.writeFileSync(testFile, 'test')
      fs.unlinkSync(testFile)
      return candidatePath
    } catch (e) {
      console.log(candidatePath, 'is not writable:', e.message)
    }
  }

  console.error('Can not find a writable tmp directory, please report issue ' +
      'on https://github.com/Obvious/phantomjs/issues/59 with as much ' +
      'information as possible.')
  exit(1)
}

function getRequestOptions(conf) {
  var options = {
    uri: downloadUrl,
    encoding: null, // Get response as a buffer
    followRedirect: true, // The default download path redirects to a CDN URL.
    headers: {},
    strictSSL: conf.get('strict-ssl')
  }

  var proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy')
  if (proxyUrl) {

    // Print using proxy
    var proxy = urlLib.parse(proxyUrl)
    if (proxy.auth) {
      // Mask password
      proxy.auth = proxy.auth.replace(/:.*$/, ':******')
    }
    console.log('Using proxy ' + urlLib.format(proxy))

    // Enable proxy
    options.proxy = proxyUrl

    // If going through proxy, spoof the User-Agent, since may commerical proxies block blank or unknown agents in headers
    options.headers['User-Agent'] = 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5'
  }

  return options
}

function requestBinary(requestOptions, filePath) {
  var deferred = kew.defer()

  var count = 0
  var notifiedCount = 0
  var writePath = filePath + '-download-' + Date.now()
  var outFile = fs.openSync(writePath, 'w')

  console.log('Receiving...')
  var bar = null
  requestProgress(request(requestOptions, function (error, response, body) {
    console.log('');
    if (!error && response.statusCode === 200) {
      fs.writeFileSync(writePath, body)
      console.log('Received ' + Math.floor(body.length / 1024) + 'K total.')
      fs.renameSync(writePath, filePath)
      deferred.resolve(filePath)

    } else if (response) {
      console.error('Error requesting archive.\n' +
          'Status: ' + response.statusCode + '\n' +
          'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
          'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
          'Make sure your network and proxy settings are correct.\n\n' +
          'If you continue to have issues, please report this full log at ' +
          'https://github.com/Medium/phantomjs')
      exit(1)
    } else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
      console.error('Error making request, SELF_SIGNED_CERT_IN_CHAIN. Please read https://github.com/Medium/phantomjs#i-am-behind-a-corporate-proxy-that-uses-self-signed-ssl-certificates-to-intercept-encrypted-traffic')
      exit(1)
    } else if (error) {
      console.error('Error making request.\n' + error.stack + '\n\n' +
          'Please report this full log at https://github.com/Medium/phantomjs')
      exit(1)
    } else {
      console.error('Something unexpected happened, please report this full ' +
          'log at https://github.com/Medium/phantomjs')
      exit(1)
    }
  })).on('progress', function (state) {
    if (!bar) {
      bar = new progress('  [:bar] :percent :etas', {total: state.total, width: 40})
    }
    bar.curr = state.received
    bar.tick(0)
  })

  return deferred.promise
}

function extractDownload(filePath) {
  var deferred = kew.defer()
  // extract to a unique directory in case multiple processes are
  // installing and extracting at once
  var extractedPath = filePath + '-extract-' + Date.now()
  var options = {cwd: extractedPath}

  mkdirp.sync(extractedPath, '0777')
  // Make double sure we have 0777 permissions; some operating systems
  // default umask does not allow write by default.
  fs.chmodSync(extractedPath, '0777')

  if (filePath.substr(-4) === '.zip') {
    console.log('Extracting zip contents')

    try {
      var zip = new AdmZip(filePath)
      zip.extractAllTo(extractedPath, true)
      deferred.resolve(extractedPath)
    } catch (err) {
      console.error('Error extracting zip')
      deferred.reject(err)
    }

  } else {
    console.log('Extracting tar contents (via spawned process)')
    cp.execFile('tar', ['jxf', filePath], options, function (err, stdout, stderr) {
      if (err) {
        console.error('Error extracting archive')
        deferred.reject(err)
      } else {
        deferred.resolve(extractedPath)
      }
    })
  }
  return deferred.promise
}

function copyIntoPlace(extractedPath, targetPath) {
  console.log('Removing', targetPath)
  return kew.nfcall(rimraf, targetPath).then(function () {
    // Look for the extracted directory, so we can rename it.
    var files = fs.readdirSync(extractedPath)
    for (var i = 0; i < files.length; i++) {
      var file = path.join(extractedPath, files[i])
      if (fs.statSync(file).isDirectory() && file.indexOf(phantomVersion) != -1) {
        console.log('Copying extracted folder', file, '->', targetPath)
        return kew.nfcall(ncp, file, targetPath)
      }
    }

    console.log('Could not find extracted file', files)
    throw new Error('Could not find extracted file')
  })
  .then(function () {
    // Cleanup extracted directory after it's been copied
    console.log('Removing', extractedPath)
    return kew.nfcall(rimraf, extractedPath).fail(function (e) {
      // Swallow the error quietly.
      console.warn(e)
      console.warn('Unable to remove temporary files at "' + extractedPath +
          '", see https://github.com/Obvious/phantomjs/issues/108 for details.')
    })
  })
}
<|endoftext|>


<commit_before>var fs = require('fs')

fs.writeFile(__dirname + '/gulpfile.js', 'console.log("Hello, World!")', function (err) {
  if (err) {
    return console.log(err)
  }
  console.log('Gulpfile created!')
})
<commit_msg>fix postinstall path issue<commit_after>var fs = require('fs')
console.log('dir: ' + process.cwd())
fs.writeFile(process.cwd() + '/gulpfile.js', 'console.log("Hello, World!")', function (err) {
  if (err) {
    return console.log(err)
  }
  console.log('Gulpfile created!')
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var os = require('os')
var path = require('path')
var nugget = require('nugget')
var extract = require('extract-zip')
var fs = require('fs')

var platform = os.platform()
var arch = os.arch()
var version = '0.18.0'
var name = 'atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'
var url = 'https://github.com/atom/atom-shell/releases/download/v'+version+'/atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'

var onerror = function(err) {
  throw err
}

var paths = {
  darwin: path.join(__dirname, './dist/Atom.app/Contents/MacOS/Atom'),
  linux: path.join(__dirname, './dist/atom'),
  win32: path.join(__dirname, './dist/atom.exe')
}

if (!paths[platform]) throw new Error('Unknown platform: '+platform)

nugget(url, {target:name, dir:__dirname, resume:true, verbose:true}, function(err) {
  if (err) return onerror(err)
  fs.writeFileSync(path.join(__dirname, 'run.bat'), '"'+paths[platform]+'"')
  extract(path.join(__dirname, name), {dir:path.join(__dirname, 'dist')}, function(err) {
    if (err) return onerror(err)
  })
})
<commit_msg>forward arguments<commit_after>#!/usr/bin/env node

var os = require('os')
var path = require('path')
var nugget = require('nugget')
var extract = require('extract-zip')
var fs = require('fs')

var platform = os.platform()
var arch = os.arch()
var version = '0.18.0'
var name = 'atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'
var url = 'https://github.com/atom/atom-shell/releases/download/v'+version+'/atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'

var onerror = function(err) {
  throw err
}

var paths = {
  darwin: path.join(__dirname, './dist/Atom.app/Contents/MacOS/Atom'),
  linux: path.join(__dirname, './dist/atom'),
  win32: path.join(__dirname, './dist/atom.exe')
}

var argv = {
  darwin: '"$@"',
  linux: '"$@"',
  win32: '"$@"' // 90% sure this isn't right
}

if (!paths[platform]) throw new Error('Unknown platform: '+platform)

nugget(url, {target:name, dir:__dirname, resume:true, verbose:true}, function(err) {
  if (err) return onerror(err)
  fs.writeFileSync(path.join(__dirname, 'run.bat'), '"'+paths[platform]+'" '+argv[platform])
  extract(path.join(__dirname, name), {dir:path.join(__dirname, 'dist')}, function(err) {
    if (err) return onerror(err)
  })
})
<|endoftext|>


<commit_before>const fs = require("fs"),
	exec = require('child_process').exec,
	modules = [
		"stc",
		"stc-eslint",
		"stc-babel",
		"stc-typescript",
		"stc-uglify",
		"stc-dep-parser",
		"stc-plugin",
		"stc-file",
		"stc-cluster",
		"stc-cache",
		"stc-demo",
		"stc-plugin-invoke",
		"stc-helper",
		"stc-replace",
		"stc-cli",
		"stc-log",
		"stc-css-combine"
	],
	STR_DASH = "========================================",
	REG_LOCAL = /^stc[\w-]*$/,
	REG_DEMO_DIR = /stc-demo$/;

var currentJob = "",
	totalPassed = 0;

Promise.resolve()
	.then(curryTask("Making stcjs dir", () => {
		if (isInStcDemo()) {
			console.log("In dir stc-demo, doesn't require so.");
			return;
		}
		return folderExistsPromise('stcjs')
			.catch(() => execPromise("mkdir stcjs"));
	}))
	.then(curryTask("Switching folder to stcjs", () => {
		if (isInStcDemo()) {
			process.chdir('../');
		} else {
			process.chdir('stcjs');
		}
		console.log('Current directory: ' + process.cwd());
	}))
	.then(curryTask("Git Cloning or pulling", () => {
		return Promise.all(modules.map((name) => {
			return folderExistsPromise(name, true)
				.then(() => execPromise('git branch | grep "* master" && git pull origin master', { cwd: name }).catch(() => {
					console.log(`${name} is not on master branch, ignore.`)
				}))
				.catch(() => execPromise(`git clone https://github.com/stcjs/${name}/`));
		}))
	}))
	.then(curryTask("Making folder node_modules", () => {
		return folderExistsPromise('node_modules')
			.catch(() => execPromise("mkdir node_modules")); // todo using `fs.mkdir`
	}))
	.then(curryTask("Making symbol link for stc projects in node_modules", () => {
		return Promise.all(modules.map((name) => {
			return folderExistsPromise(`node_modules/${name}`)
				.catch(() => execPromise(`ln -s ../${name} ${name}`, {
					cwd: `node_modules`
				}));
		}));
	}))
	.then(curryTask("Resolving all `package.json` & generating one", () => {
		return resolvePackageJSON()
	}))
	.then(curryTask("Installing npm package", () => {
		return execPromise("npm install --registry=https://registry.npm.taobao.org", {
			pipe: true
		})
	}))
	.then(() => {
		console.log(`${STR_DASH}\nAll done.`);
	})
	.catch((err) => {
		console.error(`${STR_DASH}\nError during task: ${currentJob}`);
		console.error(err);
	});

function isInStcDemo() {
	return REG_DEMO_DIR.test(process.cwd());
}

function curryTask(taskName, fn) {
	return function () {
		var startTime = +new Date();
		currentJob = taskName;
		console.log(`${STR_DASH}\nTask start: ${currentJob}`);
		return (fn() || Promise.resolve())
			.then(() => {
				var passed = new Date() - startTime;
				totalPassed += passed;
				console.log(`Task done after: ${passed}ms, total passed time: ${totalPassed}ms.`)
			});
	}
}

function resolvePackageJSON() {
	var package = {
		dependencies: {},
		devDependencies: {}
	};
	return Promise.all(
		modules.map((name) => {
			var dir = `${name}/package.json`;
			return readJSONPromise(dir)
				.then((data) => {
					setKey(data, "dependencies");
					setKey(data, "devDependencies");
				})
				.then(() => {
					console.log(`Parsed\t${dir}`);
				})
				.catch((err) => {
					console.log(`Error\t${dir}`);
					// console.error(err);
				});
		})
	).then(() => writeJSONPromise(`package.json`, package));

	function setKey(data, base) {
		for (var key in data[base]) {
			if (REG_LOCAL.test(key)) {
				continue;
			}
			if (!package[base][key] || package[base][key] > data[base][key]) {
				package[base][key] = data[base][key];
			}
		}
	}

	function readJSONPromise(file) {
		return new Promise((resolve, reject) => {
			fs.readFile(file, "utf-8", (err, data) => {
				if (err) {
					reject(err);
					return;
				}
				resolve(
					JSON.parse(data.toString())
				);
			});
		});
	}

	function writeJSONPromise(file, json) {
		return new Promise((resolve, reject) => {
			fs.writeFile(file, JSON.stringify(json, null, '\t'), "utf-8", (err, data) => {
				if (err) {
					reject(err);
					return;
				}
				resolve();
			});
		});
	}
}

function folderExistsPromise(folder, mute) {
	return new Promise((resolve, reject) => {
		fs.access(folder, fs.R_OK, (err) => {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
	}).then(() => {
		!mute && console.log(`Folder "${folder}" exists.`);
	});
}

function execPromise(cmd, options) {
	console.log(`${cmd}${options && options.cwd && ("\t@" + options.cwd) || ""}`);
	var promise = new Promise((resolve, reject) => {
		var event = exec(cmd, options, (err, stdout, stderr) => {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
		if (options && options.pipe) {
			event.stdout.pipe(process.stdout);
			event.stderr.pipe(process.stderr);
		}
	});

	return promise;
}
<commit_msg>Use SSH to clone project<commit_after>const fs = require("fs"),
	exec = require('child_process').exec,
	modules = [
		"stc",
		"stc-eslint",
		"stc-babel",
		"stc-typescript",
		"stc-uglify",
		"stc-dep-parser",
		"stc-plugin",
		"stc-file",
		"stc-cluster",
		"stc-cache",
		"stc-demo",
		"stc-plugin-invoke",
		"stc-helper",
		"stc-replace",
		"stc-cli",
		"stc-log",
		"stc-css-combine"
	],
	STR_DASH = "========================================",
	REG_LOCAL = /^stc[\w-]*$/,
	REG_DEMO_DIR = /stc-demo$/;

var currentJob = "",
	totalPassed = 0;

Promise.resolve()
	.then(curryTask("Making stcjs dir", () => {
		if (isInStcDemo()) {
			console.log("In dir stc-demo, doesn't require so.");
			return;
		}
		return folderExistsPromise('stcjs')
			.catch(() => execPromise("mkdir stcjs"));
	}))
	.then(curryTask("Switching folder to stcjs", () => {
		if (isInStcDemo()) {
			process.chdir('../');
		} else {
			process.chdir('stcjs');
		}
		console.log('Current directory: ' + process.cwd());
	}))
	.then(curryTask("Git Cloning or pulling", () => {
		return Promise.all(modules.map((name) => {
			return folderExistsPromise(name, true)
				.then(() => execPromise('git branch | grep "* master" && git pull origin master', { cwd: name }).catch(() => {
					console.log(`${name} is not on master branch, ignore.`)
				}))
				.catch(() => execPromise(`git clone git@github.com:stcjs/${name}/`));
		}))
	}))
	.then(curryTask("Making folder node_modules", () => {
		return folderExistsPromise('node_modules')
			.catch(() => execPromise("mkdir node_modules")); // todo using `fs.mkdir`
	}))
	.then(curryTask("Making symbol link for stc projects in node_modules", () => {
		return Promise.all(modules.map((name) => {
			return folderExistsPromise(`node_modules/${name}`)
				.catch(() => execPromise(`ln -s ../${name} ${name}`, {
					cwd: `node_modules`
				}));
		}));
	}))
	.then(curryTask("Resolving all `package.json` & generating one", () => {
		return resolvePackageJSON()
	}))
	.then(curryTask("Installing npm package", () => {
		return execPromise("npm install --registry=https://registry.npm.taobao.org", {
			pipe: true
		})
	}))
	.then(() => {
		console.log(`${STR_DASH}\nAll done.`);
	})
	.catch((err) => {
		console.error(`${STR_DASH}\nError during task: ${currentJob}`);
		console.error(err);
	});

function isInStcDemo() {
	return REG_DEMO_DIR.test(process.cwd());
}

function curryTask(taskName, fn) {
	return function () {
		var startTime = +new Date();
		currentJob = taskName;
		console.log(`${STR_DASH}\nTask start: ${currentJob}`);
		return (fn() || Promise.resolve())
			.then(() => {
				var passed = new Date() - startTime;
				totalPassed += passed;
				console.log(`Task done after: ${passed}ms, total passed time: ${totalPassed}ms.`)
			});
	}
}

function resolvePackageJSON() {
	var package = {
		dependencies: {},
		devDependencies: {}
	};
	return Promise.all(
		modules.map((name) => {
			var dir = `${name}/package.json`;
			return readJSONPromise(dir)
				.then((data) => {
					setKey(data, "dependencies");
					setKey(data, "devDependencies");
				})
				.then(() => {
					console.log(`Parsed\t${dir}`);
				})
				.catch((err) => {
					console.log(`Error\t${dir}`);
					// console.error(err);
				});
		})
	).then(() => writeJSONPromise(`package.json`, package));

	function setKey(data, base) {
		for (var key in data[base]) {
			if (REG_LOCAL.test(key)) {
				continue;
			}
			if (!package[base][key] || package[base][key] > data[base][key]) {
				package[base][key] = data[base][key];
			}
		}
	}

	function readJSONPromise(file) {
		return new Promise((resolve, reject) => {
			fs.readFile(file, "utf-8", (err, data) => {
				if (err) {
					reject(err);
					return;
				}
				resolve(
					JSON.parse(data.toString())
				);
			});
		});
	}

	function writeJSONPromise(file, json) {
		return new Promise((resolve, reject) => {
			fs.writeFile(file, JSON.stringify(json, null, '\t'), "utf-8", (err, data) => {
				if (err) {
					reject(err);
					return;
				}
				resolve();
			});
		});
	}
}

function folderExistsPromise(folder, mute) {
	return new Promise((resolve, reject) => {
		fs.access(folder, fs.R_OK, (err) => {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
	}).then(() => {
		!mute && console.log(`Folder "${folder}" exists.`);
	});
}

function execPromise(cmd, options) {
	console.log(`${cmd}${options && options.cwd && ("\t@" + options.cwd) || ""}`);
	var promise = new Promise((resolve, reject) => {
		var event = exec(cmd, options, (err, stdout, stderr) => {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
		if (options && options.pipe) {
			event.stdout.pipe(process.stdout);
			event.stderr.pipe(process.stderr);
		}
	});

	return promise;
}
<|endoftext|>


<commit_before>define(function(require, exports, module) {
	var preload = require('preloadImg');
	var shake = require('shake');
	var $ = require('fx');
	//create a new instance of shake.js.
	var myShakeEvent = new Shake({
		threshold: 15
	});
	function triggerShake() {

		// start listening to device motion
		myShakeEvent.start();

		// register a shake event
		window.addEventListener('shake', shakeEventDidOccur, false);
	}

	function shakeEventDidOccur () {

		//put your own code here etc.
		if(index == 6){
			alert('end~');
			myShakeEvent.stop();
			return false;
		}
		var arr=['1','2','3','4','5'];
		var i=Math.floor(Math.random()*5);
		alert(arr[i]);
		index++;
	}

	//所有的资源加载完毕才开启玩摇一摇功能
	var index = 0;
	window.onload = function() {
		triggerShake();
	};
	//判断手机横竖屏状态：
	window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
		if (window.orientation === 180 || window.orientation === 0) {
			alert('竖屏状态！');
			myShakeEvent.start();
		}
		if (window.orientation === 90 || window.orientation === -90 ){
			alert('横屏状态！');
			myShakeEvent.stop();
		}
	}, false);

	//图片预加载
	preload.init({
		imgs: [
			'./images/jinmao-load.png'
		],
		callback: function(o) {
			$('.loading .bar').width(o.progress + '%');
			$('.progress-text').html(o.progress+'%,玩命加载中...');
			setTimeout(function() {
				$('.loading').remove();
				$('.page1').removeClass('none');

			}, 200)
		}
	});

})<commit_msg>birth<commit_after>define(function(require, exports, module) {
	var preload = require('preloadImg');
	var shake = require('shake');
	var $ = require('fx');
	//create a new instance of shake.js.
	var myShakeEvent = new Shake({
		threshold: 10
	});
	function triggerShake() {

		// start listening to device motion
		myShakeEvent.start();

		// register a shake event
		window.addEventListener('shake', shakeEventDidOccur, false);
	}

	function shakeEventDidOccur () {

		//put your own code here etc.
		if(index == 6){
			alert('end~');
			myShakeEvent.stop();
			return false;
		}
		var arr=['1','2','3','4','5'];
		var i=Math.floor(Math.random()*5);
		alert(arr[i]);
		index++;
	}

	//所有的资源加载完毕才开启玩摇一摇功能
	var index = 0;
	window.onload = function() {
		triggerShake();
	};
	//判断手机横竖屏状态：
	window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
		if (window.orientation === 180 || window.orientation === 0) {
			alert('竖屏状态！');
			myShakeEvent.start();
		}
		if (window.orientation === 90 || window.orientation === -90 ){
			alert('横屏状态！');
			myShakeEvent.stop();
		}
	}, false);

	//图片预加载
	preload.init({
		imgs: [
			'./images/jinmao-load.png'
		],
		callback: function(o) {
			$('.loading .bar').width(o.progress + '%');
			$('.progress-text').html(o.progress+'%,玩命加载中...');
			setTimeout(function() {
				$('.loading').remove();
				$('.page1').removeClass('none');

			}, 200)
		}
	});

})<|endoftext|>


<commit_before>// This file is used to set up the various configs to use in the tests for
// firmwares and the like

module.exports = {
  fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'github',
    'firmata': false
  },

  npm_fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'npm': {
      'package': 'test-pkg'
    },
    'firmata': false
  },

  gh_fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'git+https://github.com/test/test-package',
    'firmata': false
  },

  gh_fw2: {
    'name': 'test_firmware2',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'firmata': false
  },

  gh_fw3: {
    'name': 'test_firmware3',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'https://github.com/test/test-package',
    'firmata': false
  },

  gh_branch_fw: {
    'name': 'test_firmware4',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'git+https://github.com/test/test-package#dev-branch',
    'firmata': false
  },

  manifest: {
    'backpack': {
      'bins': '/firmware/bin/backpack/',
      'hexPath': '/backpack.ino.hex'
    },
    'firmata': {
      'bins': '/firmware/bin/firmata/',
      'hexPath': '/firmata.ino.hex'
    }
  },

  multi_manifest: {
    'firmata': {
      'multi': true,
      'firmata1': {
        'bins': '/firmware/bin/firmata1/',
        'hexPath': '/firmata.ino.hex'
      },
      'firmata2': {
        'bins': '/firmware/bin/firmata2/',
        'hexPath': '/firmata.ino.hex'
      }
    }
  },

  options: {
    board: 'nano',
    port: '/dev/dummy',
    firmata: true,
    i2c_address: undefined,
    useFirmata: true,
    firmataName: ''
  },

  named_firmata_options: {
    board: 'nano',
    port: '/dev/dummy',
    firmata: true,
    i2c_address: undefined,
    useFirmata: true,
    firmataName: 'firmata2'
  }
}
<commit_msg>feat: added a new test firmware for gh master branch usage<commit_after>// This file is used to set up the various configs to use in the tests for
// firmwares and the like

module.exports = {
  fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'github',
    'firmata': false
  },

  npm_fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'npm': {
      'package': 'test-pkg'
    },
    'firmata': false
  },

  gh_fw: {
    'name': 'test_firmware',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'git+https://github.com/test/test-package',
    'firmata': false
  },

  gh_fw2: {
    'name': 'test_firmware2',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'firmata': false
  },

  gh_fw3: {
    'name': 'test_firmware3',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'https://github.com/test/test-package',
    'firmata': false
  },

  gh_branch_fw: {
    'name': 'test_firmware4',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'git+https://github.com/test/test-package#dev-branch',
    'firmata': false
  },

  gh_master_branch_fw: {
    'name': 'test_firmware5',
    'deviceID': 0x01,
    'creatorID': 0x00,
    'repo': 'git+https://github.com/test/test-package',
    'firmata': false
  },

  manifest: {
    'backpack': {
      'bins': '/firmware/bin/backpack/',
      'hexPath': '/backpack.ino.hex'
    },
    'firmata': {
      'bins': '/firmware/bin/firmata/',
      'hexPath': '/firmata.ino.hex'
    }
  },

  multi_manifest: {
    'firmata': {
      'multi': true,
      'firmata1': {
        'bins': '/firmware/bin/firmata1/',
        'hexPath': '/firmata.ino.hex'
      },
      'firmata2': {
        'bins': '/firmware/bin/firmata2/',
        'hexPath': '/firmata.ino.hex'
      }
    }
  },

  options: {
    board: 'nano',
    port: '/dev/dummy',
    firmata: true,
    i2c_address: undefined,
    useFirmata: true,
    firmataName: ''
  },

  named_firmata_options: {
    board: 'nano',
    port: '/dev/dummy',
    firmata: true,
    i2c_address: undefined,
    useFirmata: true,
    firmataName: 'firmata2'
  }
}
<|endoftext|>


<commit_before>describe('ConnectionManager', function() {

  it('constructor');

  it('inherits from EventEmitter');

  it('initialize', function() {

  });

  it('_startPeerConnection', function() {

  });

  it('_processQueue', function() {

  });

  it('_setupIce', function() {

  });

  it('_setupNegotiationHandler', function() {

  });

  it('_setupDataChannel', function() {

  });

  it('_makeOffer', function() {

  });

  it('_makeAnswer', function() {

  });

  it('_cleanup', function() {

  });

  it('_attachConnectionListeners', function() {

  });

  it('handleSDP', function() {

  });

  it('handleCandidate', function() {

  });

  it('handleLeave', function() {

  });

  it('close', function() {

  });

  it('connect', function() {

  });

  it('update', function() {

  });

});
<commit_msg>change untested methods to TODOs<commit_after>describe('ConnectionManager', function() {

  it('constructor');

  it('inherits from EventEmitter');

  it('_setupDataChannel');

  it('_makeOffer');

  it('_makeAnswer');

  it('_cleanup');

  it('_attachConnectionListeners');

  it('handleSDP');

  it('handleCandidate');

  it('handleLeave');

  it('close');

  it('connect');

  it('update');

});
<|endoftext|>


<commit_before>import expect from 'expect';
import dataAdapter from '../src/data-adapter.js';

describe('data-adapter', function() {
  it('should create an array of objects when passing an array of relative paths', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ],
        'myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/myfolder/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/myfolder/image2_renamed.jpg`
    }]);
  });

  it('should create an array of objects when passing an array of absolute paths', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ],
        '/myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: '/myfolder/image1.jpg'
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: '/myfolder/image2_renamed.jpg'
    }]);
  });

  it('should create an array of objects without providing the savePath parameter', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ]
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/image2_renamed.jpg`
    }]);
  });

  it('should use original image name if name property is unset or empty', function() {
    expect(
      dataAdapter(
        [
           { url: 'http://some.domain.com/image1.jpg', name: '' },
          { url: 'http://someother.domain.com/image2.jpg' }
        ],
        'myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/myfolder/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/myfolder/image2.jpg`
    }]);
  });
});
<commit_msg>test(data-adapter.spec): Adding test for duplicates<commit_after>import expect from 'expect';
import dataAdapter from '../src/data-adapter.js';

describe('data-adapter', function() {
  it('should create an array of objects when passing an array of relative paths', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ],
        'myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/myfolder/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/myfolder/image2_renamed.jpg`
    }]);
  });

  it('should create an array of objects when passing an array of absolute paths', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ],
        '/myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: '/myfolder/image1.jpg'
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: '/myfolder/image2_renamed.jpg'
    }]);
  });

  it('should create an array of objects without providing the savePath parameter', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' }
        ]
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/image2_renamed.jpg`
    }]);
  });

  it('should use original image name if name property is unset or empty', function() {
    expect(
      dataAdapter(
        [
           { url: 'http://some.domain.com/image1.jpg', name: '' },
          { url: 'http://someother.domain.com/image2.jpg' }
        ],
        'myfolder'
      )
    ).toEqual([{
      host: 'some.domain.com',
      path: '/image1.jpg',
      fileName: `${process.cwd()}/myfolder/image1.jpg`
    },
    {
      host: 'someother.domain.com',
      path: '/image2.jpg',
      fileName: `${process.cwd()}/myfolder/image2.jpg`
    }]);
  });

  it('should create an array without duplicates', function() {
    expect(
      dataAdapter(
        [
          'http://some.domain.com/image1.jpg',
          'http://some.domain.com/image1.jpg',
          'http://some.domain.com/image1.jpg',
          'http://some.domain.com/image2.jpg'
        ],
        'myfolder'
      )
    ).toEqual([
      {
        host: 'some.domain.com',
        path: '/image1.jpg',
        fileName: `${process.cwd()}/myfolder/image1.jpg`
      },
      {
        host: 'some.domain.com',
        path: '/image2.jpg',
        fileName: `${process.cwd()}/myfolder/image2.jpg`
      }
    ]);
  });
});
<|endoftext|>


<commit_before>'use strict'

var should = require('should')
var lodash = require('lodash')

module.exports = function (extract) {
  describe('sails', function () {
    it('brand with model', function () {
      [
        'loftsails racing blade',
        'loft sails racingblade',
        'loft racing blade'
      ].forEach(function (title) {
        extract.sail(title).should.be.eql({
          brand: 'Loft Sails',
          model: 'Racing Blade'
        })
      })
    })

    it('size', function () {
      var size = lodash.get(extract.sail(''), 'size')
      should(size).be.undefined()
      ;[
        '7 0',
        '7.0',
        '7,0',
        "7'0",
        '7.0m',
        '7,0m',
        "7'0m"
      ].forEach(function (sailSize) {
        var size = lodash.get(extract.sail(sailSize), 'size')
        size.should.be.equal('7.0')
      })
    })
  })
}
<commit_msg>Fix test<commit_after>'use strict'

var should = require('should')
var lodash = require('lodash')

module.exports = function (extract) {
  describe('sails', function () {
    it('brand with model', function () {
      [
        'loftsails racing blade',
        'loft sails racingblade',
        'loft racing blade'
      ].forEach(function (title) {
        extract.sail(title).should.be.eql({
          brand: 'Loft',
          model: 'Racing Blade'
        })
      })
    })

    it('size', function () {
      var size = lodash.get(extract.sail(''), 'size')
      should(size).be.undefined()
      ;[
        '7 0',
        '7.0',
        '7,0',
        "7'0",
        '7.0m',
        '7,0m',
        "7'0m"
      ].forEach(function (sailSize) {
        var size = lodash.get(extract.sail(sailSize), 'size')
        size.should.be.equal('7.0')
      })
    })
  })
}
<|endoftext|>


<commit_before>/*
 *  homestar.js
 *
 *  David Janes
 *  IOTDB.org
 *  2016-03-16
 *
 *  Copyright [2013-2016] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const iotdb = require('iotdb');
const _ = iotdb._;
const cfg = iotdb.cfg;

const path = require('path')
const fs = require('fs')
const url = require('url')

const MQTTTransport = require('iotdb-transport-mqtt').Transport;
const IOTDBTransport = require('iotdb-transport-iotdb').Transport;

const logger = iotdb.logger({
    name: 'homestar-homestar',
    module: 'homestar',
});

/*
var transport = new MQTTTransport({
    host: "A1GOKL7JWGA91X.iot.us-east-1.amazonaws.com",
    prefix: "iotdb/homestar/0/81EA6324-418D-459C-A9C4-D430F30021C7/alexa",
    ca: path.join(__dirname, "certs/rootCA.pem"),
    cert: path.join(__dirname, "certs/cert.pem"),
    key: path.join(__dirname, "certs/private.pem"),
    allow_updated: true,
});
 */

const mqtt_transport = function(locals) {
    const certificate_id = _.d.get(locals.homestar.settings, "aws/mqtt/certificate_id");
    if (!certificate_id) {
        logger.error({
            method: "mqtt_transport",
            cause: "likely you haven't set up module homestar-homestar correctly",
        }, "missing settings.aws.mqtt.certificate_id");
        return null;
    }

    const search = [".iotdb", "$HOME/.iotdb", ];
    const folder_name = path.join("certs", certificate_id);
    const folders = cfg.cfg_find(cfg.cfg_envd(), search, folder_name);
    if (folders.length === 0) {
        logger.error({
            method: "mqtt_transport",
            search: [".iotdb", "$HOME/.iotdb", ],
            folder_name: path.join("certs", certificate_id),
            cause: "are you running in the wrong folder - check .iotdb/certs",
        }, "could not find the 'certs' folder");
        return null;
    }
    const cert_folder = folders[0];

    const aws_url = _.d.get(locals.homestar.settings, "aws/mqtt/url");
    const aws_urlp = url.parse(aws_url);

    return new MQTTTransport({
        host: aws_urlp.host,
        prefix: aws_urlp.path.replace(/^\//, ''),
        ca: path.join(cert_folder, "rootCA.pem"),
        cert: path.join(cert_folder, "cert.pem"),
        key: path.join(cert_folder, "private.pem"),
        allow_updated: true,
    });
};

/**
 *  Functions defined in index.setup
 */
var on_ready = function(locals) {
    console.log("on_ready");
        // console.log("HERE:XXX", locals.homestar.settings.aws);
        // console.log(locals.homestar.things);
        // console.log(locals.homestar.recipes);
        mqtt_transport(locals);
        process.exit();

    /*
    transport.updated({
        id: 'FirstIntent',
        band: 'command',
    }, function(error, ud) {
        if (error) {
            console.log("#", error);
            return;
        }

        console.log("+", ud.value);
    });
     */
};

exports.on_ready = on_ready;
<commit_msg>add in MQTT bindings through cfg certs<commit_after>/*
 *  homestar.js
 *
 *  David Janes
 *  IOTDB.org
 *  2016-03-16
 *
 *  Copyright [2013-2016] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const iotdb = require('iotdb');
const _ = iotdb._;
const cfg = iotdb.cfg;

const path = require('path')
const fs = require('fs')
const url = require('url')

const iotdb_transport = require('iotdb-transport');
const MQTTTransport = require('iotdb-transport-mqtt').Transport;
const IOTDBTransport = require('iotdb-transport-iotdb').Transport;

const logger = iotdb.logger({
    name: 'homestar-homestar',
    module: 'homestar',
});

/*
var transport = new MQTTTransport({
    host: "A1GOKL7JWGA91X.iot.us-east-1.amazonaws.com",
    prefix: "iotdb/homestar/0/81EA6324-418D-459C-A9C4-D430F30021C7/alexa",
    ca: path.join(__dirname, "certs/rootCA.pem"),
    cert: path.join(__dirname, "certs/cert.pem"),
    key: path.join(__dirname, "certs/private.pem"),
    allow_updated: true,
});
 */

const make_mqtt_transporter = function(locals) {
    const certificate_id = _.d.get(locals.homestar.settings, "aws/mqtt/certificate_id");
    if (!certificate_id) {
        logger.error({
            method: "make_mqtt_transporter",
            cause: "likely you haven't set up module homestar-homestar correctly",
        }, "missing settings.aws.mqtt.certificate_id");
        return null;
    }

    const search = [".iotdb", "$HOME/.iotdb", ];
    const folder_name = path.join("certs", certificate_id);
    const folders = cfg.cfg_find(cfg.cfg_envd(), search, folder_name);
    if (folders.length === 0) {
        logger.error({
            method: "make_mqtt_transporter",
            search: [".iotdb", "$HOME/.iotdb", ],
            folder_name: path.join("certs", certificate_id),
            cause: "are you running in the wrong folder - check .iotdb/certs",
        }, "could not find the 'certs' folder");
        return null;
    }
    const cert_folder = folders[0];

    const aws_url = _.d.get(locals.homestar.settings, "aws/mqtt/url");
    const aws_urlp = url.parse(aws_url);

    return new MQTTTransport({
        host: aws_urlp.host,
        prefix: aws_urlp.path.replace(/^\//, ''),
        ca: path.join(cert_folder, "rootCA.pem"),
        cert: path.join(cert_folder, "cert.pem"),
        key: path.join(cert_folder, "private.pem"),
        allow_updated: true,
    });
};

/**
 *  Functions defined in index.setup
 */
var on_ready = function(locals) {
    const mqtt_transporter = make_mqtt_transporter(locals);
    const iotdb_transporter = locals.homestar.things.make_transporter();
    const owner = locals.homestar.users.owner();

    iotdb_transport.bind(iotdb_transporter, mqtt_transporter, {
        bands: [ "meta", "istate", "ostate", "model", ],
        user: owner,
    });

    logger.info({
        method: "on_ready",
    }, "connected AWS to Things");
};

exports.on_ready = on_ready;
<|endoftext|>