<commit_before>
var http = require('http'),
    events = require('events'),
    queryString = require('querystring'),
    sys = require('sys');

require('./ext');

try {
    var inspect = require('eyes').inspector();
} catch (e) {
    var inspect = function (obj) { sys.puts(sys.inspect(obj).white) }
}

var consoles = [];

this.Console = function (host, port, options) {
    this.host = host;
    this.port = port;
    this.options = options;
    this.path = [''];
    this.socket = null;
    this.cookies = {};
    consoles.push(this);
};

this.Console.prototype = new(function () {
    this.initialize = function () {
        var that = this;

        this.socket  = http.createClient(this.port, this.host, this.options.useSSL);
        this.headers = { 'Accept':'*/*' };

        this.stdin = process.openStdin();
        this.stdin.setEncoding('utf8');
        this.stdin.addListener('data', function (str) {
            that.exec(str.trim());
        });
        this.prompt();

        return this;
    };
    this.request = function (method, path, callback) {
        var request, that = this;

        this.headers['Host'] = this.host;

        request = this.socket.request(method.toUpperCase(),
                                      path,
                                      this.headers);

        request.addListener('response', function (res) {
            var body = "";

            if (that.options.rememberCookies) { that.rememberCookies(res.headers) }
            res.addListener('data', function (chunk) { body += chunk });
            res.addListener('end',  function ()      { callback(res, body) });
        });

        return request;
    };
    this.exec = function (command) {
        var method, headers = {}, path = this.path, body,
            that = this,
            match;

        if (this.waitingForData) {
            this.waitingForData.write(command);
            this.waitingForData.end();
            this.waitingForData = false;
            return;
        } else if (command[0] === '/') {
            Array.prototype.push.apply(
                this.path, command.split('/').filter(function (e) { return e })
            );
        } else if (command === '..') {
            this.path.pop();
        } else if (command[0] === '\\') {
            switch (command.slice(1)) {
                case 'headers':
                    this.printHeaders(this.headers);
                    break;
                case 'options':
                    inspect(this.options);
                    break;
                case 'cookies':
                    inspect(this.cookies);
                    break;
                case 'exit':
                case 'q':
                    process.exit(0);
            }
        } else if (match = command.match(/([a-zA-Z-]+):\s*(.*)/)) {
            if (match[2]) {
                this.headers[match[1]] = match[2];
            } else {
                delete(this.headers[match[1]]);
            }
        } else if (/^(GET|POST|PUT|HEAD|DELETE)/i.test(command)) {
            command = command.split(/\s+/);
            method  = command.shift().toUpperCase();
            path    = this.path.slice(0);

            if (command.length > 0) { path.push(command[0]) }

            path = ('/' + path.join('/')).replace(/\/+/g, '/');

            if (method === 'PUT' || method === 'POST') {
                this.waitingForData = this.request(method, path, function (res, body) {
                    that.printResponse.call(that, res, body);
                    that.prompt();
                });
                this.dataPrompt();
            } else {
                this.request(method, path, function (res, body) {
                    that.printResponse.call(that, res, body);
                    that.prompt();
                }).end();
            }
            return;
        } else if (command) {
            sys.puts(("unknown command '" + command + "'").yellow.bold);
        }
        this.prompt();
    };
    this.printResponse = function (res, body) {
        var status = ('HTTP/' + res.httpVersion +
                      ' '     + res.statusCode  +
                      ' '     + http.STATUS_CODES[res.statusCode]).bold;

        if      (res.statusCode >= 500) { status = status.red }
        else if (res.statusCode >= 400) { status = status.yellow }
        else                            { status = status.green }

        sys.puts(status);

        this.printHeaders(res.headers);

        sys.print('\n');

        try       { inspect(JSON.parse(body)) }
        catch (_) { sys.print(body.trim().white + '\n') }
    };
    this.prompt = function () {
        sys.print(((this.options.useSSL ? 'https//' : 'http://') +
                    this.host + ':' + this.port + this.path.join('/') + '> ').grey);
    };
    this.dataPrompt = function () {
        sys.print('... '.grey);
    };
    this.printHeaders = function (headers) {
        Object.keys(headers).forEach(function (k) {
            var key = k.replace(/\b([a-z])/g, function (_, m) {
                return m.toUpperCase();
            }).bold;
            sys.puts(key + ': ' + headers[k]);
        });
    };
    this.rememberCookies = function (headers) {
        var that = this;
        var parts, cookie, name, value;

        if ('set-cookie' in headers) {
            parts  = headers['set-cookie'].split(/; */);
            cookie = parts.shift().match(/^(.+?)=(.*)$/).slice(1);
            name   = cookie[0];
            value  = queryString.unescape(cookie[1]);

            this.cookies[name] = {
                value: value,
                options: {}
            };

            parts.forEach(function (part) {
                part = part.split('=');
                that.cookies[name].options[part[0]] = part[1];
            });
        }
        this.headers['Cookie'] = Object.keys(this.cookies).map(function (k) {
            return [k, queryString.escape(that.cookies[k].value) || ''].join('=');
        }).join(', ');
    };
});

process.addListener('uncaughtException', function (e) {
    sys.puts(('Error: ' + e.message).red);
    process.exit(-1);
});

process.addListener('exit', function () {
    consoles.forEach(function (c) {
        c.socket.destroy();
    });
    sys.print('\n');
});

<commit_msg>various improvements to path, and // command<commit_after>
var http = require('http'),
    events = require('events'),
    queryString = require('querystring'),
    sys = require('sys');

require('./ext');

try {
    var inspect = require('eyes').inspector();
} catch (e) {
    var inspect = function (obj) { sys.puts(sys.inspect(obj).white) }
}

var consoles = [];

this.Console = function (host, port, options) {
    this.host = host;
    this.port = port;
    this.options = options;
    this.path = [];
    this.socket = null;
    this.cookies = {};
    consoles.push(this);
};

this.Console.prototype = new(function () {
    this.initialize = function () {
        var that = this;

        this.socket  = http.createClient(this.port, this.host, this.options.useSSL);
        this.headers = { 'Accept':'*/*' };

        this.stdin = process.openStdin();
        this.stdin.setEncoding('utf8');
        this.stdin.addListener('data', function (str) {
            that.exec(str.trim());
        });
        this.prompt();

        return this;
    };
    this.request = function (method, path, callback) {
        var request, that = this;

        this.headers['Host'] = this.host;

        request = this.socket.request(method.toUpperCase(),
                                      path,
                                      this.headers);

        request.addListener('response', function (res) {
            var body = "";

            if (that.options.rememberCookies) { that.rememberCookies(res.headers) }
            res.addListener('data', function (chunk) { body += chunk });
            res.addListener('end',  function ()      { callback(res, body) });
        });

        return request;
    };
    this.exec = function (command) {
        var method, headers = {}, path = this.path, body,
            that = this,
            match;

        if (this.waitingForData) {
            this.waitingForData.write(command);
            this.waitingForData.end();
            this.waitingForData = false;
            return;
        } else if (command[0] === '/') {
            if (command === '//') {
                this.path = [];
            } else {
                Array.prototype.push.apply(
                    this.path, command.slice(1).split('/')
                );
            }
        } else if (command === '..') {
            this.path.pop();
        } else if (command[0] === '\\') {
            switch (command.slice(1)) {
                case 'headers':
                    this.printHeaders(this.headers);
                    break;
                case 'options':
                    inspect(this.options);
                    break;
                case 'cookies':
                    inspect(this.cookies);
                    break;
                case 'exit':
                case 'q':
                    process.exit(0);
            }
        } else if (match = command.match(/([a-zA-Z-]+):\s*(.*)/)) {
            if (match[2]) {
                this.headers[match[1]] = match[2];
            } else {
                delete(this.headers[match[1]]);
            }
        } else if (/^(GET|POST|PUT|HEAD|DELETE)/i.test(command)) {
            command = command.split(/\s+/);
            method  = command.shift().toUpperCase();
            path    = this.path.slice(0);

            if (command.length > 0) { path.push(command[0]) }

            path = ('/' + path.join('/')).replace(/\/+/g, '/');

            if (method === 'PUT' || method === 'POST') {
                this.waitingForData = this.request(method, path, function (res, body) {
                    that.printResponse.call(that, res, body);
                    that.prompt();
                });
                this.dataPrompt();
            } else {
                this.request(method, path, function (res, body) {
                    that.printResponse.call(that, res, body);
                    that.prompt();
                }).end();
            }
            return;
        } else if (command) {
            sys.puts(("unknown command '" + command + "'").yellow.bold);
        }
        this.prompt();
    };
    this.printResponse = function (res, body) {
        var status = ('HTTP/' + res.httpVersion +
                      ' '     + res.statusCode  +
                      ' '     + http.STATUS_CODES[res.statusCode]).bold;

        if      (res.statusCode >= 500) { status = status.red }
        else if (res.statusCode >= 400) { status = status.yellow }
        else                            { status = status.green }

        sys.puts(status);

        this.printHeaders(res.headers);

        sys.print('\n');

        try       { inspect(JSON.parse(body)) }
        catch (_) { sys.print(body.trim().white + '\n') }
    };
    this.prompt = function () {
        var path = '/' + this.path.join('/');
        sys.print(((this.options.useSSL ? 'https//' : 'http://') +
                    this.host + ':' + this.port).grey + path + '> '.grey);
    };
    this.dataPrompt = function () {
        sys.print('... '.grey);
    };
    this.printHeaders = function (headers) {
        Object.keys(headers).forEach(function (k) {
            var key = k.replace(/\b([a-z])/g, function (_, m) {
                return m.toUpperCase();
            }).bold;
            sys.puts(key + ': ' + headers[k]);
        });
    };
    this.rememberCookies = function (headers) {
        var that = this;
        var parts, cookie, name, value;

        if ('set-cookie' in headers) {
            parts  = headers['set-cookie'].split(/; */);
            cookie = parts.shift().match(/^(.+?)=(.*)$/).slice(1);
            name   = cookie[0];
            value  = queryString.unescape(cookie[1]);

            this.cookies[name] = {
                value: value,
                options: {}
            };

            parts.forEach(function (part) {
                part = part.split('=');
                that.cookies[name].options[part[0]] = part[1];
            });
        }
        this.headers['Cookie'] = Object.keys(this.cookies).map(function (k) {
            return [k, queryString.escape(that.cookies[k].value) || ''].join('=');
        }).join(', ');
    };
});

process.addListener('uncaughtException', function (e) {
    sys.puts(('Error: ' + e.message).red);
    process.exit(-1);
});

process.addListener('exit', function () {
    consoles.forEach(function (c) {
        c.socket.destroy();
    });
    sys.print('\n');
});

<|endoftext|>


<commit_before>const fs = require('fs')
const inquirer = require('inquirer')
const chalk = require('chalk')

module.exports = exports = (configFilename) => {
  return (options) => {
    const userForceOverwrite = options.force || false
    const questions = [
      {
        name: 'overwrite_file',
        message: 'A configuration file already exist. Do you want to continue ?',
        type: 'confirm',
        when: () => fileExist(configFilename) && !userForceOverwrite
      },
      {
        name: 'repo_name',
        message: 'Repository url:',
        type: 'input',
        validate: url => URL_REGEX.test(url),
        when: data => !fileExist(configFilename) || data.overwrite_file || userForceOverwrite
      },
      {
        name: 'folder_path',
        message: 'Folder path:',
        type: 'input',
        validate: path => PATH_REGEX.test(path),
        when: data => !fileExist(configFilename) || data.overwrite_file || userForceOverwrite
      }
    ]

    inquirer.prompt(questions)
      .then(data => {
        console.log(data)
        const { repo_name = null, folder_path } = data

        if (!fileExist(folder_path)) {
          log('info', 'Folder does not exist. It will be created.', ' Info ')
          fs.mkdirSync(folder_path)
        }

        const folderStat = fs.statSync(folder_path)
        if (!folderStat.isDirectory()) {
          log('error', `${folder_path} is not a folder.`, ' Abort ')
          return
        }

        const folderIsEmpty = fs.readdirSync(folder_path).length < 1
        if (!folderIsEmpty) {
          log('error', 'Folder is not empty', ' Abort ')
          return
        }
      })
  }
}

function fileExist(filename) {
  try {
    fs.accessSync(filename)
  } catch (e) {
    return false
  }

  return true
}

function log(type, message, prefix = '') {
  const options = {
    prefixColor: null,
    messageColor: null,
    logger: null
  }

  switch(type) {
    case 'error':
      options.logger = console.error
      options.messageColor = x => chalk.red(x)
      options.prefixColor = x => chalk.bgRed(chalk.black(x))
      break
    case 'info':
      options.logger = console.info
      options.messageColor = x => chalk.cyan(x)
      options.prefixColor = x => chalk.bgCyan(chalk.black(x))
      break
    case 'warn':
      options.logger = console.warn
      options.messageColor = x => chalk.yellow(x)
      options.prefixColor = x => chalk.bgYellow(chalk.black(x))
      break
    default:
      console.log(message)
      return
  }

  const args = []
  if(prefix.length > 0) { args.push(options.prefixColor(prefix)) }
  args.push(options.messageColor(message))
  options.logger(...args)
}

const URL_REGEX = /^((?:(https?):\/\/)?((?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9]))|(?:(?:(?:\w+\.){1,2}[\w]{2,3})))(?::(\d+))?((?:\/[\w]+)*)(?:\/|(\/[\w]+\.[\w]{3,4})|(\?(?:([\w]+=[\w]+)&)*([\w]+=[\w]+))?|\?(?:(wsdl|wadl))))$/
const PATH_REGEX = /^(?:(?:~|\.{1,2})?\/)+(?:[a-zA-Z\.\-\_]+\/?)*$/
<commit_msg>Remove some private methods and use utils one<commit_after>const fs = require('fs')
const inquirer = require('inquirer')
const chalk = require('chalk')

const { fileExist } = require('./fs.utils')
const { log } = require('./log.utils')

module.exports = exports = (configFilename) => {
  return (options) => {
    const userForceOverwrite = options.force || false
    const questions = [
      {
        name: 'overwrite_file',
        message: 'A configuration file already exist. Do you want to continue ?',
        type: 'confirm',
        when: () => fileExist(configFilename) && !userForceOverwrite
      },
      {
        name: 'repo_name',
        message: 'Repository url:',
        type: 'input',
        validate: url => URL_REGEX.test(url),
        when: data => !fileExist(configFilename) || data.overwrite_file || userForceOverwrite
      },
      {
        name: 'folder_path',
        message: 'Folder path:',
        type: 'input',
        validate: path => PATH_REGEX.test(path),
        when: data => !fileExist(configFilename) || data.overwrite_file || userForceOverwrite
      }
    ]

    inquirer.prompt(questions)
      .then(data => {
        console.log(data)
        const { repo_name = null, folder_path } = data

        if (!fileExist(folder_path)) {
          log('info', 'Folder does not exist. It will be created.', ' Info ')
          fs.mkdirSync(folder_path)
        }

        const folderStat = fs.statSync(folder_path)
        if (!folderStat.isDirectory()) {
          log('error', `${folder_path} is not a folder.`, ' Abort ')
          return
        }

        const folderIsEmpty = fs.readdirSync(folder_path).length < 1
        if (!folderIsEmpty) {
          log('error', 'Folder is not empty', ' Abort ')
          return
        }
      })
  }
}

const URL_REGEX = /^((?:(https?):\/\/)?((?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]|[0-9]))|(?:(?:(?:\w+\.){1,2}[\w]{2,3})))(?::(\d+))?((?:\/[\w]+)*)(?:\/|(\/[\w]+\.[\w]{3,4})|(\?(?:([\w]+=[\w]+)&)*([\w]+=[\w]+))?|\?(?:(wsdl|wadl))))$/
const PATH_REGEX = /^(?:(?:~|\.{1,2})?\/)+(?:[a-zA-Z\.\-\_]+\/?)*$/
<|endoftext|>


<commit_before>'use strict';

var estraverse = require('estraverse'),
    escallmatch = require('escallmatch'),
    SourceMapConsumer = require('source-map').SourceMapConsumer,
    clone = require('clone'),
    AssertionVisitor = require('./assertion-visitor'),
    typeName = require('type-name'),
    syntax = estraverse.Syntax,
    supportedNodeTypes = [
        syntax.Identifier,
        syntax.MemberExpression,
        syntax.CallExpression,
        syntax.UnaryExpression,
        syntax.BinaryExpression,
        syntax.LogicalExpression,
        syntax.AssignmentExpression,
        syntax.ObjectExpression,
        syntax.NewExpression,
        syntax.ArrayExpression,
        syntax.ConditionalExpression,
        syntax.UpdateExpression,
        syntax.Property
    ];

function Instrumentor (options) {
    ensureOptionPrerequisites(options);
    this.options = options;
    this.matchers = options.patterns.map(escallmatch);
}

Instrumentor.prototype.instrument = function (ast) {
    if (this.options.sourceMap) {
        this.sourceMapConsumer = new SourceMapConsumer(this.options.sourceMap);
    }

    ensureAstPrerequisites(ast, this.options);
    var that = this,
        assertionVisitor,
        skipping = false,
        result = (this.options.destructive) ? ast : clone(ast);

    estraverse.replace(result, {
        enter: function (currentNode, parentNode) {
            var controller = this,
                path = controller.path(),
                currentPath = path ? path[path.length - 1] : null;
            //console.log('enter currentNode:' + currentNode.type + ' parentNode: ' + parentNode.type + ' path: ' + path);
            if (assertionVisitor) {
                if (assertionVisitor.isCapturingArgument()) {
                    if (toBeSkipped(currentNode, parentNode, currentPath)) {
                        skipping = true;
                        return estraverse.VisitorOption.Skip;
                    }
                } else {
                    return assertionVisitor.enterArgument(currentNode, parentNode, [].concat(path));
                }
            } else {
                var candidates = that.matchers.filter(function (matcher) { return matcher.test(currentNode); });
                if (candidates.length === 1) {
                    // entering target assertion
                    var visitor = new AssertionVisitor(candidates[0], [].concat(path), that.sourceMapConsumer, that.options);
                    visitor.enter(currentNode, parentNode);
                    assertionVisitor = visitor;
                    return undefined;
                }
            }
            return undefined;
        },

        leave: function (currentNode, parentNode) {
            var controller = this,
                path = controller.path(),
                resultTree = currentNode;
            //console.log('leave ' + currentNode.type + ' path: ' + path);

            if (!assertionVisitor) {
                return undefined;
            }

            if (skipping) {
                skipping = false;
                return undefined;
            }

            if (assertionVisitor.isLeavingAssertion(path)) {
                assertionVisitor = null;
                return undefined;
            }

            if (!assertionVisitor.isCapturingArgument()) {
                return undefined;
            }

            if (isCalleeOfParent(currentNode, parentNode)) {
                return undefined;
            }

            //console.log('leave ' + currentNode.type + ' path: ' + path + ' ' + currentNode.name);
            switch(currentNode.type) {
            case syntax.Identifier:
            case syntax.MemberExpression:
            case syntax.CallExpression:
            case syntax.UnaryExpression:
            case syntax.BinaryExpression:
            case syntax.LogicalExpression:
            case syntax.AssignmentExpression:
            case syntax.UpdateExpression:
            case syntax.NewExpression:
                resultTree = assertionVisitor.captureNode(currentNode, path);
                break;
            default:
                break;
            }

            if (assertionVisitor.isLeavingArgument(path)) {
                return assertionVisitor.leaveArgument(resultTree, path);
            }

            return resultTree;
        }
    });
    return result;
};

function isCalleeOfParent(currentNode, parentNode) {
    return (parentNode.type === syntax.CallExpression || parentNode.type === syntax.NewExpression) &&
        parentNode.callee === currentNode;
}

function toBeSkipped (currentNode, parentNode, currentPath) {
    return !isSupportedNodeType(currentNode) ||
        isLeftHandSideOfAssignment(parentNode, currentPath) ||
        isObjectLiteralKey(parentNode, currentPath) ||
        isUpdateExpression(parentNode) ||
        isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentPath) ||
        isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentPath);
}

function isLeftHandSideOfAssignment(parentNode, currentPath) {
    // Do not instrument left due to 'Invalid left-hand side in assignment'
    return parentNode.type === syntax.AssignmentExpression && currentPath === 'left';
}

function isObjectLiteralKey(parentNode, currentPath) {
    // Do not instrument Object literal key
    return parentNode.type === syntax.Property && parentNode.kind === 'init' && currentPath === 'key';
}

function isUpdateExpression(parentNode) {
    // Just wrap UpdateExpression, not digging in.
    return parentNode.type === syntax.UpdateExpression;
}

function isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentPath) {
    // Do not instrument non-computed property of MemberExpression within CallExpression.
    return currentNode.type === syntax.Identifier && parentNode.type === syntax.MemberExpression && !parentNode.computed && currentPath === 'property';
}

function isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentPath) {
    // 'typeof Identifier' or 'delete Identifier' is not instrumented
    return currentNode.type === syntax.Identifier && parentNode.type === syntax.UnaryExpression && (parentNode.operator === 'typeof' || parentNode.operator === 'delete') && currentPath === 'argument';
}

function isSupportedNodeType (node) {
    return supportedNodeTypes.indexOf(node.type) !== -1;
}

function ensureAstPrerequisites (ast, options) {
    var errorMessage;
    if (typeof ast.loc === 'undefined') {
        errorMessage = 'JavaScript AST should contain location information.';
        if (options.path) {
            errorMessage += ' path: ' + options.path;
        }
        throw new Error(errorMessage);
    }
}

function ensureOptionPrerequisites (options) {
    if (typeName(options.destructive) !== 'boolean') {
        throw new Error('options.destructive should be a boolean value.');
    }
    if (typeName(options.patterns) !== 'Array') {
        throw new Error('options.patterns should be an array.');
    }
}

module.exports = Instrumentor;
<commit_msg>refactor(espower): extract toBeCaptured function<commit_after>'use strict';

var estraverse = require('estraverse'),
    escallmatch = require('escallmatch'),
    SourceMapConsumer = require('source-map').SourceMapConsumer,
    clone = require('clone'),
    AssertionVisitor = require('./assertion-visitor'),
    typeName = require('type-name'),
    syntax = estraverse.Syntax,
    supportedNodeTypes = [
        syntax.Identifier,
        syntax.MemberExpression,
        syntax.CallExpression,
        syntax.UnaryExpression,
        syntax.BinaryExpression,
        syntax.LogicalExpression,
        syntax.AssignmentExpression,
        syntax.ObjectExpression,
        syntax.NewExpression,
        syntax.ArrayExpression,
        syntax.ConditionalExpression,
        syntax.UpdateExpression,
        syntax.Property
    ];

function Instrumentor (options) {
    ensureOptionPrerequisites(options);
    this.options = options;
    this.matchers = options.patterns.map(escallmatch);
}

Instrumentor.prototype.instrument = function (ast) {
    if (this.options.sourceMap) {
        this.sourceMapConsumer = new SourceMapConsumer(this.options.sourceMap);
    }

    ensureAstPrerequisites(ast, this.options);
    var that = this,
        assertionVisitor,
        skipping = false,
        result = (this.options.destructive) ? ast : clone(ast);

    estraverse.replace(result, {
        enter: function (currentNode, parentNode) {
            var controller = this,
                path = controller.path(),
                currentPath = path ? path[path.length - 1] : null;
            //console.log('enter currentNode:' + currentNode.type + ' parentNode: ' + parentNode.type + ' path: ' + path);
            if (assertionVisitor) {
                if (assertionVisitor.isCapturingArgument()) {
                    if (toBeSkipped(currentNode, parentNode, currentPath)) {
                        skipping = true;
                        return estraverse.VisitorOption.Skip;
                    }
                } else {
                    return assertionVisitor.enterArgument(currentNode, parentNode, [].concat(path));
                }
            } else {
                var candidates = that.matchers.filter(function (matcher) { return matcher.test(currentNode); });
                if (candidates.length === 1) {
                    // entering target assertion
                    var visitor = new AssertionVisitor(candidates[0], [].concat(path), that.sourceMapConsumer, that.options);
                    visitor.enter(currentNode, parentNode);
                    assertionVisitor = visitor;
                    return undefined;
                }
            }
            return undefined;
        },

        leave: function (currentNode, parentNode) {
            var controller = this,
                path = controller.path(),
                resultTree = currentNode;
            //console.log('leave ' + currentNode.type + ' path: ' + path);

            if (!assertionVisitor) {
                return undefined;
            }

            if (skipping) {
                skipping = false;
                return undefined;
            }

            if (assertionVisitor.isLeavingAssertion(path)) {
                assertionVisitor = null;
                return undefined;
            }

            if (!assertionVisitor.isCapturingArgument()) {
                return undefined;
            }

            if (isCalleeOfParent(currentNode, parentNode)) {
                return undefined;
            }

            if (toBeCaptured(currentNode)) {
                resultTree = assertionVisitor.captureNode(currentNode, path);
            }

            if (assertionVisitor.isLeavingArgument(path)) {
                return assertionVisitor.leaveArgument(resultTree, path);
            }

            return resultTree;
        }
    });
    return result;
};

function isCalleeOfParent(currentNode, parentNode) {
    return (parentNode.type === syntax.CallExpression || parentNode.type === syntax.NewExpression) &&
        parentNode.callee === currentNode;
}

function toBeCaptured (currentNode) {
    switch(currentNode.type) {
    case syntax.Identifier:
    case syntax.MemberExpression:
    case syntax.CallExpression:
    case syntax.UnaryExpression:
    case syntax.BinaryExpression:
    case syntax.LogicalExpression:
    case syntax.AssignmentExpression:
    case syntax.UpdateExpression:
    case syntax.NewExpression:
        return true;
    default:
        return false;
    }
}

function toBeSkipped (currentNode, parentNode, currentPath) {
    return !isSupportedNodeType(currentNode) ||
        isLeftHandSideOfAssignment(parentNode, currentPath) ||
        isObjectLiteralKey(parentNode, currentPath) ||
        isUpdateExpression(parentNode) ||
        isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentPath) ||
        isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentPath);
}

function isLeftHandSideOfAssignment(parentNode, currentPath) {
    // Do not instrument left due to 'Invalid left-hand side in assignment'
    return parentNode.type === syntax.AssignmentExpression && currentPath === 'left';
}

function isObjectLiteralKey(parentNode, currentPath) {
    // Do not instrument Object literal key
    return parentNode.type === syntax.Property && parentNode.kind === 'init' && currentPath === 'key';
}

function isUpdateExpression(parentNode) {
    // Just wrap UpdateExpression, not digging in.
    return parentNode.type === syntax.UpdateExpression;
}

function isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentPath) {
    // Do not instrument non-computed property of MemberExpression within CallExpression.
    return currentNode.type === syntax.Identifier && parentNode.type === syntax.MemberExpression && !parentNode.computed && currentPath === 'property';
}

function isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentPath) {
    // 'typeof Identifier' or 'delete Identifier' is not instrumented
    return currentNode.type === syntax.Identifier && parentNode.type === syntax.UnaryExpression && (parentNode.operator === 'typeof' || parentNode.operator === 'delete') && currentPath === 'argument';
}

function isSupportedNodeType (node) {
    return supportedNodeTypes.indexOf(node.type) !== -1;
}

function ensureAstPrerequisites (ast, options) {
    var errorMessage;
    if (typeof ast.loc === 'undefined') {
        errorMessage = 'JavaScript AST should contain location information.';
        if (options.path) {
            errorMessage += ' path: ' + options.path;
        }
        throw new Error(errorMessage);
    }
}

function ensureOptionPrerequisites (options) {
    if (typeName(options.destructive) !== 'boolean') {
        throw new Error('options.destructive should be a boolean value.');
    }
    if (typeName(options.patterns) !== 'Array') {
        throw new Error('options.patterns should be an array.');
    }
}

module.exports = Instrumentor;
<|endoftext|>


<commit_before>var _ = require("underscore");
var jolokia = require("jolokia-client");
var openDB = require('./db');
var url = require('url');

function report(collection, _url, mbeans, response) {
  var records = [];
  for (var idx in response) {
    var result = response[idx];
    var status = result.status;
    var bean = mbeans[idx];
    if (status !== 200) {
      console.error("failed to read mbeans %s from %s: %j", bean, _url, result);
      return;
    }
    var date = new Date();
    var timestamp = date.getTime();
    var responseTimestamp = result.timestamp * 1000;
    var value = result.value;
    var purl = url.parse(_url, false);
    records.push({
      "type" : "jmx",
      "timestamp": responseTimestamp,
      "url": {
        "host" : purl.host,
        "port" : purl.port
      },
      "mbean": bean,
      "value": value
    });
  }
  collection.insert(records, function(err) {
    if (err) {
      console.error("failed to insert %j, because of %s", records, err);
    }
  });
}

function scan(collection, url, entry) {
    var mbeans = entry.mbeans;
    if (!_.isArray(mbeans)) {
      mbeans = [mbeans];
    }
    var client = new jolokia(url);
    client.read(mbeans, function(response) {
      if (response) {
        report(collection, url, mbeans, response);
      }
    });
}

function scrape(collection, url, master, entry) {
  var interval = entry.interval ? entry.interval : 15000;
  return setInterval(function() {
    master.isMaster(function(flag){
      if (flag) {
        scan(collection, url, entry);
      }
    });
  }, interval);
}

function JmxScrapper(config, master) {
  this.config = config;
  this.master = master;
  this.ids = [];
}

JmxScrapper.prototype.start = function(callback) {
  var self = this;
  var jmx = self.config.jmx;

  if (!jmx) {
    return callback();
  }
  openDB(self.config.mongo, function(db) {
    db.collection('measurements', function(error, collection) {
      if (error) {
        throw error;
      }
      self.collection = collection;
      _.each(jmx, function(entry) {
        _.each(entry.targets, function(url) {
            var id = scrape(collection, url, self.master, {
              "interval": entry.interval,
              "mbeans": entry.mbeans
            });
            self.ids.push(id);
        });
      });

      callback();
    });
  });
}

JmxScrapper.prototype.stop = function(callback) {
    var self = this;
    _.each(self.ids, function(id){
        clearInterval(id);
    });
    if (self.collection) {
        self.collection.close(function() {
            delete self.collection;
            if (callback) {
                callback();
            }
        });
    }
}

module.exports.start = function(config, master, callback) {
  var scrapper = new JmxScrapper(config, master);
  scrapper.start(function(svr) {
    if (callback) {
      callback(svr);
    }
  });
  return scrapper;
};
<commit_msg>not saving port if there is none.<commit_after>var _ = require("underscore");
var jolokia = require("jolokia-client");
var openDB = require('./db');
var url = require('url');

function report(collection, _url, mbeans, response) {
  var records = [];
  for (var idx in response) {
    var result = response[idx];
    var status = result.status;
    var bean = mbeans[idx];
    if (status !== 200) {
      console.error("failed to read mbeans %s from %s: %j", bean, _url, result);
      return;
    }
    var date = new Date();
    var timestamp = date.getTime();
    var responseTimestamp = result.timestamp * 1000;
    var value = result.value;
    var purl = url.parse(_url, false);
    var surl = {
        "host" : purl.host,
        "port" : purl.port
    };
    if (purl.port) {
        surl.port = purl.port;
    }
    records.push({
      "type" : "jmx",
      "timestamp": responseTimestamp,
      "url": surl,
      "mbean": bean,
      "value": value
    });
  }
  collection.insert(records, function(err) {
    if (err) {
      console.error("failed to insert %j, because of %s", records, err);
    }
  });
}

function scan(collection, url, entry) {
    var mbeans = entry.mbeans;
    if (!_.isArray(mbeans)) {
      mbeans = [mbeans];
    }
    var client = new jolokia(url);
    client.read(mbeans, function(response) {
      if (response) {
        report(collection, url, mbeans, response);
      }
    });
}

function scrape(collection, url, master, entry) {
  var interval = entry.interval ? entry.interval : 15000;
  return setInterval(function() {
    master.isMaster(function(flag){
      if (flag) {
        scan(collection, url, entry);
      }
    });
  }, interval);
}

function JmxScrapper(config, master) {
  this.config = config;
  this.master = master;
  this.ids = [];
}

JmxScrapper.prototype.start = function(callback) {
  var self = this;
  var jmx = self.config.jmx;

  if (!jmx) {
    return callback();
  }
  openDB(self.config.mongo, function(db) {
    db.collection('measurements', function(error, collection) {
      if (error) {
        throw error;
      }
      self.collection = collection;
      _.each(jmx, function(entry) {
        _.each(entry.targets, function(url) {
            var id = scrape(collection, url, self.master, {
              "interval": entry.interval,
              "mbeans": entry.mbeans
            });
            self.ids.push(id);
        });
      });

      callback();
    });
  });
}

JmxScrapper.prototype.stop = function(callback) {
    var self = this;
    _.each(self.ids, function(id){
        clearInterval(id);
    });
    if (self.collection) {
        self.collection.close(function() {
            delete self.collection;
            if (callback) {
                callback();
            }
        });
    }
}

module.exports.start = function(config, master, callback) {
  var scrapper = new JmxScrapper(config, master);
  scrapper.start(function(svr) {
    if (callback) {
      callback(svr);
    }
  });
  return scrapper;
};
<|endoftext|>


<commit_before>(function($) {

  // helper functions

  function print_array(obj, opts){
    opts.maxString = 40
    var max = obj.length > opts.maxArray ? opts.maxArray : obj.length

    var result = [];
    for (var i = 0; i < max; i++) {
      result.push($.print(obj[i], opts));
    }

    if (obj.length > max)
      result.push('... ' + (obj.length - max) + ' more')

    if (result.length == 0) return "[]"
    return "[ " + result.join(", ") + " ]"
  }

  function print_element(obj){
    if (obj.nodeType == 1)
      return "<" + obj.tagName.toLowerCase() +
                   (obj.className != "" ? " class='" + obj.className + "'" : "") +
                   (obj.id != "" ? " id='" + obj.id + "'" : "") +
             ">"
  }

  function print_object(obj, opts){
    opts.maxString = 40
    if (!opts.seen) opts.seen = []

    var result = []
    for (var k in obj) {
      if (opts.seen.indexOf(obj[k]) == -1) {
        opts.seen.push(obj[k])
        result.push(k + ": " + $.print(obj[k], opts))
      }
    }

    if (result.length == 0) return "{}"
    return "{ " + result.join(", ") + " }"
  }

  function print_jquery(obj){
    var result = []
    obj.each(function(){ result.push(this) })

    return "jQuery(length="+obj.length+")" + $.print(result)
  }

  function print_string(value, opts){
    // adapted from json2.js
    var m = {    // table of character substitutions
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\f': '\\f',
      '\r': '\\r',
      '"' : '\\"',
      '\\': '\\\\'
    }

    var r = /["\\\x00-\x1f\x7f-\x9f]/g

    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe sequences.

    var str = r.test(value) ?
        '"' + value.replace(r, function (a) {
            var c = m[a];
            if (c) {
                return c;
            }
            c = a.charCodeAt();
            return '\\u00' + Math.floor(c / 16).toString(16) +
                                       (c % 16).toString(16);
        }) + '"' :
        '"' + value + '"';

    if (opts.maxString && str.length > opts.maxString)
      return str.slice(0, opts.maxString) + '..."'
    else
      return str
  }

  $.print = function(obj, options) {
    var opts = $.extend({}, $.print.options, options || {})

    if (typeof obj == 'undefined')
      return "undefined"

    else if (typeof obj == 'boolean')
      return obj.toString()

    else if (!obj && typeof obj == 'number')
      return 'NaN'

    else if (!obj)
      return "null"

    else if (typeof obj == 'string')
      return print_string(obj, opts)

    else if (typeof obj == 'function' || obj instanceof Function)
      return (m = obj.toString().match(/^([^\{]*?)\s*{/)) ? m[1].replace(' (','(') : 'function()'

    else if (obj instanceof Array)
      return print_array(obj, opts)

    // no HTMLElement in IE6
    else if (obj.nodeType)
      return print_element(obj)

    else if (obj instanceof jQuery)
      return print_jquery(obj)

    else if (obj instanceof Object)
      return print_object(obj, opts)

    else
      return obj.toString().replace(/\n\s*/g, '')
  }

  $.print.options = {
    maxArray: 10,
    maxString: 0
  }
})(jQuery);<commit_msg>jQuery.print: no Array.prototype.indexOf in IE6, use $.inArray instead<commit_after>(function($) {

  // helper functions

  function print_array(obj, opts){
    opts.maxString = 40
    var max = obj.length > opts.maxArray ? opts.maxArray : obj.length

    var result = [];
    for (var i = 0; i < max; i++) {
      result.push($.print(obj[i], opts));
    }

    if (obj.length > max)
      result.push('... ' + (obj.length - max) + ' more')

    if (result.length == 0) return "[]"
    return "[ " + result.join(", ") + " ]"
  }

  function print_element(obj){
    if (obj.nodeType == 1)
      return "<" + obj.tagName.toLowerCase() +
                   (obj.className != "" ? " class='" + obj.className + "'" : "") +
                   (obj.id != "" ? " id='" + obj.id + "'" : "") +
             ">"
  }

  function print_object(obj, opts){
    opts.maxString = 40
    if (!opts.seen) opts.seen = []

    var result = []
    for (var k in obj) {
      if (Object.prototype.hasOwnProperty.apply(obj, [k]) &&
          $.inArray(obj[k], opts.seen) == -1) {
        opts.seen.push(obj[k])
        result.push(k + ": " + $.print(obj[k], opts))
      }
    }

    if (result.length == 0) return "{}"
    return "{ " + result.join(", ") + " }"
  }

  function print_jquery(obj){
    var result = []
    obj.each(function(){ result.push(this) })

    return "jQuery(length="+obj.length+")" + $.print(result)
  }

  function print_string(value, opts){
    // adapted from json2.js
    var m = {    // table of character substitutions
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\f': '\\f',
      '\r': '\\r',
      '"' : '\\"',
      '\\': '\\\\'
    }

    var r = /["\\\x00-\x1f\x7f-\x9f]/g

    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe sequences.

    var str = r.test(value) ?
        '"' + value.replace(r, function (a) {
            var c = m[a];
            if (c) {
                return c;
            }
            c = a.charCodeAt();
            return '\\u00' + Math.floor(c / 16).toString(16) +
                                       (c % 16).toString(16);
        }) + '"' :
        '"' + value + '"';

    if (opts.maxString && str.length > opts.maxString)
      return str.slice(0, opts.maxString) + '..."'
    else
      return str
  }

  $.print = function(obj, options) {
    var opts = $.extend({}, $.print.options, options || {})

    if (typeof obj == 'undefined')
      return "undefined"

    else if (typeof obj == 'boolean')
      return obj.toString()

    else if (!obj && typeof obj == 'number')
      return 'NaN'

    else if (!obj)
      return "null"

    else if (typeof obj == 'string')
      return print_string(obj, opts)

    else if (typeof obj == 'function' || obj instanceof Function)
      return (m = obj.toString().match(/^([^\{]*?)\s*{/)) ? m[1].replace(' (','(') : 'function()'

    else if (obj instanceof Array)
      return print_array(obj, opts)

    else if (obj.nodeType) // no HTMLElement in IE6
      return print_element(obj)

    else if (obj instanceof jQuery)
      return print_jquery(obj)

    else if (obj instanceof Object)
      return print_object(obj, opts)

    else
      return obj.toString().replace(/\n\s*/g, '')
  }

  $.print.options = {
    maxArray: 10,
    maxString: 0
  }
})(jQuery);<|endoftext|>


<commit_before>var AWS = require('../core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.JSON = {};

/**
 * @api private
 */
AWS.JSON.Builder = inherit({

  constructor: function JSONBuilder(rules, options) {
    this.rules = rules;
    this.timestampFormat = options.timestampFormat;
  },

  build: function build(params) {
    return JSON.stringify(this.translate(this.rules, params));
  },

  translate: function translate(rules, value) {
    if (rules.type == 'structure') {

      // translate structures (hashes with pre-defined keys)
      var struct = {};
      AWS.util.each.call(this, value, function (memberName, memberValue) {
        var memberRules = rules.members[memberName] || {};
        struct[memberName] = this.translate(memberRules, memberValue);
      });
      return struct;

    } else if (rules.type == 'list') {

      // translate each member of the list
      var list = [];
      AWS.util.arrayEach.call(this, value, function (memberValue) {
        var memberRules = rules.members || {};
        list.push(this.translate(memberRules, memberValue));
      });
      return list;

    } else if (rules.type == 'map') {

      // translate maps (hashes with user supplied keys)
      var map = {};
      AWS.util.each.call(this, value, function (memberName, memberValue) {
        var memberRules = rules.members || {};
        map[memberName] = translate(memberRules, memberValue);
      });
      return map;

    } else if (rules.type == 'timestamp') {

      var timestampFormat = rules.format || this.timestampFormat;
      return AWS.util.date.format(value, timestampFormat);

    } else if (rules.type == 'integer') {
      return parseInt(value, 10);
    } else if (rules.type == 'float') {
      return parseFloat(value);
    } else {

      // all other shapes
      return value;

    }
  }

});
<commit_msg>Fix translate method<commit_after>var AWS = require('../core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.JSON = {};

/**
 * @api private
 */
AWS.JSON.Builder = inherit({

  constructor: function JSONBuilder(rules, options) {
    this.rules = rules;
    this.timestampFormat = options.timestampFormat;
  },

  build: function build(params) {
    return JSON.stringify(this.translate(this.rules, params));
  },

  translate: function translate(rules, value) {
    if (rules.type == 'structure') {

      // translate structures (hashes with pre-defined keys)
      var struct = {};
      AWS.util.each.call(this, value, function (memberName, memberValue) {
        var memberRules = rules.members[memberName] || {};
        struct[memberName] = this.translate(memberRules, memberValue);
      });
      return struct;

    } else if (rules.type == 'list') {

      // translate each member of the list
      var list = [];
      AWS.util.arrayEach.call(this, value, function (memberValue) {
        var memberRules = rules.members || {};
        list.push(this.translate(memberRules, memberValue));
      });
      return list;

    } else if (rules.type == 'map') {

      // translate maps (hashes with user supplied keys)
      var map = {};
      AWS.util.each.call(this, value, function (memberName, memberValue) {
        var memberRules = rules.members || {};
        map[memberName] = this.translate(memberRules, memberValue);
      });
      return map;

    } else if (rules.type == 'timestamp') {

      var timestampFormat = rules.format || this.timestampFormat;
      return AWS.util.date.format(value, timestampFormat);

    } else if (rules.type == 'integer') {
      return parseInt(value, 10);
    } else if (rules.type == 'float') {
      return parseFloat(value);
    } else {

      // all other shapes
      return value;

    }
  }

});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var EventEmitter = require("eventEmitter"),
        adapter = require("./adapter"),
        util = require("./util"),
        Promise = require("bluebird");

    /**
     * The LayerManager provides an API for dealing with the layers of the
     * currently active document
     *
     * Right now, this is purely demonstration code. This will need to be elaborated
     * to deal with all documents (or changed to be document specific / not a singleton).
     *
     * Emits "selectionChanged" event whenever the currently selected layer changes
     * with the following parameters
     *    1. @param {String} the selected layer name
     *
     * @extends EventEmitter
     * @constructor
     * @private
     */
    var LayerManager = function () {
        EventEmitter.call(this);

        adapter.on("select", this._handleSelect.bind(this));
        adapter.on("make", this._handleSelect.bind(this));
    };
    util.inherits(LayerManager, EventEmitter);

    /**
     * Holds the currently selected layer indices
     *
     * @type {Array<number>}
     */
    LayerManager.prototype._currentSelection = null;

    /**
     * Event handler for low level select and make events
     * "Make" layer may cause selection to change as well
     * Grabs the current selected layer indices, saves them in _currentSelection
     * and emits a "selectionChanged" event with the current Selection array
     *
     * @private
     */
    LayerManager.prototype._handleSelect = function () {
        this.getSelectedLayerIndices().bind(this).then(function (layers) {
            this._currentSelection = layers;
            this.emit("selectionChanged", this._currentSelection);
        });
    };

    /**
     * Gets the action descriptor of the layer at given index
     *
     * Will check for correct index, if image is only a background layer, will return that
     *
     * @param {number} index Layer index
     * @return {Promise.<Object>} Promise that resolve to the action descriptor of the layer
     */
     LayerManager.prototype.getLayerAtIndex = function (index) {
        return adapter.getProperty("document", "numberOfLayers").then(function (layerCount) {
            if (typeof index === undefined || index < 0 || index > layerCount) {
                throw new Error("Invalid layer index");
            }

            // If only background layer, count is 0, and background layer cannot be unselected
            if (layerCount === 0) {
                return adapter.get({ref: "$Lyr", value: "$Trgt", enum: "$Ordn"});
            } else {
                return adapter.get({ref: "$Lyr", "index": index});
            }
        });
    };

    /**
     * Gets an array of layer references for all selected layers in the current document
     *
     * @return {Promise.<Array.<ref: object, index: number>>} Resolves to an array of
     *      layers with index and ref(:layer) keys
     */
    LayerManager.prototype.getSelectedLayers = function () {
        return adapter.get("document").then(function (document) {
            return document.targetLayers || [];
        });
    };

    /**
     * Gets an array of layer indices for all selected layers in the current document
     *
     * @return {Promise.<Array.<Number>>} Resolves to an array of numbers for each index of layers
     */
    LayerManager.prototype.getSelectedLayerIndices = function () {
        return this.getSelectedLayers().then(function (layers) {
            return layers.map(function (layer) {
                return layer.index;
            });
        });
    };

    /**
     * Gets the action descriptors for all selected layers
     *
     * @return {Promise.<Array.<ActionDescriptor>>} Resolves to an array of
     *     action descriptor for each selected layers
     */
    LayerManager.prototype.getSelectedLayerDescriptors = function () {
        return this.getSelectedLayerIndices().then(function (indices) {
            var layerGetPromises = indices.map(function (index) {
                return adapter.get({ref: "layer", index: index});
            });
            return Promise.all(layerGetPromises);
        });
    };

    /**
     * Creates a new layer in the currently active document.
     * The returned promise resolves/rejects when the operation is complete/has an error
     *
     * @return {Promise.<Object>} Result of the layer creation call
     */
    LayerManager.prototype.createNewLayer = function () {
        return adapter.call("$Mk", {"null" : { "ref" : "$Lyr " }});
    };

    /**
     * Gets all layers in the document with their properties
     *
     * @return {Promise.<Array.<ActionDescriptor>>} Resolves to an array of all array descriptors
     */
    LayerManager.prototype.getAllLayers = function () {
        return adapter.getProperty("document", "numberOfLayers").then(function (layerCount) {
            return adapter.getProperty("document", "hasBackgroundLayer").then(function (hasBackground) {
                var layerGets = [];
                var startIndex = hasBackground ? 0 : 1;

                for (var i = startIndex; i <= layerCount; i++) {
                    layerGets.push(adapter.get({ref: "layer", index: i}));
                }
                return Promise.all(layerGets);
            });
        });
    };

    /**
     * Duplicates layers.
     * If index is supplied, will only duplicate the indexed layer
     *
     * If only one layer is selected, and newLayerName is not null, copy will be renamed
     * Otherwise layers get copied with their original names
     * The returned promise resolves to the dupeArgs object.
     *
     * @param {?number} index Index of the layer to duplicate, default is currently selected layer(s)
     * @param {?string} newLayerName If supplied, renames the new layer, only applies when a single layer is selected
     * @return {Promise.<Object>} Promise that resolves to a reference to currently selected layer
     */
    LayerManager.prototype.duplicateLayer = function (index, newLayerName) {
        var nullArgs = { "ref": "$Lyr" };

        // This way we can either choose the current layer or a layer by index
        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var dupeArgs = { "null" : nullArgs };
        dupeArgs.$Vrsn = 5;

        if (newLayerName) {
            dupeArgs["$Nm  "] = newLayerName;
        }

        return adapter.call("$Dplc", dupeArgs);
    };

    /**
     * Moves a layer
     * If index is null, will move the selected layer
     *
     * @param {?number} index Index of the layer to move, default is currently selected layer
     * @param {?number} dx Pixel value to move the layer horizontally (Default 0)
     * @param {?number} dy Pixel value to move the layer vertically (Default 0)
     * @return {Promise.<Object>} Promise that resolves to empty object
     */
    LayerManager.prototype.moveLayer = function (index, dx, dy) {
        var nullArgs = { "ref": "$Lyr" };

        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var selectArgs = {"null": nullArgs};

        // If index is given, this ensures that the layer with given index is selected first
        // Otherwise, is a no-op and will move on to copying the layer
        return adapter.call("$slct", selectArgs).then(function () {
            var moveArgs = { "null": nullArgs };

            moveArgs.to = {
                "obj": "Offset",
                "value": {
                    "horizontal": {
                        "unit": "pixelsUnit",
                        "value": dx || 0
                    },
                    "vertical": {
                        "unit": "pixelsUnit",
                        "value": dy || 0
                    }
                }
            };

            return adapter.call("move", moveArgs);
        });
    };

    /**
     * Copies a layer and moves it
     * If index is null, will copy the selected layer
     *
     * @param {?number=} index Index of the layer to copy, default is currently selected layer
     * @param {?number} dx Pixel value to move the copied layer horizontally (Default 0)
     * @param {?number} dy Pixel value to move the copied layer vertically (Default 0)
     * @return {Promise.<Object>} Promise that resolves to empty object
     */
    LayerManager.prototype.copyLayer = function (index, dx, dy) {
        var nullArgs = { "ref": "$Lyr" };

        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var selectArgs = {"null": nullArgs};

        // If index is given, this ensures that the layer with given index is selected first
        // Otherwise, is a no-op and will move on to copying the layer
        return adapter.call("$slct", selectArgs).then(function () {
            var copyArgs = { "null": nullArgs };

            copyArgs.to = {
                "obj": "Offset",
                "value": {
                    "horizontal": {
                        "unit": "pixelsUnit",
                        "value": dx || 0
                    },
                    "vertical": {
                        "unit": "pixelsUnit",
                        "value": dy || 0
                    }
                }
            };

            return adapter.call("copyEvent", copyArgs);
        });
    };

    /** @type {LayerManager} The LayerManager singleton */
    var theLayerManager = new LayerManager();

    module.exports = theLayerManager;

});
<commit_msg>Whitespaces fixes<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var EventEmitter = require("eventEmitter"),
        adapter = require("./adapter"),
        util = require("./util"),
        Promise = require("bluebird");

    /**
     * The LayerManager provides an API for dealing with the layers of the
     * currently active document
     *
     * Right now, this is purely demonstration code. This will need to be elaborated
     * to deal with all documents (or changed to be document specific / not a singleton).
     *
     * Emits "selectionChanged" event whenever the currently selected layer changes
     * with the following parameters
     *    1. @param {String} the selected layer name
     *
     * @extends EventEmitter
     * @constructor
     * @private
     */
    var LayerManager = function () {
        EventEmitter.call(this);

        adapter.on("select", this._handleSelect.bind(this));
        adapter.on("make", this._handleSelect.bind(this));
    };
    util.inherits(LayerManager, EventEmitter);

    /**
     * Holds the currently selected layer indices
     *
     * @type {Array<number>}
     */
    LayerManager.prototype._currentSelection = null;

    /**
     * Event handler for low level select and make events
     * "Make" layer may cause selection to change as well
     * Grabs the current selected layer indices, saves them in _currentSelection
     * and emits a "selectionChanged" event with the current Selection array
     *
     * @private
     */
    LayerManager.prototype._handleSelect = function () {
        this.getSelectedLayerIndices().bind(this).then(function (layers) {
            this._currentSelection = layers;
            this.emit("selectionChanged", this._currentSelection);
        });
    };

    /**
     * Gets the action descriptor of the layer at given index
     *
     * Will check for correct index, if image is only a background layer, will return that
     *
     * @param {number} index Layer index
     * @return {Promise.<Object>} Promise that resolve to the action descriptor of the layer
     */
    LayerManager.prototype.getLayerAtIndex = function (index) {
        return adapter.getProperty("document", "numberOfLayers").then(function (layerCount) {
            if (typeof index === undefined || index < 0 || index > layerCount) {
                throw new Error("Invalid layer index");
            }

            // If only background layer, count is 0, and background layer cannot be unselected
            if (layerCount === 0) {
                return adapter.get({ref: "$Lyr", value: "$Trgt", enum: "$Ordn"});
            } else {
                return adapter.get({ref: "$Lyr", "index": index});
            }
        });
    };

    /**
     * Gets an array of layer references for all selected layers in the current document
     *
     * @return {Promise.<Array.<ref: object, index: number>>} Resolves to an array of
     *      layers with index and ref(:layer) keys
     */
    LayerManager.prototype.getSelectedLayers = function () {
        return adapter.get("document").then(function (document) {
            return document.targetLayers || [];
        });
    };

    /**
     * Gets an array of layer indices for all selected layers in the current document
     *
     * @return {Promise.<Array.<Number>>} Resolves to an array of numbers for each index of layers
     */
    LayerManager.prototype.getSelectedLayerIndices = function () {
        return this.getSelectedLayers().then(function (layers) {
            return layers.map(function (layer) {
                return layer.index;
            });
        });
    };

    /**
     * Gets the action descriptors for all selected layers
     *
     * @return {Promise.<Array.<ActionDescriptor>>} Resolves to an array of
     *     action descriptor for each selected layers
     */
    LayerManager.prototype.getSelectedLayerDescriptors = function () {
        return this.getSelectedLayerIndices().then(function (indices) {
            var layerGetPromises = indices.map(function (index) {
                return adapter.get({ref: "layer", index: index});
            });
            return Promise.all(layerGetPromises);
        });
    };

    /**
     * Creates a new layer in the currently active document.
     * The returned promise resolves/rejects when the operation is complete/has an error
     *
     * @return {Promise.<Object>} Result of the layer creation call
     */
    LayerManager.prototype.createNewLayer = function () {
        return adapter.call("$Mk", {"null" : { "ref" : "$Lyr " }});
    };

    /**
     * Gets all layers in the document with their properties
     *
     * @return {Promise.<Array.<ActionDescriptor>>} Resolves to an array of all array descriptors
     */
    LayerManager.prototype.getAllLayers = function () {
        return adapter.getProperty("document", "numberOfLayers").then(function (layerCount) {
            return adapter.getProperty("document", "hasBackgroundLayer").then(function (hasBackground) {
                var layerGets = [];
                var startIndex = hasBackground ? 0 : 1;

                for (var i = startIndex; i <= layerCount; i++) {
                    layerGets.push(adapter.get({ref: "layer", index: i}));
                }
                return Promise.all(layerGets);
            });
        });
    };

    /**
     * Duplicates layers.
     * If index is supplied, will only duplicate the indexed layer
     *
     * If only one layer is selected, and newLayerName is not null, copy will be renamed
     * Otherwise layers get copied with their original names
     * The returned promise resolves to the dupeArgs object.
     *
     * @param {?number} index Index of the layer to duplicate, default is currently selected layer(s)
     * @param {?string} newLayerName If supplied, renames the new layer, only applies when a single layer is selected
     * @return {Promise.<Object>} Promise that resolves to a reference to currently selected layer
     */
    LayerManager.prototype.duplicateLayer = function (index, newLayerName) {
        var nullArgs = { "ref": "$Lyr" };

        // This way we can either choose the current layer or a layer by index
        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var dupeArgs = { "null" : nullArgs };
        dupeArgs.$Vrsn = 5;

        if (newLayerName) {
            dupeArgs["$Nm  "] = newLayerName;
        }

        return adapter.call("$Dplc", dupeArgs);
    };

    /**
     * Moves a layer
     * If index is null, will move the selected layer
     *
     * @param {?number} index Index of the layer to move, default is currently selected layer
     * @param {?number} dx Pixel value to move the layer horizontally (Default 0)
     * @param {?number} dy Pixel value to move the layer vertically (Default 0)
     * @return {Promise.<Object>} Promise that resolves to empty object
     */
    LayerManager.prototype.moveLayer = function (index, dx, dy) {
        var nullArgs = { "ref": "$Lyr" };

        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var selectArgs = {"null": nullArgs};

        // If index is given, this ensures that the layer with given index is selected first
        // Otherwise, is a no-op and will move on to copying the layer
        return adapter.call("$slct", selectArgs).then(function () {
            var moveArgs = { "null": nullArgs };

            moveArgs.to = {
                "obj": "Offset",
                "value": {
                    "horizontal": {
                        "unit": "pixelsUnit",
                        "value": dx || 0
                    },
                    "vertical": {
                        "unit": "pixelsUnit",
                        "value": dy || 0
                    }
                }
            };

            return adapter.call("move", moveArgs);
        });
    };

    /**
     * Copies a layer and moves it
     * If index is null, will copy the selected layer
     *
     * @param {?number=} index Index of the layer to copy, default is currently selected layer
     * @param {?number} dx Pixel value to move the copied layer horizontally (Default 0)
     * @param {?number} dy Pixel value to move the copied layer vertically (Default 0)
     * @return {Promise.<Object>} Promise that resolves to empty object
     */
    LayerManager.prototype.copyLayer = function (index, dx, dy) {
        var nullArgs = { "ref": "$Lyr" };

        if (index !== null) {
            nullArgs.index = index;
        } else {
            nullArgs.enum = "$Ordn";
            nullArgs.value = "$Trgt";
        }

        var selectArgs = {"null": nullArgs};

        // If index is given, this ensures that the layer with given index is selected first
        // Otherwise, is a no-op and will move on to copying the layer
        return adapter.call("$slct", selectArgs).then(function () {
            var copyArgs = { "null": nullArgs };

            copyArgs.to = {
                "obj": "Offset",
                "value": {
                    "horizontal": {
                        "unit": "pixelsUnit",
                        "value": dx || 0
                    },
                    "vertical": {
                        "unit": "pixelsUnit",
                        "value": dy || 0
                    }
                }
            };

            return adapter.call("copyEvent", copyArgs);
        });
    };

    /** @type {LayerManager} The LayerManager singleton */
    var theLayerManager = new LayerManager();

    module.exports = theLayerManager;

});
<|endoftext|>


<commit_before>var fs = require("fs")
  , path = require("path")
  , through = require("through")
  , extend = require("extend")
  , marked = require("marked")
  , highlight = require('highlight.js')
  , tmp = require("tmp")
  , childProcess = require("child_process")
  , duplexer = require("duplexer")
  , streamft = require("stream-from-to")

tmp.setGracefulCleanup()

function markdownpdf (opts) {
  opts = opts || {}
  opts.phantomPath = opts.phantomPath || require("phantomjs").path
  opts.runningsPath = path.resolve(__dirname + "/..", opts.runningsPath || '') || __dirname + "/runnings.js"
  opts.cssPath = opts.cssPath || __dirname + "/../pdf.css"
  opts.highlightCssPath = opts.highlightCssPath || __dirname + "/../highlight.css"
  opts.paperFormat = opts.paperFormat || "A4"
  opts.paperOrientation = opts.paperOrientation || "portrait"
  opts.paperBorder = opts.paperBorder || "1cm"
  opts.renderDelay = opts.renderDelay || 500
  opts.preProcessMd = opts.preProcessMd || function () { return through() }
  opts.preProcessHtml = opts.preProcessHtml || function () { return through() }

  var md = ""

  // set options for marked
  var markedOptions = {
    highlight: function (code, lang) {
      if (lang) {
        return highlight.highlight(lang, code).value;
      } else {
        return highlight.highlightAuto(code).value;
      }

    }
  }

  // Argh! marked, why you no stream?
  var mdToHtml = through(
    function write (data) {
      md += data
    },
    function end () {
      var html = marked(md, markedOptions)
      this.queue(html)
      this.queue(null)
    }
  )

  var inputStream = through()
    , outputStream = through()

  // Stop input stream emitting data events until we're ready to read them
  inputStream.pause()

  // Create tmp file to save HTML for phantom to process
  tmp.file({postfix: ".html"}, function (er, tmpHtmlPath, tmpHtmlFd) {
    if (er) return outputStream.emit("error", er)
    fs.close(tmpHtmlFd)

    // Create tmp file to save PDF to
    tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath, tmpPdfFd) {
      if (er) return outputStream.emit("error", er)
      fs.close(tmpPdfFd)

      var htmlToTmpHtmlFile = fs.createWriteStream(tmpHtmlPath)

      htmlToTmpHtmlFile.on("finish", function () {
        // Invoke phantom to generate the PDF
        var childArgs = [
            path.join(__dirname, "..", "lib-phantom", "markdown-pdf.js")
          , tmpHtmlPath
          , tmpPdfPath
          , opts.runningsPath
          , opts.cssPath
          , opts.highlightCssPath
          , opts.paperFormat
          , opts.paperOrientation
          , opts.paperBorder
          , opts.renderDelay
        ]

        childProcess.execFile(opts.phantomPath, childArgs, function(er, stdout, stderr) {
          //if (stdout) console.log(stdout)
          //if (stderr) console.error(stderr)
          if (er) return outputStream.emit("error", er)
          fs.createReadStream(tmpPdfPath).pipe(outputStream)
        })
      })

      // Setup the pipeline
      inputStream.pipe(opts.preProcessMd()).pipe(mdToHtml).pipe(opts.preProcessHtml()).pipe(htmlToTmpHtmlFile)
      inputStream.resume()
    })
  })

  return extend(
    duplexer(inputStream, outputStream),
    streamft(function () {
      return markdownpdf(opts)
    })
  )
}

module.exports = markdownpdf<commit_msg>check if language exists in highlight.js<commit_after>var fs = require("fs")
  , path = require("path")
  , through = require("through")
  , extend = require("extend")
  , marked = require("marked")
  , highlight = require('highlight.js')
  , tmp = require("tmp")
  , childProcess = require("child_process")
  , duplexer = require("duplexer")
  , streamft = require("stream-from-to")

tmp.setGracefulCleanup()

function markdownpdf (opts) {
  opts = opts || {}
  opts.phantomPath = opts.phantomPath || require("phantomjs").path
  opts.runningsPath = path.resolve(__dirname + "/..", opts.runningsPath || '') || __dirname + "/runnings.js"
  opts.cssPath = opts.cssPath || __dirname + "/../pdf.css"
  opts.highlightCssPath = opts.highlightCssPath || __dirname + "/../highlight.css"
  opts.paperFormat = opts.paperFormat || "A4"
  opts.paperOrientation = opts.paperOrientation || "portrait"
  opts.paperBorder = opts.paperBorder || "1cm"
  opts.renderDelay = opts.renderDelay || 500
  opts.preProcessMd = opts.preProcessMd || function () { return through() }
  opts.preProcessHtml = opts.preProcessHtml || function () { return through() }

  var md = ""

  // set options for marked
  var markedOptions = {
    highlight: function (code, lang) {

      if (lang && highlight.getLanguage(lang)) {
        return highlight.highlight(lang, code).value;
      } else {
        return highlight.highlightAuto(code).value;
      }

    }
  }

  // Argh! marked, why you no stream?
  var mdToHtml = through(
    function write (data) {
      md += data
    },
    function end () {
      var html = marked(md, markedOptions)
      this.queue(html)
      this.queue(null)
    }
  )

  var inputStream = through()
    , outputStream = through()

  // Stop input stream emitting data events until we're ready to read them
  inputStream.pause()

  // Create tmp file to save HTML for phantom to process
  tmp.file({postfix: ".html"}, function (er, tmpHtmlPath, tmpHtmlFd) {
    if (er) return outputStream.emit("error", er)
    fs.close(tmpHtmlFd)

    // Create tmp file to save PDF to
    tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath, tmpPdfFd) {
      if (er) return outputStream.emit("error", er)
      fs.close(tmpPdfFd)

      var htmlToTmpHtmlFile = fs.createWriteStream(tmpHtmlPath)

      htmlToTmpHtmlFile.on("finish", function () {
        // Invoke phantom to generate the PDF
        var childArgs = [
            path.join(__dirname, "..", "lib-phantom", "markdown-pdf.js")
          , tmpHtmlPath
          , tmpPdfPath
          , opts.runningsPath
          , opts.cssPath
          , opts.highlightCssPath
          , opts.paperFormat
          , opts.paperOrientation
          , opts.paperBorder
          , opts.renderDelay
        ]

        childProcess.execFile(opts.phantomPath, childArgs, function(er, stdout, stderr) {
          //if (stdout) console.log(stdout)
          //if (stderr) console.error(stderr)
          if (er) return outputStream.emit("error", er)
          fs.createReadStream(tmpPdfPath).pipe(outputStream)
        })
      })

      // Setup the pipeline
      inputStream.pipe(opts.preProcessMd()).pipe(mdToHtml).pipe(opts.preProcessHtml()).pipe(htmlToTmpHtmlFile)
      inputStream.resume()
    })
  })

  return extend(
    duplexer(inputStream, outputStream),
    streamft(function () {
      return markdownpdf(opts)
    })
  )
}

module.exports = markdownpdf<|endoftext|>


<commit_before>var _   = require('underscore'),
    fs  = require('fs'),
    path = require('path'),
    config  = require('./config');

module.exports = function(paths, contents) {

  function itterate(obj, parentKey, parentObj) {

    _.each(obj, function(val, key) {

      if(key.match(/\$ref/)) {

        var filePath = config.schemas + parentObj[parentKey][key];

        if(path.existsSync(filePath)) {
          // TODO: Should the sub schema have the parent key?
          return parentObj[parentKey] = itterate(JSON.parse(fs.readFileSync(filePath, 'binary'))[parentKey], parentKey, parentObj);

        }

      }

      if (typeof val === 'object') {

        itterate(val, key, obj);

      }

    });

    return obj;

  }

  contents.forEach(function(val, key) {

    contents[key] = itterate(JSON.parse(val));

  });

  return contents;

};<commit_msg>comments<commit_after>var _   = require('underscore'),
    fs  = require('fs'),
    path = require('path'),
    config  = require('./config');

module.exports = function(paths, contents) {

  function itterate(obj, parentKey, parentObj) {

    _.each(obj, function(val, key) {

      if(key.match(/\$ref/)) {

        // The $ref keys value should be a path to the sub schema, get it.
        var filePath = config.schemas + parentObj[parentKey][key];

        if(path.existsSync(filePath)) {

          // Get the subSchema and assume it has an initial key to match the parent
          // object that is calling it.
          // TODO: Should our sub schemas follow this pattern or just be keyless objects?
          var subSchema = JSON.parse(fs.readFileSync(filePath, 'binary'))[parentKey];

          // Return a new itterator into our sub schema and bind that to the parents key
          return parentObj[parentKey] = itterate(subSchema, parentKey, parentObj);

        }

      }

      // If we encounter a ew object
      if (typeof val === 'object') {

        // Itterate down into that
        itterate(val, key, obj);

      }

    });

    return obj;

  }

  contents.forEach(function(val, key) {

    // For each schema we have mapped into our contents we will itterate down into
    // it and look for any $ref keys that will point to our sub schemas
    contents[key] = itterate(JSON.parse(val));

  });

  return contents;

};<|endoftext|>


<commit_before>'use babel';

/* @flow */
const fs = require('fs');
const path = require('path');
const Mocha = require('mocha');
const ErrorStackParser = require('error-stack-parser');

export function run(textEditor) {
  console.log('run function call', textEditor);
  return new Promise((resolve) => {
    console.log('run promise create', textEditor);
    const write = process.stdout.write;
    let output = '';
    process.stdout.write = function (str) {
      output += str;
    };
    // TODO add to settings
    const mocha = new Mocha({
      ui: 'bdd',
      //reporter() {},
    });
    const messages = [];

    const fileModified = textEditor.isModified();
    const fileName = textEditor.getPath();
    let outputFilePath = fileName;
    if (fileModified) {
      const outputDir = `${atom.getConfigDirPath()}/tester-mocha`;
      if (!fs.existsSync(outputDir)) {
        fs.mkdir(outputDir);
      }
      outputFilePath = `${outputDir}/${path.basename(fileName)}`;
      fs.writeFileSync(outputFilePath, textEditor.getText());
      console.log('WRITE TEMP FILE', outputFilePath, textEditor.getText());
    }

    // remove cached file https://github.com/mochajs/mocha/issues/995
    delete require.cache[outputFilePath];
    mocha.addFile(outputFilePath);

    const pushTestResult = function pushTestResult(test) {
      console.log('++++pushTestResult', test);
      console.log('++++pushTestResult _trace', test._trace);
      if (!test || !test._trace) {
        console.log('++++test trace is empty', test);
        return;
      }
      const traceObjects = ErrorStackParser.parse(test._trace)
        .filter(stackTraceObject => stackTraceObject.fileName === outputFilePath);
      console.log('++++traceObjects', traceObjects);
      const traceObject = traceObjects.length > 0 ? traceObjects[0] : traceObjects;
      if (!traceObject) {
        console.log('++++traceObject is empty', test);
        return;
      }

      console.log('++++trace', traceObject);
      if (!test.state) {
        test.state = 'skipped';
      }
      messages.push({
        state: test.state,
        title: test.title,
        error: test.err,
        duration: test.duration,
        lineNumber: traceObject.lineNumber - 1,
        filePath: textEditor.getPath(),
      });
      console.log('++++ADDED TO RESULTS', messages);
    };

    // TODO add to settings
    // const testDir = './test';

    /* fs.readdirSync(testDir)
        .filter(file =>
            // Only keep the .js files
           file.substr(-3) === '.js')
        .forEach(function (file) {
          this.mocha.addFile(
                path.join(testDir, file),
            );
        });*/

    console.log('BEFORE mocha run', mocha);
    mocha.run((failures) => {
      process.stdout.write = write;
      if (fileModified && fs.existsSync(outputFilePath)) {
        fs.unlink(outputFilePath);
      }
      resolve({ messages, output });
      console.log('AFTER mocha run', failures, messages, output);
    })
    .on('start', (start) => {
      console.log('START', start);
    })
    .on('end', (end) => {
      console.log('END', end);
      console.log('self.results', messages);
    })
    .on('suite', (suite) => {
      console.log('SUITE START', suite);
    })
    .on('suite end', (suite) => {
      console.log('SUITE END', suite);
    })
    .on('test', (test) => {
      console.log('TEST START', test);
    })
    .on('test end', (test) => {
      console.log('TEST END', test);
    })
    .on('hook', (hook) => {
      console.log('HOOK START', hook);
    })
    .on('hook end', (hook) => {
      console.log('HOOK END', hook);
    })
    .on('pass', (test) => {
      pushTestResult(test);
      console.log('PASS', test);
    })
    .on('fail', (test, error) => {
      pushTestResult(test);
      console.log('FAIL', test, error);
    })
    .on('pending', (test) => {
      pushTestResult(test);
      console.log('PENDING', test);
    });
  });
}
<commit_msg>reporter output<commit_after>'use babel';

/* @flow */
const fs = require('fs');
const path = require('path');
const Mocha = require('mocha');
const ErrorStackParser = require('error-stack-parser');

export function run(textEditor) {
  console.log('run function call', textEditor);
  return new Promise((resolve) => {
    console.log('run promise create', textEditor);
    const write = process.stdout.write;
    let output = 'Mocha Runner:\n\n';
    process.stdout.write = function (str) {
      output += str;
    };
    // TODO add to settings
    const mocha = new Mocha({
      ui: 'bdd',
      reporter: 'spec',
    });
    const messages = [];

    const fileModified = textEditor.isModified();
    const fileName = textEditor.getPath();
    let outputFilePath = fileName;
    if (fileModified) {
      const outputDir = `${atom.getConfigDirPath()}/tester-mocha`;
      if (!fs.existsSync(outputDir)) {
        fs.mkdir(outputDir);
      }
      outputFilePath = `${outputDir}/${path.basename(fileName)}`;
      fs.writeFileSync(outputFilePath, textEditor.getText());
      console.log('WRITE TEMP FILE', outputFilePath, textEditor.getText());
    }

    // remove cached file https://github.com/mochajs/mocha/issues/995
    delete require.cache[outputFilePath];
    mocha.addFile(outputFilePath);

    const pushTestResult = function pushTestResult(test) {
      console.log('++++pushTestResult', test);
      console.log('++++pushTestResult _trace', test._trace);
      if (!test || !test._trace) {
        console.log('++++test trace is empty', test);
        return;
      }
      const traceObjects = ErrorStackParser.parse(test._trace)
        .filter(stackTraceObject => stackTraceObject.fileName === outputFilePath);
      console.log('++++traceObjects', traceObjects);
      const traceObject = traceObjects.length > 0 ? traceObjects[0] : traceObjects;
      if (!traceObject) {
        console.log('++++traceObject is empty', test);
        return;
      }

      console.log('++++trace', traceObject);
      if (!test.state) {
        test.state = 'skipped';
      }
      messages.push({
        state: test.state,
        title: test.title,
        error: test.err,
        duration: test.duration,
        lineNumber: traceObject.lineNumber - 1,
        filePath: textEditor.getPath(),
      });
      console.log('++++ADDED TO RESULTS', messages);
    };

    // TODO add to settings
    // const testDir = './test';

    /* fs.readdirSync(testDir)
        .filter(file =>
            // Only keep the .js files
           file.substr(-3) === '.js')
        .forEach(function (file) {
          this.mocha.addFile(
                path.join(testDir, file),
            );
        });*/

    console.log('BEFORE mocha run', mocha);
    mocha.run((failures) => {
      process.stdout.write = write;
      if (fileModified && fs.existsSync(outputFilePath)) {
        fs.unlink(outputFilePath);
      }
      resolve({ messages, output });
      console.log('AFTER mocha run', failures, messages, output);
    })
    .on('start', (start) => {
      console.log('START', start);
    })
    .on('end', (end) => {
      console.log('END', end);
      console.log('self.results', messages);
    })
    .on('suite', (suite) => {
      console.log('SUITE START', suite);
    })
    .on('suite end', (suite) => {
      console.log('SUITE END', suite);
    })
    .on('test', (test) => {
      console.log('TEST START', test);
    })
    .on('test end', (test) => {
      console.log('TEST END', test);
    })
    .on('hook', (hook) => {
      console.log('HOOK START', hook);
    })
    .on('hook end', (hook) => {
      console.log('HOOK END', hook);
    })
    .on('pass', (test) => {
      pushTestResult(test);
      console.log('PASS', test);
    })
    .on('fail', (test, error) => {
      pushTestResult(test);
      console.log('FAIL', test, error);
    })
    .on('pending', (test) => {
      pushTestResult(test);
      console.log('PENDING', test);
    });
  });
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

var Copayer = require('./copayer');
var Bitcore = require('bitcore');
var PublicKey = Bitcore.PublicKey;
var WALLET_VERSION = '1.0.0';

function Wallet(opts) {
	opts = opts || {};

	this.createdOn = Math.floor(Date.now() / 1000);
	this.id = opts.id;
	this.name = opts.name;
	this.m = opts.m;
	this.n = opts.n;
	this.status = 'pending';
	this.publicKeyRing = [];
	this.addressIndex = 0;
	this.copayers = [];
  this.version = WALLET_VERSION;

  if (opts.pubKey)
    this.pubKey = new PublicKey(opts.pubKey);
};

Wallet.fromUntrustedObj = function (obj) {

  // TODO add sanity checks OR migration steps?
  if (!obj.pubKey || !obj.m || !obj.n)
    return cb('Wallet corrupted');

  return Wallet.fromObj(obj);
};

Wallet.fromObj = function (obj) {
	var x = new Wallet();

	x.createdOn = obj.createdOn;
	x.id = obj.id;
	x.name = obj.name;
	x.m = obj.m;
	x.n = obj.n;
	x.status = obj.status;
	x.publicKeyRing = obj.publicKeyRing;
	x.addressIndex = obj.addressIndex;
	x.copayers = _.map(obj.copayers, function (copayer) {
		return new Copayer(copayer);
	});
  x.pubKey = new PublicKey(obj.pubKey);

	return x;
};

Wallet.prototype.addCopayer = function (copayer) {
	this.copayers.push(copayer);

	if (this.copayers.length < this.n) return;

	this.status = 'complete';
	this.publicKeyRing = _.pluck(this.copayers, 'xPubKey');
};

Wallet.prototype.getCopayer = function (copayerId) {
	return _.find(this.copayers, { id: copayerId });
};

module.exports = Wallet;
<commit_msg>simplify wallet object<commit_after>'use strict';

var _ = require('lodash');

var Copayer = require('./copayer');
var WALLET_VERSION = '1.0.0';

function Wallet(opts) {
	opts = opts || {};

	this.createdOn = Math.floor(Date.now() / 1000);
	this.id = opts.id;
	this.name = opts.name;
	this.m = opts.m;
	this.n = opts.n;
	this.status = 'pending';
	this.publicKeyRing = [];
	this.addressIndex = 0;
	this.copayers = [];
  this.version = WALLET_VERSION;
  this.pubKey = opts.pubKey;
};

Wallet.fromUntrustedObj = function (obj) {

  // TODO add sanity checks OR migration steps?
  if (!obj.pubKey || !obj.m || !obj.n)
    return cb('Wallet corrupted');

  return Wallet.fromObj(obj);
};

Wallet.fromObj = function (obj) {
	var x = new Wallet();

	x.createdOn = obj.createdOn;
	x.id = obj.id;
	x.name = obj.name;
	x.m = obj.m;
	x.n = obj.n;
	x.status = obj.status;
	x.publicKeyRing = obj.publicKeyRing;
	x.addressIndex = obj.addressIndex;
	x.copayers = _.map(obj.copayers, function (copayer) {
		return new Copayer(copayer);
	});
  x.pubKey = obj.pubKey;

	return x;
};

Wallet.prototype.addCopayer = function (copayer) {
	this.copayers.push(copayer);

	if (this.copayers.length < this.n) return;

	this.status = 'complete';
	this.publicKeyRing = _.pluck(this.copayers, 'xPubKey');
};

Wallet.prototype.getCopayer = function (copayerId) {
	return _.find(this.copayers, { id: copayerId });
};

module.exports = Wallet;
<|endoftext|>


<commit_before>var models = require('../utils').index(__dirname, __filename);

// Create a new instance of each model and returns an object of name/Model
// pairs where name is the constructor name lowercased without the Model
// suffix.
//
// Example:
//
//   var models = createModels(store); //=> {user: {}, bin: {}}
module.exports.createModels = function (store) {
  var initialized = {}, Model, name;
  for (name in models) {
    if (models.hasOwnProperty(name)) {
      Model = models[name];
      initialized[name.slice(0, -5).toLowerCase()] = new Model(store);
    }
  }
  return initialized;
};
<commit_msg>Now load models with camel case names correctly<commit_after>var models = require('../utils').index(__dirname, __filename);

// Create a new instance of each model and returns an object of name/Model
// pairs where name is the constructor name lowercased without the Model
// suffix.
//
// Example:
//
//   var models = createModels(store); //=> {user: {}, bin: {}}
module.exports.createModels = function (store) {
  var initialized = {}, Model, name;
  for (name in models) {
    if (models.hasOwnProperty(name)) {
      Model = models[name];

      // Convert ForgotTokenModel -> forgotToken
      name = name.slice(0, -5);
      name = name[0].toLowerCase() + name.slice(1);

      initialized[name] = new Model(store);
    }
  }
  return initialized;
};
<|endoftext|>


<commit_before>/**
 * loader配置 - html模板入口
 */
'use strict';

const path = require('path');
const glob = require('glob');
const extend = require('extend');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const paths = require('../config/paths');
const TypeOf = require('../utils/typeof');
const HtmlWebpackAssetsPlugin = require('../fixtures/htmlWebpackAssetsPlugin');

const REG_VIEW_HANDLEBARS_NAME_RULE = /(\.view)$/;

const DEFAULT_CONFIG = {
    pattern: '**/*.view.{handlebars,hbs}'
};

module.exports = function (config) {
    if (config.html === false) {
        return config;
    }

    let htmlConfig = TypeOf.isObject(config.html) ?
        extend(true, {}, DEFAULT_CONFIG, config.html) :
        extend(true, {}, DEFAULT_CONFIG);

    let htmlDirCwd = path.join(config.context, 'src');
    let htmlFiles = glob.sync(htmlConfig.pattern, {
        cwd: paths.appSrc,
        nodir: true,
        matchBase: true
    });

    if (!htmlFiles.length) {
        return config;
    }

    htmlFiles.forEach(function (file) {
        let info = path.parse(file);
        let filename = path.join(
            config.output.path,
            config.output.templateDir,
            (info.name.replace(REG_VIEW_HANDLEBARS_NAME_RULE, '')) + '.html'
        );

        let HtmlWebpackPluginConfig = {
            filename: filename,
            template: path.join(htmlDirCwd, file),
            inject: false,
            hash: false
        };

        if (TypeOf.isFunction(htmlConfig.beforeInitialization)) {
            htmlConfig.beforeInitialization(HtmlWebpackPluginConfig);
        }

        let obj = new HtmlWebpackPlugin(HtmlWebpackPluginConfig);

        if (TypeOf.isFunction(htmlConfig.afterInitialization)) {
            obj = htmlConfig.afterInitialization(obj);
        }

        config.plugins.push(obj);
    });

    config.plugins.push(new HtmlWebpackAssetsPlugin({
        // data: renderData,
        assetsDir: {
            output: config.output.path,
            template: config.output.templateDir,
            image: config.output.imageDir,
            font: config.output.fontDir,
            css: config.output.cssDir,
            js: config.output.jsDir
        }
    }));

    return config;
};
<commit_msg>默认开启html-webpack-plugin cache<commit_after>/**
 * loader配置 - html模板入口
 */
'use strict';

const path = require('path');
const glob = require('glob');
const extend = require('extend');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const paths = require('../config/paths');
const TypeOf = require('../utils/typeof');
const HtmlWebpackAssetsPlugin = require('../fixtures/htmlWebpackAssetsPlugin');

const REG_VIEW_HANDLEBARS_NAME_RULE = /(\.view)$/;

const DEFAULT_CONFIG = {
    pattern: '**/*.view.{handlebars,hbs}'
};

module.exports = function (config) {
    if (config.html === false) {
        return config;
    }

    let htmlConfig = TypeOf.isObject(config.html) ?
        extend(true, {}, DEFAULT_CONFIG, config.html) :
        extend(true, {}, DEFAULT_CONFIG);

    let htmlDirCwd = path.join(config.context, 'src');
    let htmlFiles = glob.sync(htmlConfig.pattern, {
        cwd: paths.appSrc,
        nodir: true,
        matchBase: true
    });

    if (!htmlFiles.length) {
        return config;
    }

    htmlFiles.forEach(function (file) {
        let info = path.parse(file);
        let filename = path.join(
            config.output.path,
            config.output.templateDir,
            (info.name.replace(REG_VIEW_HANDLEBARS_NAME_RULE, '')) + '.html'
        );

        let HtmlWebpackPluginConfig = {
            filename: filename,
            template: path.join(htmlDirCwd, file),
            cache: true,
            inject: false,
            hash: false
        };

        if (TypeOf.isFunction(htmlConfig.beforeInitialization)) {
            htmlConfig.beforeInitialization(HtmlWebpackPluginConfig);
        }

        let obj = new HtmlWebpackPlugin(HtmlWebpackPluginConfig);

        if (TypeOf.isFunction(htmlConfig.afterInitialization)) {
            obj = htmlConfig.afterInitialization(obj);
        }

        config.plugins.push(obj);
    });

    config.plugins.push(new HtmlWebpackAssetsPlugin({
        assetsDir: {
            output: config.output.path,
            template: config.output.templateDir,
            image: config.output.imageDir,
            font: config.output.fontDir,
            css: config.output.cssDir,
            js: config.output.jsDir
        }
    }));

    return config;
};
<|endoftext|>