<commit_before>'use strict';
var mongoose = require('mongoose');
var ShortId = require('mongoose-shortid');
var timestamps = require('mongoose-timestamp');
var BBPromise = require('bluebird');
var mongooseDelete = require('mongoose-delete');
var keygen = require('keygenerator');

var Schema = mongoose.Schema;
var ApplicationSchema = new Schema({
  schemaVersion: String,
  //the org that owns this application
  organisation: {
    type: ShortId,
    required: 'Application must belong to an Organisation',
    index: true,
    ref: 'Organisation'
  },
  //friendly name
  name: {
    type: String
  },
  _id: {
    type: ShortId,
    base: 64,
    retries: 4,
    len: 20
  },
  //url alias
  alias: {
    type: [String],
    index: true
  },
  loggly: {
    _id: false,
    token: String,
    subdomain: String
  },
  //the app.hoi.io sub domain for hosting
  subDomain: {
    type: String,
    unique: true,
    index: true,
    required: true,
    default: function () {
      return require('moniker').choose();
    }
  },

  //api key
  apiKey: {
    type: String,
    unique: true,
    index: true,
    required: true,
    default: function () {
      return keygen._();
    }
  },
  //the storage for data
  dataKey: {
    type: String,
    unique: true,
    required: true,
    default: function () {
      return keygen._({
        forceLowercase: true
      });
    }
  },
  //anonymous

  anonymousPermissions: {
    dev: [{
      type: String
    }],
    test: [{
      type: String
    }],
    live: [{
      type: String
    }]
  },
  //settings from the hoist.json files
  settings: {
    dev: {
      type: Schema.Types.Mixed
    },
    test: {
      type: Schema.Types.Mixed
    },
    live: {
      type: Schema.Types.Mixed
    },
  },
  //when was the code last released
  lastDeploy: {
    dev: {
      type: Date
    },
    test: {
      type: Date
    },
    live: {
      type: Date
    }
  },
  //should this application get preview features
  isCanary: {
    type: Boolean,
    default: false
  },
  //path to the git repository
  slug: {
    type: String,
    index: true
  }

});

ApplicationSchema.plugin(timestamps);
ApplicationSchema.plugin(mongooseDelete);
ApplicationSchema.set('toJSON', { virtuals: true });
ApplicationSchema.virtual('gitRepo').get(function () {
  return this.slug;
}).set(function (value) {
  this.slug = value;
});

mongoose.model('Application', ApplicationSchema);

var Application = mongoose.model('Application');
BBPromise.promisifyAll(Application);
BBPromise.promisifyAll(Application.prototype);
exports.name = 'Application';
exports.model = Application;
<commit_msg>last commit<commit_after>'use strict';
var mongoose = require('mongoose');
var ShortId = require('mongoose-shortid');
var timestamps = require('mongoose-timestamp');
var BBPromise = require('bluebird');
var mongooseDelete = require('mongoose-delete');
var keygen = require('keygenerator');

var Schema = mongoose.Schema;
var ApplicationSchema = new Schema({
  schemaVersion: String,
  //the org that owns this application
  organisation: {
    type: ShortId,
    required: 'Application must belong to an Organisation',
    index: true,
    ref: 'Organisation'
  },
  //friendly name
  name: {
    type: String
  },
  _id: {
    type: ShortId,
    base: 64,
    retries: 4,
    len: 20
  },
  //url alias
  alias: {
    type: [String],
    index: true
  },
  loggly: {
    _id: false,
    token: String,
    subdomain: String
  },
  //the app.hoi.io sub domain for hosting
  subDomain: {
    type: String,
    unique: true,
    index: true,
    required: true,
    default: function () {
      return require('moniker').choose();
    }
  },

  //api key
  apiKey: {
    type: String,
    unique: true,
    index: true,
    required: true,
    default: function () {
      return keygen._();
    }
  },
  //the storage for data
  dataKey: {
    type: String,
    unique: true,
    required: true,
    default: function () {
      return keygen._({
        forceLowercase: true
      });
    }
  },
  //anonymous

  anonymousPermissions: {
    dev: [{
      type: String
    }],
    test: [{
      type: String
    }],
    live: [{
      type: String
    }]
  },
  //settings from the hoist.json files
  settings: {
    dev: {
      type: Schema.Types.Mixed
    },
    test: {
      type: Schema.Types.Mixed
    },
    live: {
      type: Schema.Types.Mixed
    },
  },
  //when was the code last released
  lastDeploy: {
    dev: {
      type: Date
    },
    test: {
      type: Date
    },
    live: {
      type: Date
    }
  },
  //information about the commit
  lastCommit: {
    live: {
      message: String,
      sha1: String,
      user: {
        type: String,
        ref: 'HoistUser'
      }
    }
  },
  //should this application get preview features
  isCanary: {
    type: Boolean,
    default: false
  },
  //path to the git repository
  slug: {
    type: String,
    index: true
  }

});

ApplicationSchema.plugin(timestamps);
ApplicationSchema.plugin(mongooseDelete);
ApplicationSchema.set('toJSON', { virtuals: true });
ApplicationSchema.virtual('gitRepo').get(function () {
  return this.slug;
}).set(function (value) {
  this.slug = value;
});

mongoose.model('Application', ApplicationSchema);

var Application = mongoose.model('Application');
BBPromise.promisifyAll(Application);
BBPromise.promisifyAll(Application.prototype);
exports.name = 'Application';
exports.model = Application;
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var util = require('util'),
    nodemailer = require('nodemailer'),
    logger = require('logops'),
    smtpTransport = require('nodemailer-smtp-transport'),
    config = require('../../config'),
    myutils = require('../myutils'),
    alarm = require('../alarm'),
    metrics = require('./metrics');

function buildTransporterOptions(action, event) {
    var options = {};
    if (action.parameters.smtp) {
        options.smtp = {};
        options.smtp = action.parameters.smtp;
        if (action.parameters.smtp.host) {
            options.smtp.host = myutils.expandVar(action.parameters.smtp.host, event);
        }
        if (action.parameters.smtp.port) {
            options.smtp.port = myutils.expandVar(action.parameters.smtp.port, event);
        }
    }
    return options;
}

function buildMailOptions(action, event) {
    return {
        from: myutils.expandVar(action.parameters.from, event),
        to: myutils.expandVar(action.parameters.to, event),
        subject: myutils.expandVar(action.parameters.subject || '', event),
        text: myutils.expandVar(action.template, event)
    };
}

function SendMail(action, event, callback) {
    try {
        // setup e-mail data with unicode symbols
        var mailOptions = buildMailOptions(action, event),
            transporterOptions = buildTransporterOptions(action, event),
            opt2log,
            transporter;

        if (transporterOptions.smtp) {
            logger.debug('Using smtp transporter config from action: %j', transporterOptions.smtp);
            transporter = nodemailer.createTransport(smtpTransport(transporterOptions.smtp));
        } else {
            logger.debug('Using smtp transporter config: %j', config.smtp);
            transporter = nodemailer.createTransport(smtpTransport(config.smtp));
        }
        metrics.IncMetrics(event.service, event.subservice, metrics.actionEmail);

        transporter.sendMail(mailOptions, function(err, info) {
            logger.debug('emailAction.SendMail %j %j %j', mailOptions, err, info);
            // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
            metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactions);

            if (err) {
                metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEmail);
                // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
                metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactionsErrors);

                opt2log = { to: mailOptions.to, from: mailOptions.from, subject: mailOptions.subject };
                myutils.logErrorIf(err, util.format('emailAction.SendMail %j', opt2log));
                alarm.raise(alarm.EMAIL);
            } else {
                metrics.IncMetrics(event.service, event.subservice, metrics.okActionEmail);

                logger.info('done emailAction.SendMail');
                alarm.release(alarm.EMAIL);
            }
            return callback(err, info);
        });
    } catch (ex) {
        metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEmail);
        // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
        metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactionsErrors);
        return callback(ex);
    }
}

module.exports.doIt = SendMail;
module.exports.buildMailOptions = buildMailOptions;
<commit_msg>log smtp config used<commit_after>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var util = require('util'),
    nodemailer = require('nodemailer'),
    logger = require('logops'),
    smtpTransport = require('nodemailer-smtp-transport'),
    config = require('../../config'),
    myutils = require('../myutils'),
    alarm = require('../alarm'),
    metrics = require('./metrics');

function buildTransporterOptions(action, event) {
    var options = {};
    if (action.parameters.smtp) {
        options.smtp = {};
        options.smtp = action.parameters.smtp;
        if (action.parameters.smtp.host) {
            options.smtp.host = myutils.expandVar(action.parameters.smtp.host, event);
        }
        if (action.parameters.smtp.port) {
            options.smtp.port = myutils.expandVar(action.parameters.smtp.port, event);
        }
    }
    return options;
}

function buildMailOptions(action, event) {
    return {
        from: myutils.expandVar(action.parameters.from, event),
        to: myutils.expandVar(action.parameters.to, event),
        subject: myutils.expandVar(action.parameters.subject || '', event),
        text: myutils.expandVar(action.template, event)
    };
}

function SendMail(action, event, callback) {
    try {
        // setup e-mail data with unicode symbols
        var mailOptions = buildMailOptions(action, event),
            transporterOptions = buildTransporterOptions(action, event),
            opt2log,
            smtpConfig,
            transporter;

        if (transporterOptions.smtp) {
            logger.debug('Using smtp transporter config from action: %j', transporterOptions.smtp);
            smtpConfig = transporterOptions.smtp;
        } else {
            logger.debug('Using smtp transporter config: %j', config.smtp);
            smtpConfig = config.smtp;
        }
        transporter = nodemailer.createTransport(smtpTransport(smtpConfig));
        metrics.IncMetrics(event.service, event.subservice, metrics.actionEmail);

        transporter.sendMail(mailOptions, function(err, info) {
            logger.debug('emailAction.SendMail mailOptions: %j error: %j info: %j', mailOptions, err, info);
            // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
            metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactions);

            if (err) {
                metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEmail);
                // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
                metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactionsErrors);

                opt2log = {
                    to: mailOptions.to,
                    from: mailOptions.from,
                    subject: mailOptions.subject,
                    smtp: smtpConfig
                };
                myutils.logErrorIf(err, util.format('emailAction.SendMail %j', opt2log));
                alarm.raise(alarm.EMAIL);
            } else {
                metrics.IncMetrics(event.service, event.subservice, metrics.okActionEmail);

                logger.info('done emailAction.SendMail to %s', mailOptions.to);
                alarm.release(alarm.EMAIL);
            }
            return callback(err, info);
        });
    } catch (ex) {
        metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEmail);
        // Not an HTTP request, so outgoingTransacion hasn't already counted and must be counted now
        metrics.IncMetrics(event.service, event.subservice, metrics.outgoingTransactionsErrors);
        return callback(ex);
    }
}

module.exports.doIt = SendMail;
module.exports.buildMailOptions = buildMailOptions;
<|endoftext|>


<commit_before>/**
 * node-archiver
 *
 * Copyright (c) 2012-2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var Transform = require('stream').Transform || require('readable-stream').Transform;
var PassThrough = require('stream').PassThrough || require('readable-stream').PassThrough;

var util = require('../../util');
var Queue = require('./queue');

var Archiver = module.exports = function(options) {
  options = this.options = util.defaults(options, {
    highWaterMark: 512 * 1024
  });

  Transform.call(this, options);

  this.catchEarlyExitAttached = false;
  this.moduleOutputPiped = false;

  this.archiver = {
    pointer: 0,
    files: [],
    module: false
  };

  this.queue = new Queue();
  this.queue.on('entry', this._onQueueEntry.bind(this));
  this.queue.on('end', this._onQueueEnd.bind(this));
};

inherits(Archiver, Transform);

Archiver.prototype._catchEarlyExit = function() {
  var earlyExitCheck = function() {
    if (this._readableState.endEmitted === false) {
      throw new Error('process exited before Archiver could finish emitting data');
    }
  }.bind(this);

  process.once('exit', earlyExitCheck);

  this.once('end', function() {
    process.removeListener('exit', earlyExitCheck);
  });

  this.catchEarlyExitAttached = true;
};

Archiver.prototype._emitErrorCallback = function(err, data) {
  if (err) {
    this.emit('error', err);
  }
};

Archiver.prototype._normalizeFileData = function(data) {
  data = util.defaults(data, {
    name: null,
    date: null
  });

  if (data.name) {
    data.name = util.sanitizePath(data.name);
  }

  data.date = util.dateify(data.date);

  return data;
};

Archiver.prototype._normalizeSource = function(source) {
  if (typeof source === 'string') {
    return new Buffer(source);
  } else if (util.isStream(source) && !source._readableState) {
    var normalized = new PassThrough();
    source.pipe(normalized);

    return normalized;
  }

  return source;
};

Archiver.prototype._onQueueEnd = function() {
  if (typeof this.archiver.module.finalize === 'function') {
    this.archiver.module.finalize();
  } else if (typeof this.archiver.module.end === 'function') {
    this.archiver.module.end();
  } else {
    this.emit('error', new Error('format module missing finalize and end method'));
  }
};

Archiver.prototype._onQueueEntry = function(entry, queueCallback) {
  var nextCallback = function(err, file) {
    entry.callback(err);

    if (!err) {
      this.archiver.files.push(file);
      queueCallback();
    }
  }.bind(this);

  this.archiver.module.append(entry.source, entry.data, nextCallback);
};

Archiver.prototype._pipeModuleOutput = function() {
  this.archiver.module.pipe(this);

  this.moduleOutputPiped = true;
};

Archiver.prototype._processFile = function(source, data, callback) {
  callback(new Error('method not implemented'));
};

Archiver.prototype._transform = function(chunk, encoding, callback) {
  if (chunk) {
    this.archiver.pointer += chunk.length;
  }

  callback(null, chunk);
};

Archiver.prototype.append = function(source, data, callback) {
  data = this._normalizeFileData(data);

  if (!this.catchEarlyExitAttached) {
    this._catchEarlyExit();
  }

  if (typeof callback !== 'function') {
    callback = this._emitErrorCallback.bind(this);
  }

  if (!this.moduleOutputPiped) {
    if (!this.archiver.module) {
      callback(new Error('format module not registered'));
      return this;
    }

    this._pipeModuleOutput();
  }

  if (typeof data.name !== 'string' || data.name.length === 0) {
    callback(new Error('filename must be a non-empty string value'));
    return this;
  }

  source = this._normalizeSource(source);

  if (Buffer.isBuffer(source)) {
    data.sourceType = 'buffer';
  } else if (util.isStream(source)) {
    data.sourceType = 'stream';
  } else {
    callback(new Error('input source must be valid Stream or Buffer instance'));
    return this;
  }

  this.queue.add({
    data: data,
    source: source,
    callback: callback
  });

  return this;
};

Archiver.prototype.bulk = function(mappings) {
  if (!Array.isArray(mappings)) {
    throw new Error('bulk expects an array of src-dest pairings');
  }

  var self = this;
  var files = util.normalizeFilesArray(mappings);

  files.forEach(function(file){
    var isExpandedPair = file.orig.expand || false;
    var data = file.data || {};
    var src = file.src.filter(function(f) {
      return util.file.isFile(f);
    });

    src.forEach(function(filepath) {
      data.name = isExpandedPair ? file.dest : util.unixifyPath(file.dest || '', filepath);

      self.append(util.lazyReadStream(filepath), data);
    });
  });

  return this;
};

Archiver.prototype.file = function(filepath, data, callback) {
  data = this._normalizeFileData(data);
  filepath = String(filepath);

  if (typeof callback !== 'function') {
    callback = this._emitErrorCallback.bind(this);
  }

  if (typeof filepath !== 'string' || filepath.length === 0) {
    callback(new Error('filepath must be a non-empty string value'));
    return this;
  }

  if (util.file.isFile(filepath)) {
    if (typeof data.name !== 'string' || data.name.length === 0) {
      data.name = filepath;
    }

    this.append(util.lazyReadStream(filepath), data, callback);
  } else {
    callback(new Error('invalid file: ' + filepath));
  }

  return this;
};

Archiver.prototype.finalize = function(callback) {
  if (typeof callback === 'function') {
    this.once('end', function() {
      callback(null, this.archiver.pointer);
    }.bind(this));
  }

  this.queue.close();

  return this;
};

Archiver.prototype.setModule = function(module) {
  this.archiver.module = module;
};<commit_msg>pipe module output when module is defined. closes #57.<commit_after>/**
 * node-archiver
 *
 * Copyright (c) 2012-2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var Transform = require('stream').Transform || require('readable-stream').Transform;
var PassThrough = require('stream').PassThrough || require('readable-stream').PassThrough;

var util = require('../../util');
var Queue = require('./queue');

var Archiver = module.exports = function(options) {
  options = this.options = util.defaults(options, {
    highWaterMark: 512 * 1024
  });

  Transform.call(this, options);

  this.catchEarlyExitAttached = false;
  this.moduleOutputPiped = false;

  this.archiver = {
    pointer: 0,
    files: [],
    module: false
  };

  this.queue = new Queue();
  this.queue.on('entry', this._onQueueEntry.bind(this));
  this.queue.on('end', this._onQueueEnd.bind(this));
};

inherits(Archiver, Transform);

Archiver.prototype._catchEarlyExit = function() {
  var earlyExitCheck = function() {
    if (this._readableState.endEmitted === false) {
      throw new Error('process exited before Archiver could finish emitting data');
    }
  }.bind(this);

  process.once('exit', earlyExitCheck);

  this.once('end', function() {
    process.removeListener('exit', earlyExitCheck);
  });

  this.catchEarlyExitAttached = true;
};

Archiver.prototype._emitErrorCallback = function(err, data) {
  if (err) {
    this.emit('error', err);
  }
};

Archiver.prototype._normalizeFileData = function(data) {
  data = util.defaults(data, {
    name: null,
    date: null
  });

  if (data.name) {
    data.name = util.sanitizePath(data.name);
  }

  data.date = util.dateify(data.date);

  return data;
};

Archiver.prototype._normalizeSource = function(source) {
  if (typeof source === 'string') {
    return new Buffer(source);
  } else if (util.isStream(source) && !source._readableState) {
    var normalized = new PassThrough();
    source.pipe(normalized);

    return normalized;
  }

  return source;
};

Archiver.prototype._onQueueEnd = function() {
  if (typeof this.archiver.module.finalize === 'function') {
    this.archiver.module.finalize();
  } else if (typeof this.archiver.module.end === 'function') {
    this.archiver.module.end();
  } else {
    this.emit('error', new Error('format module missing finalize and end method'));
  }
};

Archiver.prototype._onQueueEntry = function(entry, queueCallback) {
  var nextCallback = function(err, file) {
    entry.callback(err);

    if (!err) {
      this.archiver.files.push(file);
      queueCallback();
    }
  }.bind(this);

  this.archiver.module.append(entry.source, entry.data, nextCallback);
};

Archiver.prototype._pipeModuleOutput = function() {
  this.archiver.module.pipe(this);

  this.moduleOutputPiped = true;
};

Archiver.prototype._processFile = function(source, data, callback) {
  callback(new Error('method not implemented'));
};

Archiver.prototype._transform = function(chunk, encoding, callback) {
  if (chunk) {
    this.archiver.pointer += chunk.length;
  }

  callback(null, chunk);
};

Archiver.prototype.append = function(source, data, callback) {
  data = this._normalizeFileData(data);

  if (!this.catchEarlyExitAttached) {
    this._catchEarlyExit();
  }

  if (typeof callback !== 'function') {
    callback = this._emitErrorCallback.bind(this);
  }

  if (typeof data.name !== 'string' || data.name.length === 0) {
    callback(new Error('filename must be a non-empty string value'));
    return this;
  }

  source = this._normalizeSource(source);

  if (Buffer.isBuffer(source)) {
    data.sourceType = 'buffer';
  } else if (util.isStream(source)) {
    data.sourceType = 'stream';
  } else {
    callback(new Error('input source must be valid Stream or Buffer instance'));
    return this;
  }

  this.queue.add({
    data: data,
    source: source,
    callback: callback
  });

  return this;
};

Archiver.prototype.bulk = function(mappings) {
  if (!Array.isArray(mappings)) {
    throw new Error('bulk expects an array of src-dest pairings');
  }

  var self = this;
  var files = util.normalizeFilesArray(mappings);

  files.forEach(function(file){
    var isExpandedPair = file.orig.expand || false;
    var data = file.data || {};
    var src = file.src.filter(function(f) {
      return util.file.isFile(f);
    });

    src.forEach(function(filepath) {
      data.name = isExpandedPair ? file.dest : util.unixifyPath(file.dest || '', filepath);

      self.append(util.lazyReadStream(filepath), data);
    });
  });

  return this;
};

Archiver.prototype.file = function(filepath, data, callback) {
  data = this._normalizeFileData(data);
  filepath = String(filepath);

  if (typeof callback !== 'function') {
    callback = this._emitErrorCallback.bind(this);
  }

  if (typeof filepath !== 'string' || filepath.length === 0) {
    callback(new Error('filepath must be a non-empty string value'));
    return this;
  }

  if (util.file.isFile(filepath)) {
    if (typeof data.name !== 'string' || data.name.length === 0) {
      data.name = filepath;
    }

    this.append(util.lazyReadStream(filepath), data, callback);
  } else {
    callback(new Error('invalid file: ' + filepath));
  }

  return this;
};

Archiver.prototype.finalize = function(callback) {
  if (typeof callback === 'function') {
    this.once('end', function() {
      callback(null, this.archiver.pointer);
    }.bind(this));
  }

  this.queue.close();

  return this;
};

Archiver.prototype.setModule = function(module) {
  if (this.moduleOutputPiped) {
    self.emit('error', new Error('format module already set'));
    return;
  }

  this.archiver.module = module;
  this._pipeModuleOutput();
};<|endoftext|>


<commit_before>/**
 * node-archiver
 *
 * Copyright (c) 2012-2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var Transform = require('readable-stream').Transform;

var crc32 = require('buffer-crc32');
var util = require('../../util');

var Json = module.exports = function(options) {
  options = this.options = util.defaults(options, {});

  Transform.call(this, options);

  this.supports = {
    directory: true
  };

  this.files = [];
};

inherits(Json, Transform);

Json.prototype._transform = function(chunk, encoding, callback) {
  callback(null, chunk);
};

Json.prototype._writeStringified = function() {
  var fileString = JSON.stringify(this.files);
  this.write(fileString);
};

Json.prototype.append = function(source, data, callback) {
  var self = this;

  data.crc32 = 0;

  function onend(err, sourceBuffer) {
    if (err) {
      callback(err);
      return;
    }

    data.size = sourceBuffer.length || 0;
    data.crc32 = crc32.unsigned(sourceBuffer);

    self.files.push(data);

    callback(null, data);
  }

  if (data.sourceType === 'buffer') {
    onend(null, source);
  } else if (data.sourceType === 'stream') {
    util.collectStream(source, onend);
  }
};

Json.prototype.finalize = function(callback) {
  callback = callback || function() {};

  this._writeStringified();

  this.end();

  callback();
};<commit_msg>json: remove callback from finalize. old code.<commit_after>/**
 * node-archiver
 *
 * Copyright (c) 2012-2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var Transform = require('readable-stream').Transform;

var crc32 = require('buffer-crc32');
var util = require('../../util');

var Json = module.exports = function(options) {
  options = this.options = util.defaults(options, {});

  Transform.call(this, options);

  this.supports = {
    directory: true
  };

  this.files = [];
};

inherits(Json, Transform);

Json.prototype._transform = function(chunk, encoding, callback) {
  callback(null, chunk);
};

Json.prototype._writeStringified = function() {
  var fileString = JSON.stringify(this.files);
  this.write(fileString);
};

Json.prototype.append = function(source, data, callback) {
  var self = this;

  data.crc32 = 0;

  function onend(err, sourceBuffer) {
    if (err) {
      callback(err);
      return;
    }

    data.size = sourceBuffer.length || 0;
    data.crc32 = crc32.unsigned(sourceBuffer);

    self.files.push(data);

    callback(null, data);
  }

  if (data.sourceType === 'buffer') {
    onend(null, source);
  } else if (data.sourceType === 'stream') {
    util.collectStream(source, onend);
  }
};

Json.prototype.finalize = function() {
  this._writeStringified();
  this.end();
};<|endoftext|>


<commit_before>"use strict";

var Parser = require('./Parser'),
    Methods = require('./Methods'),
    UrlNormalizer = require('./UrlNormalizer'),
    inherits = require('inherits'),
    HttpClient = require('./HttpClient'),
    Promise = require('bluebird'),
    _ = require('lodash');

var BaseHttpClient = function (http) {
    this._http = http;
};

inherits(BaseHttpClient, HttpClient);

BaseHttpClient.prototype.unwrapResponse = function () {
    return false;
};

BaseHttpClient.prototype.credentialsRequestsEnabled = function () {
    return false;
};

BaseHttpClient.prototype.get = function (url, parser, headers) {
    return this._handleRequest(url, Methods.GET, null, parser, headers);
};

BaseHttpClient.prototype.post = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.POST, data, parser, headers);
};

BaseHttpClient.prototype.put = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.PUT, data, parser, headers);
};

BaseHttpClient.prototype.delete = function (url, parser, headers) {
    return this._handleRequest(url, Methods.DELETE, null, parser, headers);
};

BaseHttpClient.prototype.jsonp = function (url, parser, headers) {
    url = UrlNormalizer.normalizeJsonp(url);
    return this._handleRequest(url, Methods.JSONP, null, parser, headers);
};

BaseHttpClient.prototype.multipart = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.MULTIPART, data, parser, headers);
};

BaseHttpClient.prototype._handleRequest = function (url, method, data, parser, headers, plainResponse) {
    return new Promise(_.bind(function (resolve, reject) {
        parser = parser || new Parser();
        var unwrapResponse = this.unwrapResponse();
        this._getNetworkPromise(url, method, data, headers, plainResponse)
            .success(function (response, status, headers, config) {
                if (!unwrapResponse)
                    resolve(parser.parse(response));
                else
                    resolve([parser.parse(response), status, headers, config]);
            })
            .error(function (error, status, headers, config) {
                if (!unwrapResponse)
                    reject(error);
                else
                    reject({data: error, status: status, headers: headers, config: config});
            });
    }, this));
};

BaseHttpClient.prototype._getNetworkPromise = function (url, method, data, headers, plainResponse) {
    var config = {
        headers: headers,
        withCredentials: this.credentialsRequestsEnabled()
    };
    if (plainResponse)
        config.transformResponse = undefined;
    if (method === Methods.MULTIPART) {
        config.transformRequest = angular.identity;
        config.headers = config.headers || {};
        config.headers['Content-Type'] = undefined;
    }
    switch (method) {
        case Methods.GET:
            return this._http.get(url, config);
        case Methods.POST:
        case Methods.MULTIPART:
            return this._http.post(url, data, config);
        case Methods.PUT:
            return this._http.put(url, data, config);
        case Methods.DELETE:
            return this._http.delete(url, config);
        case Methods.JSONP:
            return this._http.jsonp(url, config);
    }
};

module.exports = BaseHttpClient;
<commit_msg>Make promise compatible with Angular 1.6<commit_after>"use strict";

var Parser = require('./Parser'),
    Methods = require('./Methods'),
    UrlNormalizer = require('./UrlNormalizer'),
    inherits = require('inherits'),
    HttpClient = require('./HttpClient'),
    Promise = require('bluebird'),
    _ = require('lodash');

var BaseHttpClient = function (http) {
    this._http = http;
};

inherits(BaseHttpClient, HttpClient);

BaseHttpClient.prototype.unwrapResponse = function () {
    return false;
};

BaseHttpClient.prototype.credentialsRequestsEnabled = function () {
    return false;
};

BaseHttpClient.prototype.get = function (url, parser, headers) {
    return this._handleRequest(url, Methods.GET, null, parser, headers);
};

BaseHttpClient.prototype.post = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.POST, data, parser, headers);
};

BaseHttpClient.prototype.put = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.PUT, data, parser, headers);
};

BaseHttpClient.prototype.delete = function (url, parser, headers) {
    return this._handleRequest(url, Methods.DELETE, null, parser, headers);
};

BaseHttpClient.prototype.jsonp = function (url, parser, headers) {
    url = UrlNormalizer.normalizeJsonp(url);
    return this._handleRequest(url, Methods.JSONP, null, parser, headers);
};

BaseHttpClient.prototype.multipart = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.MULTIPART, data, parser, headers);
};

BaseHttpClient.prototype._handleRequest = function (url, method, data, parser, headers, plainResponse) {
    return new Promise(_.bind(function (resolve, reject) {
        parser = parser || new Parser();
        var unwrapResponse = this.unwrapResponse();
        this._getNetworkPromise(url, method, data, headers, plainResponse)
            .then(function (response) {
                if (!unwrapResponse)
                    resolve(parser.parse(response.data));
                else
                    resolve([parser.parse(response.data), response.status, response.headers, response.config]);
            })
            .catch(function (error) {
                if (!unwrapResponse)
                    reject(error);
                else
                    reject({data: error.error, status: error.status, headers: error.headers, config: error.config});
            });
    }, this));
};

BaseHttpClient.prototype._getNetworkPromise = function (url, method, data, headers, plainResponse) {
    var config = {
        headers: headers,
        withCredentials: this.credentialsRequestsEnabled()
    };
    if (plainResponse)
        config.transformResponse = undefined;
    if (method === Methods.MULTIPART) {
        config.transformRequest = angular.identity;
        config.headers = config.headers || {};
        config.headers['Content-Type'] = undefined;
    }
    switch (method) {
        case Methods.GET:
            return this._http.get(url, config);
        case Methods.POST:
        case Methods.MULTIPART:
            return this._http.post(url, data, config);
        case Methods.PUT:
            return this._http.put(url, data, config);
        case Methods.DELETE:
            return this._http.delete(url, config);
        case Methods.JSONP:
            return this._http.jsonp(url, config);
    }
};

module.exports = BaseHttpClient;
<|endoftext|>


<commit_before>var path = require('path');

module.exports = function (start, opts) {
    var modules = opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
    var prefix = '/';
    if (/^([A-Za-z]:)/.test(start)) {
        prefix = '';
    } else if (/^\\\\/.test(start)) {
        prefix = '\\\\';
    }
    var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
    var parts = start.split(splitRe);

    var dirs = [];
    for (var i = parts.length - 1; i >= 0; i--) {
        if (modules.indexOf(parts[i]) !== -1) continue;
        dirs = dirs.concat(modules.map(function(module_dir) {
            return prefix + path.join(
                path.join.apply(path, parts.slice(0, i + 1)),
                module_dir
            );
        }));
    }
    if(process.platform === 'win32'){
        dirs[dirs.length-1] = dirs[dirs.length-1].replace(":", ":\\");
    }
    return dirs.concat(opts.paths);
}<commit_msg>formatting<commit_after>var path = require('path');

module.exports = function (start, opts) {
    var modules = opts.moduleDirectory
        ? [].concat(opts.moduleDirectory)
        : ['node_modules']
    ;
    var prefix = '/';
    if (/^([A-Za-z]:)/.test(start)) {
        prefix = '';
    } else if (/^\\\\/.test(start)) {
        prefix = '\\\\';
    }
    var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
    var parts = start.split(splitRe);

    var dirs = [];
    for (var i = parts.length - 1; i >= 0; i--) {
        if (modules.indexOf(parts[i]) !== -1) continue;
        dirs = dirs.concat(modules.map(function(module_dir) {
            return prefix + path.join(
                path.join.apply(path, parts.slice(0, i + 1)),
                module_dir
            );
        }));
    }
    if (process.platform === 'win32'){
        dirs[dirs.length-1] = dirs[dirs.length-1].replace(":", ":\\");
    }
    return dirs.concat(opts.paths);
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash')
    , CloudFormationFunction = require('./cloud-formation-function')
    , AWSResource = require('./aws-resource');

function ensureValueValid(type, x) {
    if (!type.validate(x)) {
        throw Error(`${type.name}.toCloudFormationValue received invalid value ${x}.`);
    }
}

const NUMBER_TO_NAME_MAP = {
    1: 'icmp',
    4: 'ipv4',
    6: 'tcp',
    17: 'udp',

    '-1': 'all',
};

function createProtocolNumberToNameMap() {
    return NUMBER_TO_NAME_MAP;
}

function createProtocolNameToNumberMap() {
    return _.reduce(NUMBER_TO_NAME_MAP, (m, v, k) => { m[v] = parseInt(k, 10); return m; }, {});
}

const Types = {
    ensureValueValid: ensureValueValid,

    string: {
        name: 'string',
        validate: function(x) {
            if (typeof x === 'string') {
                return true;
            }

            // implicit ref
            if (x instanceof AWSResource) {
                return true;
            }

            if (x instanceof CloudFormationFunction.Base) {
                return true;
            }

            // TODO: allow manually created function objects

            return false;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (x instanceof AWSResource) {
                return CloudFormationFunction.ref(x);
            }
            return x;
        },
    },

    regex: {
        name: 'regex',
        validate: function(x) {
            if (x instanceof RegExp) {
                return true;
            }

            return false;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.source;
        },
    },

    boolean: {
        name: 'boolean',
        validate: function(x) {
            return typeof x === 'boolean';
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.toString();
        },
    },

    enum: function() {
        var values = Array.prototype.slice.call(arguments);
        return {
            name: 'enum',
            validate: function(x) { return typeof x === 'string' && values.indexOf(x) !== -1; },
            toCloudFormationValue: function(x) {
                Types.ensureValueValid(this, x);
                return x;
            },
        };
    },

    range: function(from, to) {
        return {
            name: 'range',
            validate: function(x) { return typeof x === 'number' && x >= from && x <= to; },
            toCloudFormationValue: function(x) {
                Types.ensureValueValid(this, x);
                return x.toString();
            },
        };
    },

    number: {
        name: 'number',
        validate: function(x) { return typeof x === 'number'; },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.toString();
        },
    },

    cidr: {
        name: 'cidr',
        validate: function(x) {
            if (typeof x !== 'string') {
                return false;
            }

            return new RegExp(
                _.map(
                    [
                        /^/,
                        /(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}/,
                        /([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/,
                        /(\/([0-9]|[1-2][0-9]|3[0-2]))/,
                        /$/,
                    ],
                    r => r.source
                ).join('')
            ).test(x);
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x;
        },
    },

    protocol: {

        numberToNameMap: createProtocolNumberToNameMap(),

        nameToNumberMap: createProtocolNameToNumberMap(),

        valueAsName: function(x) {
            if (typeof x === 'number') {
                return this.numberToNameMap[x].toLowerCase();
            }
            return x.toLowerCase();
        },

        name: 'protocol',

        validate: function(x) {
            if (typeof x === 'number') {
                return x in this.numberToNameMap;
            }
            if (typeof x !== 'string') {
                return false;
            }

            return x.toLowerCase() in this.nameToNumberMap;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (typeof x === 'string') {
                x = this.nameToNumberMap[x.toLowerCase()];
            }
            return x.toString();
        },
    },

    tags: {

        validOptions: {
            'PropagateAtLaunch': 'boolean',
        },

        getValueAndOptions: function(valueOrOptions) {
            if (typeof valueOrOptions === 'object' &&
                !(valueOrOptions instanceof AWSResource) &&
                !(valueOrOptions instanceof CloudFormationFunction.Base)) {
                return {
                    value: valueOrOptions.Value,
                    options: _.omit(valueOrOptions, 'Value'),
                };
            }

            return {
                value: valueOrOptions,
                options: {},
            };
        },

        name: 'tags',

        validate: function(x) {
            if (typeof x !== 'object') {
                return false;
            }

            return _.every(x, (tagValue, tagName) => {
                var tagData = this.getValueAndOptions(tagValue);

                if (typeof tagData.value !== 'string' &&
                    !(tagData.value instanceof AWSResource) &&
                    !(tagData.value instanceof CloudFormationFunction.Base)) {
                    return false;
                }

                // the only accepted option at the moment is 'PropagateAtLaunch'
                return _.every(tagData.options, (optionValue, optionName) => {
                    return optionName in this.validOptions
                        && typeof optionValue === this.validOptions[optionName];
                });
            });
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return _.map(x, (tagValue, tagName) => {
                var tagData = this.getValueAndOptions(tagValue);
                return _.extend({
                    Key: tagName,
                    Value: tagData.value,
                }, _.reduce(tagData.options, (m, v, k) => {m[k] = v.toString(); return m; }, {}));
            });
        },
    },

    portrange: {
        name: 'portrange',
        validate: function(x) {
            if (!_.isArray(x)) {
                return false;
            }

            if (x.length !== 2) {
                return false;
            }

            if (x[0] > x[1]) {
                return false;
            }

            return _.every(x, p => _.isNumber(p) && p > 0 && p <= 65535);
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return {
                From: x[0].toString(),
                To: x[1].toString(),
            };
        },
    },

    jsonobject: {
        name: 'jsonobject',
        validate: function(x) {
            if (typeof x === 'object') {
                return true;
            }

            if (typeof x !== 'string') {
                return false;
            }

            try {
                JSON.parse(x);
            } catch (e) {
                return false;
            }

            return true;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (typeof x === 'string') {
                return JSON.parse(x);
            }
            return x;
        },
    },

    object: function(name, properties) {
        return {
            name: name,
            validate: function(x) {
                if (typeof x !== 'object') {
                    return false;
                }
                if (!properties) {
                    return true;
                }
                return _.every(x, function(value, key) {
                    var type = properties[key];
                    if (type) {
                        return type.validate(value);
                    }
                    return false;
                });
            },
            toCloudFormationValue: function(x) {
                if (!properties) {
                    return x;
                }
                return _.mapValues(x, function(value, key) {
                    var type = properties[key];
                    if (type && type.toCloudFormationValue) {
                        return type.toCloudFormationValue(value);
                    }
                    return value;
                });
            },
        };
    },

    // TODO: make typed arrays
    array: {
        name: 'array',
        validate: function(/* x */) {
            return true;
        },
    },
};

module.exports = Types;
<commit_msg>fix lint<commit_after>'use strict';

var _ = require('lodash')
    , CloudFormationFunction = require('./cloud-formation-function')
    , AWSResource = require('./aws-resource');

function ensureValueValid(type, x) {
    if (!type.validate(x)) {
        throw Error(`${type.name}.toCloudFormationValue received invalid value ${x}.`);
    }
}

const NUMBER_TO_NAME_MAP = {
    1: 'icmp',
    4: 'ipv4',
    6: 'tcp',
    17: 'udp',

    '-1': 'all',
};

function createProtocolNumberToNameMap() {
    return NUMBER_TO_NAME_MAP;
}

function createProtocolNameToNumberMap() {
    return _.reduce(NUMBER_TO_NAME_MAP, (m, v, k) => { m[v] = parseInt(k, 10); return m; }, {});
}

const Types = {
    ensureValueValid: ensureValueValid,

    string: {
        name: 'string',
        validate: function(x) {
            if (typeof x === 'string') {
                return true;
            }

            // implicit ref
            if (x instanceof AWSResource) {
                return true;
            }

            if (x instanceof CloudFormationFunction.Base) {
                return true;
            }

            // TODO: allow manually created function objects

            return false;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (x instanceof AWSResource) {
                return CloudFormationFunction.ref(x);
            }
            return x;
        },
    },

    regex: {
        name: 'regex',
        validate: function(x) {
            if (x instanceof RegExp) {
                return true;
            }

            return false;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.source;
        },
    },

    boolean: {
        name: 'boolean',
        validate: function(x) {
            return typeof x === 'boolean';
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.toString();
        },
    },

    enum: function() {
        var values = Array.prototype.slice.call(arguments);
        return {
            name: 'enum',
            validate: function(x) { return typeof x === 'string' && values.indexOf(x) !== -1; },
            toCloudFormationValue: function(x) {
                Types.ensureValueValid(this, x);
                return x;
            },
        };
    },

    range: function(from, to) {
        return {
            name: 'range',
            validate: function(x) { return typeof x === 'number' && x >= from && x <= to; },
            toCloudFormationValue: function(x) {
                Types.ensureValueValid(this, x);
                return x.toString();
            },
        };
    },

    number: {
        name: 'number',
        validate: function(x) { return typeof x === 'number'; },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x.toString();
        },
    },

    cidr: {
        name: 'cidr',
        validate: function(x) {
            if (typeof x !== 'string') {
                return false;
            }

            return new RegExp(
                _.map(
                    [
                        /^/,
                        /(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}/,
                        /([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/,
                        /(\/([0-9]|[1-2][0-9]|3[0-2]))/,
                        /$/,
                    ],
                    r => r.source
                ).join('')
            ).test(x);
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return x;
        },
    },

    protocol: {

        numberToNameMap: createProtocolNumberToNameMap(),

        nameToNumberMap: createProtocolNameToNumberMap(),

        valueAsName: function(x) {
            if (typeof x === 'number') {
                return this.numberToNameMap[x].toLowerCase();
            }
            return x.toLowerCase();
        },

        name: 'protocol',

        validate: function(x) {
            if (typeof x === 'number') {
                return x in this.numberToNameMap;
            }
            if (typeof x !== 'string') {
                return false;
            }

            return x.toLowerCase() in this.nameToNumberMap;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (typeof x === 'string') {
                x = this.nameToNumberMap[x.toLowerCase()];
            }
            return x.toString();
        },
    },

    tags: {

        validOptions: {
            'PropagateAtLaunch': 'boolean',
        },

        getValueAndOptions: function(valueOrOptions) {
            if (typeof valueOrOptions === 'object' &&
                !(valueOrOptions instanceof AWSResource) &&
                !(valueOrOptions instanceof CloudFormationFunction.Base)) {
                return {
                    value: valueOrOptions.Value,
                    options: _.omit(valueOrOptions, 'Value'),
                };
            }

            return {
                value: valueOrOptions,
                options: {},
            };
        },

        name: 'tags',

        validate: function(x) {
            if (typeof x !== 'object') {
                return false;
            }

            return _.every(x, tagValue => {
                var tagData = this.getValueAndOptions(tagValue);

                if (typeof tagData.value !== 'string' &&
                    !(tagData.value instanceof AWSResource) &&
                    !(tagData.value instanceof CloudFormationFunction.Base)) {
                    return false;
                }

                return _.every(tagData.options, (optionValue, optionName) => {
                    return optionName in this.validOptions
                        && typeof optionValue === this.validOptions[optionName];
                });
            });
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return _.map(x, (tagValue, tagName) => {
                var tagData = this.getValueAndOptions(tagValue);
                return _.extend({
                    Key: tagName,
                    Value: tagData.value,
                }, _.reduce(tagData.options, (m, v, k) => {m[k] = v.toString(); return m; }, {}));
            });
        },
    },

    portrange: {
        name: 'portrange',
        validate: function(x) {
            if (!_.isArray(x)) {
                return false;
            }

            if (x.length !== 2) {
                return false;
            }

            if (x[0] > x[1]) {
                return false;
            }

            return _.every(x, p => _.isNumber(p) && p > 0 && p <= 65535);
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            return {
                From: x[0].toString(),
                To: x[1].toString(),
            };
        },
    },

    jsonobject: {
        name: 'jsonobject',
        validate: function(x) {
            if (typeof x === 'object') {
                return true;
            }

            if (typeof x !== 'string') {
                return false;
            }

            try {
                JSON.parse(x);
            } catch (e) {
                return false;
            }

            return true;
        },
        toCloudFormationValue: function(x) {
            Types.ensureValueValid(this, x);
            if (typeof x === 'string') {
                return JSON.parse(x);
            }
            return x;
        },
    },

    object: function(name, properties) {
        return {
            name: name,
            validate: function(x) {
                if (typeof x !== 'object') {
                    return false;
                }
                if (!properties) {
                    return true;
                }
                return _.every(x, function(value, key) {
                    var type = properties[key];
                    if (type) {
                        return type.validate(value);
                    }
                    return false;
                });
            },
            toCloudFormationValue: function(x) {
                if (!properties) {
                    return x;
                }
                return _.mapValues(x, function(value, key) {
                    var type = properties[key];
                    if (type && type.toCloudFormationValue) {
                        return type.toCloudFormationValue(value);
                    }
                    return value;
                });
            },
        };
    },

    // TODO: make typed arrays
    array: {
        name: 'array',
        validate: function(/* x */) {
            return true;
        },
    },
};

module.exports = Types;
<|endoftext|>


<commit_before>var abstract_udp = require('./abstract_udp'),
  hepjs = require('hep-js'),
  util = require('util'),
  logger = require('log4node');

function OutputHep() {
  abstract_udp.AbstractUdp.call(this);
  this.mergeConfig({
    name: 'Udp',
  });
  this.mergeConfig(this.serializer_config());
  this.mergeConfig({
    name: 'HEP/EEP Server',
    optional_params: ['hep_id', 'hep_pass', 'hep_cid', 'hep_type', 'src_ip', 'src_port', 'dst_ip', 'dst_port', 'hep_payload_type', 'hep_ip_family', 'hep_protocol', 'transaction_type'],
    default_values: {
      host: '127.0.0.1',
      port: 9063,
      hep_id: '2001',
      hep_pass: 'MyHep',
      hep_cid: '#{correlation_id}',
      hep_type: 100,
      hep_payload_type: 1,
      hep_ip_family: 1,
      hep_protocol: 17,
      src_ip: '127.0.0.1',
      src_port: '0',
      dst_ip: '127.0.0.2',
      dst_port: '0',
      hep_timefield: false
    },
  });
}

util.inherits(OutputHep, abstract_udp.AbstractUdp);

OutputHep.prototype.preHep = function(data) {

  try {
	  // IF HEP JSON
	  if (data.rcinfo && data.payload) {
		logger.debug('PRE-PACKED HEP JSON!');
		data.rcinfo.captureId = this.hep_id;
		data.rcinfo.capturePass = this.hep_pass;
		return hepjs.encapsulate(data.payload,data.rcinfo);
	  };

	  // Default HEP RCINFO
	  var hep_proto = {
	    'type': 'HEP',
	    'version': 3,
	    'payload_type': this.hep_payload_type,
	    'proto_type': this.hep_type,
	    'captureId': this.hep_id,
	    'capturePass': this.hep_pass,
	    'ip_family': this.hep_ip_family,
	    'protocol': this.hep_protocol
	  };

  	var datenow = new Date();
	hep_proto.time_sec = data.time_sec || Math.floor(datenow.getTime() / 1000);
	hep_proto.time_usec = data.time_usec || datenow.getMilliseconds() * 1000;
	// Build HEP3 w/ null network parameters - TBD configurable
  	hep_proto.srcIp = data.srcIp || this.src_ip;
  	hep_proto.dstIp = data.dstIp || this.dst_ip;
  	hep_proto.srcPort = data.srcPort || this.src_port;
  	hep_proto.dstPort = data.dstPort || this.dst_port;
  	// pair correlation id from pattern
	hep_proto.correlation_id = data.correlation_id || '';
	// Optional Transaction Type
	if (this.transaction_type) { hep_proto.transaction_type = this.transaction_type; }

	if (data.payload) {
	    // Pack HEP3
	    return hepjs.encapsulate(JSON.stringify(data.payload),hep_proto);
 	} else {
	    // Pack HEP3 Log Type fallback
	    hep_proto.payload_type = 100;
	    return hepjs.encapsulate(JSON.stringify(data),hep_proto);
        }

   } catch(e) { logger.error('PREHEP ERROR:',e); }
};

OutputHep.prototype.formatPayload = function(data, callback) {
  if (data) callback(this.preHep(data));
};

OutputHep.prototype.to = function() {
  return 'HEP udp to ' + this.host + ':' + this.port;
};

exports.create = function() {
  return new OutputHep();
};
<commit_msg>Update output_hep.js (#103)<commit_after>var abstract_udp = require('./abstract_udp'),
  hepjs = require('hep-js'),
  util = require('util'),
  logger = require('log4node');

function OutputHep() {
  abstract_udp.AbstractUdp.call(this);
  this.mergeConfig({
    name: 'Udp',
  });
  this.mergeConfig(this.serializer_config());
  this.mergeConfig({
    name: 'HEP/EEP Server',
    optional_params: ['hep_id', 'hep_pass', 'hep_cid', 'hep_type', 'src_ip', 'src_port', 'dst_ip', 'dst_port', 'hep_payload_type', 'hep_ip_family', 'hep_protocol', 'transaction_type'],
    default_values: {
      host: '127.0.0.1',
      port: 9063,
      hep_id: '2001',
      hep_pass: 'MyHep',
      hep_cid: '#{correlation_id}',
      hep_type: 100,
      hep_payload_type: 1,
      hep_ip_family: 1,
      hep_protocol: 17,
      src_ip: '127.0.0.1',
      src_port: '0',
      dst_ip: '127.0.0.2',
      dst_port: '0',
      hep_timefield: false
    },
  });
}

util.inherits(OutputHep, abstract_udp.AbstractUdp);

OutputHep.prototype.preHep = function(data) {

  try {
	  // IF HEP JSON
	  if (data.rcinfo && data.payload) {
		logger.debug('PRE-PACKED HEP JSON!');
		data.rcinfo.captureId = this.hep_id;
		data.rcinfo.capturePass = this.hep_pass;
		return hepjs.encapsulate(JSON.stringify(data.payload),data.rcinfo);
	  };

	  // Default HEP RCINFO
	  var hep_proto = {
	    'type': 'HEP',
	    'version': 3,
	    'payload_type': this.hep_payload_type,
	    'proto_type': this.hep_type,
	    'captureId': this.hep_id,
	    'capturePass': this.hep_pass,
	    'ip_family': this.hep_ip_family,
	    'protocol': this.hep_protocol
	  };

  	var datenow = new Date();
	hep_proto.time_sec = data.time_sec || Math.floor(datenow.getTime() / 1000);
	hep_proto.time_usec = data.time_usec || datenow.getMilliseconds() * 1000;
	// Build HEP3 w/ null network parameters - TBD configurable
  	hep_proto.srcIp = data.srcIp || this.src_ip;
  	hep_proto.dstIp = data.dstIp || this.dst_ip;
  	hep_proto.srcPort = data.srcPort || this.src_port;
  	hep_proto.dstPort = data.dstPort || this.dst_port;
  	// pair correlation id from pattern
	hep_proto.correlation_id = data.correlation_id || '';
	// Optional Transaction Type
	if (this.transaction_type) { hep_proto.transaction_type = this.transaction_type; }

	if (data.payload) {
	    // Pack HEP3
	    return hepjs.encapsulate(JSON.stringify(data.payload),hep_proto);
 	} else {
	    // Pack HEP3 Log Type fallback
	    hep_proto.payload_type = 100;
	    return hepjs.encapsulate(JSON.stringify(data),hep_proto);
        }

   } catch(e) { logger.error('PREHEP ERROR:',e); }
};

OutputHep.prototype.formatPayload = function(data, callback) {
  if (data) callback(this.preHep(data));
};

OutputHep.prototype.to = function() {
  return 'HEP udp to ' + this.host + ':' + this.port;
};

exports.create = function() {
  return new OutputHep();
};
<|endoftext|>


<commit_before>require('proof')(3, prove)

function prove (okay, callback) {
    var Destructible = require('destructible')
    var destructible = new Destructible('test/http.t')

    var path = require('path')

    destructible.completed.wait(callback)

    var cadence = require('cadence')

    var UserAgent = require('vizsla')
    var Mock = require('olio/mock')

    cadence(function (async) {
        async(function () {
            destructible.durable('mock', Mock, {
                socket: path.join(__dirname, 'socket'),
                children: {
                    http: {
                        path: path.resolve(__dirname, '../olio.js'),
                        properties: { port: 8888, iface: '127.0.0.1' }
                    },
                    mingle: {
                        path: path.resolve(__dirname, './mingle.js'),
                        properties: {}
                    }
                }
            }, async())
        }, function () {
            var ua = new UserAgent
            async(function () {
                ua.fetch({
                    url: 'http://127.0.0.1:8888/',
                    parse: 'text',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, 'Mingle API\n', 'index')
                ua.fetch({
                    url: 'http://127.0.0.1:8888/health',
                    parse: 'json',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, {
                    http: { occupied: 1, waiting: 0, rejecting: 0, turnstiles: 24 }
                }, 'health')
                ua.fetch({
                    url: 'http://127.0.0.1:8888/discover',
                    parse: 'json',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, [ '127.0.0.1:8080' ], 'discover')
            })
        })
    })(destructible.durable('test'))
}
<commit_msg>Fix Olio upgrade.<commit_after>require('proof')(3, prove)

function prove (okay, callback) {
    var Destructible = require('destructible')
    var destructible = new Destructible('test/http.t')
    var path = require('path')

    destructible.completed.wait(callback)

    var cadence = require('cadence')

    var UserAgent = require('vizsla')
    var Mock = require('olio/mock')

    cadence(function (async) {
        async(function () {
            destructible.durable('mock', Mock, {
                socket: path.join(__dirname, 'socket'),
                constituents: {
                    http: {
                        path: path.resolve(__dirname, '../olio.js'),
                        properties: { port: 8888, iface: '127.0.0.1' }
                    },
                    mingle: {
                        path: path.resolve(__dirname, './mingle.js'),
                        properties: {}
                    }
                }
            }, async())
        }, function () {
            var ua = new UserAgent
            async(function () {
                ua.fetch({
                    url: 'http://127.0.0.1:8888/',
                    parse: 'text',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, 'Mingle API\n', 'index')
                ua.fetch({
                    url: 'http://127.0.0.1:8888/health',
                    parse: 'json',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, {
                    http: { occupied: 1, waiting: 0, rejecting: 0, turnstiles: 24 }
                }, 'health')
                ua.fetch({
                    url: 'http://127.0.0.1:8888/discover',
                    parse: 'json',
                    raise: true
                }, async())
            }, function (body) {
                okay(body, [ '127.0.0.1:8080' ], 'discover')
            })
        })
    })(destructible.durable('test'))
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// WebKit Web Facing API
var console = {}
/** @param {...*} vararg */
console.warn = function(vararg) {}
/** @param {...*} vararg */
console.assert = function(vararg) {}
/** @param {...*} vararg */
console.error = function(vararg) {}
console.trace = function() {}

/** @param {boolean=} param */
Element.prototype.scrollIntoViewIfNeeded = function(param) {}
/** @type {boolean} */
Event.prototype.isMetaOrCtrlForTest = false;
/** @param {...*} vararg */
Event.prototype.initWebKitWheelEvent = function(vararg) {}
Event.prototype.stopImmediatePropagation = function() {}

/** @param {Element} element */
window.getComputedStyle = function(element) {}
/** @param {*} message */
function postMessage(message) {}

/** @type {*} */
window.testRunner = null;

/**
 * @constructor
 */
function WebKitMutation(callback)
{
    this.type = "";
    /** @type {Node} */ this.target = null;
    /** @type {Array.<Node>} */ this.addedNodes = [];
    /** @type {Array.<Node>} */ this.removedNodes = [];
}

/**
 * @constructor
 * @param {function(Array.<WebKitMutation>)} callback
 */
function WebKitMutationObserver(callback) {}
/**
 * @param {Node} container
 * @param {Object} options
 */
WebKitMutationObserver.prototype.observe = function(container, options) {}
WebKitMutationObserver.prototype.disconnect = function() {}

/**
 * @param {string} eventName
 * @param {Function} listener
 * @param {boolean=} capturing
 */
function addEventListener(eventName, listener, capturing) {}

/** @param {boolean=} onlyFirst */
Array.prototype.remove = function(obj, onlyFirst) {}
Array.prototype.keySet = function() {}
/** @return {number} */
Array.prototype.upperBound = function(anchor) {}
/** @return {number} */
Array.prototype.binaryIndexOf = function(anchor) {}
Array.prototype.sortRange = function(comparator, leftBound, rightBound, k) {}

/**
 * @this {Array.<number>}
 * @param {function(number,number):boolean} comparator
 * @param {number} left
 * @param {number} right
 * @param {number} pivotIndex
 * @return {number}
 */
Array.prototype.partition = function(comparator, left, right, pivotIndex) {}

/**
 * @this {Array.<number>}
 * @param {number} k
 * @param {function(number,number):boolean=} comparator
 * @return {number}
 */
Array.prototype.qselect = function(k, comparator) {}

/**
 * @this {Array.<*>}
 * @param {string} field
 * @return {Array.<*>}
 */
Array.prototype.select = function(field) {}

/**
 * @this {Array.<*>}
 * @return {*}
 */
Array.prototype.peekLast = function() {}

DOMApplicationCache.prototype.UNCACHED = 0;
DOMApplicationCache.prototype.IDLE = 1;
DOMApplicationCache.prototype.CHECKING = 2;
DOMApplicationCache.prototype.DOWNLOADING = 3;
DOMApplicationCache.prototype.UPDATEREADY = 4;
DOMApplicationCache.prototype.OBSOLETE = 5;

// File System API
/**
 * @constructor
 */
function DOMFileSystem() {}

/**
 * @type {DirectoryEntry}
 */
DOMFileSystem.prototype.root = null;

/** @type {Node} */
Range.prototype.startContainer;

// Inspector Backend
var InspectorBackend = {}
InspectorBackend.runAfterPendingDispatches = function(message) {}

/** @interface */
function InspectorFrontendHostAPI() {}
InspectorFrontendHostAPI.prototype.platform = function() {}
InspectorFrontendHostAPI.prototype.port = function() {}
InspectorFrontendHostAPI.prototype.bringToFront = function() {}
InspectorFrontendHostAPI.prototype.closeWindow = function() {}
InspectorFrontendHostAPI.prototype.requestSetDockSide = function(dockSide) {}
InspectorFrontendHostAPI.prototype.setAttachedWindowHeight = function(height) {}
InspectorFrontendHostAPI.prototype.moveWindowBy = function(x, y) {}
InspectorFrontendHostAPI.prototype.setInjectedScriptForOrigin = function(origin, script) {}
InspectorFrontendHostAPI.prototype.loaded = function() {}
InspectorFrontendHostAPI.prototype.localizedStringsURL = function() {}
InspectorFrontendHostAPI.prototype.inspectedURLChanged = function(url) {}
InspectorFrontendHostAPI.prototype.documentCopy = function(event) {}
InspectorFrontendHostAPI.prototype.copyText = function(text) {}
InspectorFrontendHostAPI.prototype.openInNewTab = function(url) {}
InspectorFrontendHostAPI.prototype.canSave = function() {}
InspectorFrontendHostAPI.prototype.save = function(url, content, forceSaveAs) {}
InspectorFrontendHostAPI.prototype.close = function(url) {}
InspectorFrontendHostAPI.prototype.append = function(url, content) {}
InspectorFrontendHostAPI.prototype.sendMessageToBackend = function(message) {}
InspectorFrontendHostAPI.prototype.recordActionTaken = function(actionCode) {}
InspectorFrontendHostAPI.prototype.recordPanelShown = function(panelCode) {}
InspectorFrontendHostAPI.prototype.recordSettingChanged = function(settingCode) {}
InspectorFrontendHostAPI.prototype.loadResourceSynchronously = function(url) {}
InspectorFrontendHostAPI.prototype.supportsFileSystems = function() {}
InspectorFrontendHostAPI.prototype.requestFileSystems = function() {}
InspectorFrontendHostAPI.prototype.addFileSystem = function() {}
InspectorFrontendHostAPI.prototype.removeFileSystem = function(fileSystemPath) {}
InspectorFrontendHostAPI.prototype.isolatedFileSystem = function(fileSystemId, registeredName) {}
InspectorFrontendHostAPI.prototype.setZoomFactor = function(zoom) {}
/** @type {InspectorFrontendHostAPI} */
var InspectorFrontendHost;

/** @constructor */
function SourceMapV3()
{
    /** @type {number} */ this.version;
    /** @type {string} */ this.file;
    /** @type {Array.<string>} */ this.sources;
    /** @type {Array.<SourceMapV3.Section>} */ this.sections;
    /** @type {string} */ this.mappings;
    /** @type {string} */ this.sourceRoot;
}

/** @constructor */
SourceMapV3.Section = function()
{
    /** @type {SourceMapV3} */ this.map;
    /** @type {SourceMapV3.Offset} */ this.offset;
}

/** @constructor */
SourceMapV3.Offset = function()
{
    /** @type {number} */ this.line;
    /** @type {number} */ this.column;
}

// FIXME: remove everything below.
var WebInspector = {}

WebInspector.queryParamsObject = {}
WebInspector.toggleSearchingForNode = function() {}
WebInspector.panels = {};

/**
 * @param {Element} element
 * @param {function()=} onclose
 */
WebInspector.showViewInDrawer = function(element, view, onclose) {}

WebInspector.closeViewInDrawer = function() {}

/**
 * @param {string=} messageLevel
 * @param {boolean=} showConsole
 */
WebInspector.log = function(message, messageLevel, showConsole) {}

WebInspector.showErrorMessage = function(error) {}

WebInspector.addMainEventListeners = function(doc) {}

WebInspector.openResource = function(url, external) {}

WebInspector.showConsole = function() {}

/**
 * @param {string} expression
 * @param {boolean=} showResultOnly
 */
WebInspector.evaluateInConsole = function(expression, showResultOnly) {}

WebInspector.queryParamsObject = {}

/**
 * @param {Element} element
 */
WebInspector.showAnchorLocation = function(element) {}

WebInspector.Events = {
    InspectorLoaded: "InspectorLoaded",
    InspectorClosing: "InspectorClosing"
}

/** Extensions API */

/** @constructor */
function AuditCategory() {}
/** @constructor */
function AuditResult() {}
/** @constructor */
function EventSink() {}
/** @constructor */
function ExtensionSidebarPane() {}
/** @constructor */
function Panel() {}
/** @constructor */
function PanelWithSidebar() {}
/** @constructor */
function Request() {}
/** @constructor */
function Resource() {}
/** @constructor */
function Timeline() {}

var extensionServer;

/** @type {string} */
Location.prototype.origin = "";

/**
 * @constructor
 */
function ExtensionDescriptor() {
    this.startPage = "";
    this.name = "";
}

/**
 * @constructor
 */
function ExtensionReloadOptions() {
    this.ignoreCache = false;
    this.injectedScript = "";
    this.userAgent = "";
}

WebInspector.showPanel = function(panel)
{
}

/**
 * @param {ExtensionDescriptor} extensionInfo
 * @return {string}
 */
function buildPlatformExtensionAPI(extensionInfo) {}

/**
 * @type {string}
 */
WebInspector.inspectedPageDomain;

WebInspector.SourceJavaScriptTokenizer = {}
WebInspector.SourceJavaScriptTokenizer.Keywords = {}

var InspectorTest = {}

/* jsdifflib API */
var difflib = {};
difflib.stringAsLines = function(text) { return []; }
/** @constructor */
difflib.SequenceMatcher = function(baseText, newText) { }
difflib.SequenceMatcher.prototype.get_opcodes = function() { return []; }

/** @constructor */
WebInspector.AceTextEditor = function(url, delegate) { }

/** @constructor */
var CodeMirror = function() { }
CodeMirror.on = function(obj, type, handler) { }
CodeMirror.prototype = {
    addKeyMap: function(map) { },
    addLineClass: function(handle, where, cls) { },
    addLineWidget: function(handle, node, options) { },
    /**
     * @param {string|Object} spec
     * @param {Object=} options
     */
    addOverlay: function(spec, options) { },
    addWidget: function(pos, node, scroll, vert, horiz) { },
    charCoords: function(pos, mode) { },
    clearGutter: function(gutterID) { },
    clearHistory: function() { },
    clipPos: function(pos) { },
    coordsChar: function(coords, mode) { },
    cursorCoords: function(start, mode) { },
    defaultCharWidth: function() { },
    defaultTextHeight: function() { },
    deleteH: function(dir, unit) { },
    eachLine: function(from, to, op) { },
    execCommand: function(cmd) { },
    extendSelection: function(from, to) { },
    findMarksAt: function(pos) { },
    findMatchingBracket: function() { },
    findPosH: function(from, amount, unit, visually) { },
    findPosV: function(from, amount, unit, goalColumn) { },
    firstLine: function() { },
    focus: function() { },
    getAllMarks: function() { },
    getCursor: function(start) { },
    getDoc: function() { },
    getGutterElement: function() { },
    getHistory: function() { },
    getInputField: function(){ },
    getLine: function(line) { },
    /**
     * @return {{wrapClass: string}}
     */
    getLineHandle: function(line) { },
    getLineNumber: function(line) { },
    getMode: function() { },
    getOption: function(option) { },
    getRange: function(from, to, lineSep) { },
    getScrollInfo: function() { },
    getScrollerElement: function() { },
    getSelection: function() { },
    getStateAfter: function(line) { },
    getTokenAt: function(pos) { },
    getValue: function(lineSep) { },
    getViewport: function() { },
    getWrapperElement: function() { },
    hasFocus: function() { },
    historySize: function() { },
    indentLine: function(n, dir, aggressive) { },
    indentSelection: function(how) { },
    indexFromPos: function(coords) { },
    isClean: function() { },
    iterLinkedDocs: function(f) { },
    lastLine: function() { },
    lineCount: function() { },
    lineInfo: function(line) { },
    linkedDoc: function(options) { },
    markClean: function() { },
    markText: function(from, to, options) { },
    moveH: function(dir, unit) { },
    moveV: function(dir, unit) { },
    off: function(type, f) { },
    on: function(type, f) { },
    operation: function(f) { },
    posFromIndex: function(off) { },
    redo: function() { },
    refresh: function() { },
    removeKeyMap: function(map) { },
    removeLine: function(line) { },
    removeLineClass: function(handle, where, cls) { },
    removeLineWidget: function(widget) { },
    removeOverlay: function(spec) { },
    replaceRange: function(code, from, to, origin) { },
    replaceSelection: function(code, collapse, origin) { },
    scrollIntoView: function(pos, margin) { },
    scrollTo: function(x, y) { },
    setBookmark: function(pos, options) { },
    setCursor: function(line, ch, extend) { },
    setExtending: function(val) { },
    setGutterMarker: function(line, gutterID, value) { },
    setHistory: function(histData) { },
    setLine: function(line, text) { },
    setOption: function(option, value) { },
    setSelection: function(anchor, head) { },
    setSize: function(width, height) { },
    setValue: function(code) { },
    somethingSelected: function() { },
    swapDoc: function(doc) { },
    undo: function() { },
    unlinkDoc: function(other) { }
}
/** @type {number} */
CodeMirror.prototype.lineCount;
CodeMirror.Pass;
CodeMirror.showHint = function(codeMirror, hintintFunction) { };
CodeMirror.commands = {};

/** @constructor */
CodeMirror.Pos = function(line, ch) { }
/** type {number} */
CodeMirror.Pos.prototype.line;
/** type {number} */
CodeMirror.Pos.prototype.ch;

/** @constructor */
CodeMirror.StringStream = function() { }
CodeMirror.StringStream.prototype = {
    backUp: function (n) { },
    column: function () { },
    current: function () { },
    eat: function (match) { },
    eatSpace: function () { },
    eatWhile: function (match) { },
    eol: function () { },
    indentation: function () { },
    /**
     * @param {RegExp|string} pattern
     * @param {boolean=} consume
     * @param {boolean=} caseInsensitive
     */
    match: function (pattern, consume, caseInsensitive) { },
    next: function () { },
    peek: function () { },
    skipTo: function (ch) { },
    skipToEnd: function () { },
    sol: function () { }
}

WebInspector.suggestReload = function() { }
WebInspector.reload = function() { }

/** @type {boolean} */
window.dispatchStandaloneTestRunnerMessages;

WebInspector.settings.continuousPainting = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showDebugBorders = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showFPSCounter = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showPaintRects = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showFPSCounter = /** type {WebInspector.Setting} */ { }
<commit_msg>DevTools: [CodeMirror] fix compilation warnings<commit_after>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// WebKit Web Facing API
var console = {}
/** @param {...*} vararg */
console.warn = function(vararg) {}
/** @param {...*} vararg */
console.assert = function(vararg) {}
/** @param {...*} vararg */
console.error = function(vararg) {}
console.trace = function() {}

/** @param {boolean=} param */
Element.prototype.scrollIntoViewIfNeeded = function(param) {}
/** @type {boolean} */
Event.prototype.isMetaOrCtrlForTest = false;
/** @param {...*} vararg */
Event.prototype.initWebKitWheelEvent = function(vararg) {}
Event.prototype.stopImmediatePropagation = function() {}

/** @param {Element} element */
window.getComputedStyle = function(element) {}
/** @param {*} message */
function postMessage(message) {}

/** @type {*} */
window.testRunner = null;

/**
 * @constructor
 */
function WebKitMutation(callback)
{
    this.type = "";
    /** @type {Node} */ this.target = null;
    /** @type {Array.<Node>} */ this.addedNodes = [];
    /** @type {Array.<Node>} */ this.removedNodes = [];
}

/**
 * @constructor
 * @param {function(Array.<WebKitMutation>)} callback
 */
function WebKitMutationObserver(callback) {}
/**
 * @param {Node} container
 * @param {Object} options
 */
WebKitMutationObserver.prototype.observe = function(container, options) {}
WebKitMutationObserver.prototype.disconnect = function() {}

/**
 * @param {string} eventName
 * @param {Function} listener
 * @param {boolean=} capturing
 */
function addEventListener(eventName, listener, capturing) {}

/** @param {boolean=} onlyFirst */
Array.prototype.remove = function(obj, onlyFirst) {}
Array.prototype.keySet = function() {}
/** @return {number} */
Array.prototype.upperBound = function(anchor) {}
/** @return {number} */
Array.prototype.binaryIndexOf = function(anchor) {}
Array.prototype.sortRange = function(comparator, leftBound, rightBound, k) {}

/**
 * @this {Array.<number>}
 * @param {function(number,number):boolean} comparator
 * @param {number} left
 * @param {number} right
 * @param {number} pivotIndex
 * @return {number}
 */
Array.prototype.partition = function(comparator, left, right, pivotIndex) {}

/**
 * @this {Array.<number>}
 * @param {number} k
 * @param {function(number,number):boolean=} comparator
 * @return {number}
 */
Array.prototype.qselect = function(k, comparator) {}

/**
 * @this {Array.<*>}
 * @param {string} field
 * @return {Array.<*>}
 */
Array.prototype.select = function(field) {}

/**
 * @this {Array.<*>}
 * @return {*}
 */
Array.prototype.peekLast = function() {}

DOMApplicationCache.prototype.UNCACHED = 0;
DOMApplicationCache.prototype.IDLE = 1;
DOMApplicationCache.prototype.CHECKING = 2;
DOMApplicationCache.prototype.DOWNLOADING = 3;
DOMApplicationCache.prototype.UPDATEREADY = 4;
DOMApplicationCache.prototype.OBSOLETE = 5;

// File System API
/**
 * @constructor
 */
function DOMFileSystem() {}

/**
 * @type {DirectoryEntry}
 */
DOMFileSystem.prototype.root = null;

/** @type {Node} */
Range.prototype.startContainer;

// Inspector Backend
var InspectorBackend = {}
InspectorBackend.runAfterPendingDispatches = function(message) {}

/** @interface */
function InspectorFrontendHostAPI() {}
InspectorFrontendHostAPI.prototype.platform = function() {}
InspectorFrontendHostAPI.prototype.port = function() {}
InspectorFrontendHostAPI.prototype.bringToFront = function() {}
InspectorFrontendHostAPI.prototype.closeWindow = function() {}
InspectorFrontendHostAPI.prototype.requestSetDockSide = function(dockSide) {}
InspectorFrontendHostAPI.prototype.setAttachedWindowHeight = function(height) {}
InspectorFrontendHostAPI.prototype.moveWindowBy = function(x, y) {}
InspectorFrontendHostAPI.prototype.setInjectedScriptForOrigin = function(origin, script) {}
InspectorFrontendHostAPI.prototype.loaded = function() {}
InspectorFrontendHostAPI.prototype.localizedStringsURL = function() {}
InspectorFrontendHostAPI.prototype.inspectedURLChanged = function(url) {}
InspectorFrontendHostAPI.prototype.documentCopy = function(event) {}
InspectorFrontendHostAPI.prototype.copyText = function(text) {}
InspectorFrontendHostAPI.prototype.openInNewTab = function(url) {}
InspectorFrontendHostAPI.prototype.canSave = function() {}
InspectorFrontendHostAPI.prototype.save = function(url, content, forceSaveAs) {}
InspectorFrontendHostAPI.prototype.close = function(url) {}
InspectorFrontendHostAPI.prototype.append = function(url, content) {}
InspectorFrontendHostAPI.prototype.sendMessageToBackend = function(message) {}
InspectorFrontendHostAPI.prototype.recordActionTaken = function(actionCode) {}
InspectorFrontendHostAPI.prototype.recordPanelShown = function(panelCode) {}
InspectorFrontendHostAPI.prototype.recordSettingChanged = function(settingCode) {}
InspectorFrontendHostAPI.prototype.loadResourceSynchronously = function(url) {}
InspectorFrontendHostAPI.prototype.supportsFileSystems = function() {}
InspectorFrontendHostAPI.prototype.requestFileSystems = function() {}
InspectorFrontendHostAPI.prototype.addFileSystem = function() {}
InspectorFrontendHostAPI.prototype.removeFileSystem = function(fileSystemPath) {}
InspectorFrontendHostAPI.prototype.isolatedFileSystem = function(fileSystemId, registeredName) {}
InspectorFrontendHostAPI.prototype.setZoomFactor = function(zoom) {}
/** @type {InspectorFrontendHostAPI} */
var InspectorFrontendHost;

/** @constructor */
function SourceMapV3()
{
    /** @type {number} */ this.version;
    /** @type {string} */ this.file;
    /** @type {Array.<string>} */ this.sources;
    /** @type {Array.<SourceMapV3.Section>} */ this.sections;
    /** @type {string} */ this.mappings;
    /** @type {string} */ this.sourceRoot;
}

/** @constructor */
SourceMapV3.Section = function()
{
    /** @type {SourceMapV3} */ this.map;
    /** @type {SourceMapV3.Offset} */ this.offset;
}

/** @constructor */
SourceMapV3.Offset = function()
{
    /** @type {number} */ this.line;
    /** @type {number} */ this.column;
}

// FIXME: remove everything below.
var WebInspector = {}

WebInspector.queryParamsObject = {}
WebInspector.toggleSearchingForNode = function() {}
WebInspector.panels = {};

/**
 * @param {Element} element
 * @param {function()=} onclose
 */
WebInspector.showViewInDrawer = function(element, view, onclose) {}

WebInspector.closeViewInDrawer = function() {}

/**
 * @param {string=} messageLevel
 * @param {boolean=} showConsole
 */
WebInspector.log = function(message, messageLevel, showConsole) {}

WebInspector.showErrorMessage = function(error) {}

WebInspector.addMainEventListeners = function(doc) {}

WebInspector.openResource = function(url, external) {}

WebInspector.showConsole = function() {}

/**
 * @param {string} expression
 * @param {boolean=} showResultOnly
 */
WebInspector.evaluateInConsole = function(expression, showResultOnly) {}

WebInspector.queryParamsObject = {}

/**
 * @param {Element} element
 */
WebInspector.showAnchorLocation = function(element) {}

WebInspector.Events = {
    InspectorLoaded: "InspectorLoaded",
    InspectorClosing: "InspectorClosing"
}

/** Extensions API */

/** @constructor */
function AuditCategory() {}
/** @constructor */
function AuditResult() {}
/** @constructor */
function EventSink() {}
/** @constructor */
function ExtensionSidebarPane() {}
/** @constructor */
function Panel() {}
/** @constructor */
function PanelWithSidebar() {}
/** @constructor */
function Request() {}
/** @constructor */
function Resource() {}
/** @constructor */
function Timeline() {}

var extensionServer;

/** @type {string} */
Location.prototype.origin = "";

/**
 * @constructor
 */
function ExtensionDescriptor() {
    this.startPage = "";
    this.name = "";
}

/**
 * @constructor
 */
function ExtensionReloadOptions() {
    this.ignoreCache = false;
    this.injectedScript = "";
    this.userAgent = "";
}

WebInspector.showPanel = function(panel)
{
}

/**
 * @param {ExtensionDescriptor} extensionInfo
 * @return {string}
 */
function buildPlatformExtensionAPI(extensionInfo) {}

/**
 * @type {string}
 */
WebInspector.inspectedPageDomain;

WebInspector.SourceJavaScriptTokenizer = {}
WebInspector.SourceJavaScriptTokenizer.Keywords = {}

var InspectorTest = {}

/* jsdifflib API */
var difflib = {};
difflib.stringAsLines = function(text) { return []; }
/** @constructor */
difflib.SequenceMatcher = function(baseText, newText) { }
difflib.SequenceMatcher.prototype.get_opcodes = function() { return []; }

/** @constructor */
WebInspector.AceTextEditor = function(url, delegate) { }

/** @constructor */
var CodeMirror = function() { }
CodeMirror.on = function(obj, type, handler) { }
CodeMirror.prototype = {
    addKeyMap: function(map) { },
    addLineClass: function(handle, where, cls) { },
    addLineWidget: function(handle, node, options) { },
    /**
     * @param {string|Object} spec
     * @param {Object=} options
     */
    addOverlay: function(spec, options) { },
    addWidget: function(pos, node, scroll, vert, horiz) { },
    charCoords: function(pos, mode) { },
    clearGutter: function(gutterID) { },
    clearHistory: function() { },
    clipPos: function(pos) { },
    coordsChar: function(coords, mode) { },
    cursorCoords: function(start, mode) { },
    defaultCharWidth: function() { },
    defaultTextHeight: function() { },
    deleteH: function(dir, unit) { },
    eachLine: function(from, to, op) { },
    execCommand: function(cmd) { },
    extendSelection: function(from, to) { },
    findMarksAt: function(pos) { },
    findMatchingBracket: function() { },
    findPosH: function(from, amount, unit, visually) { },
    findPosV: function(from, amount, unit, goalColumn) { },
    firstLine: function() { },
    focus: function() { },
    getAllMarks: function() { },
    getCursor: function(start) { },
    getDoc: function() { },
    getGutterElement: function() { },
    getHistory: function() { },
    getInputField: function(){ },
    getLine: function(line) { },
    /**
     * @return {{wrapClass: string}}
     */
    getLineHandle: function(line) { },
    getLineNumber: function(line) { },
    getMode: function() { },
    getOption: function(option) { },
    getRange: function(from, to, lineSep) { },
    getScrollInfo: function() { },
    getScrollerElement: function() { },
    getSelection: function() { },
    getStateAfter: function(line) { },
    getTokenAt: function(pos) { },
    getValue: function(lineSep) { },
    getViewport: function() { },
    getWrapperElement: function() { },
    hasFocus: function() { },
    historySize: function() { },
    indentLine: function(n, dir, aggressive) { },
    indentSelection: function(how) { },
    indexFromPos: function(coords) { },
    isClean: function() { },
    iterLinkedDocs: function(f) { },
    lastLine: function() { },
    lineCount: function() { },
    lineInfo: function(line) { },
    lineAtHeight: function(height) { },
    linkedDoc: function(options) { },
    markClean: function() { },
    markText: function(from, to, options) { },
    moveH: function(dir, unit) { },
    moveV: function(dir, unit) { },
    off: function(type, f) { },
    on: function(type, f) { },
    operation: function(f) { },
    posFromIndex: function(off) { },
    redo: function() { },
    refresh: function() { },
    removeKeyMap: function(map) { },
    removeLine: function(line) { },
    removeLineClass: function(handle, where, cls) { },
    removeLineWidget: function(widget) { },
    removeOverlay: function(spec) { },
    replaceRange: function(code, from, to, origin) { },
    replaceSelection: function(code, collapse, origin) { },
    scrollIntoView: function(pos, margin) { },
    scrollTo: function(x, y) { },
    setBookmark: function(pos, options) { },
    setCursor: function(line, ch, extend) { },
    setExtending: function(val) { },
    setGutterMarker: function(line, gutterID, value) { },
    setHistory: function(histData) { },
    setLine: function(line, text) { },
    setOption: function(option, value) { },
    setSelection: function(anchor, head) { },
    setSize: function(width, height) { },
    setValue: function(code) { },
    somethingSelected: function() { },
    swapDoc: function(doc) { },
    undo: function() { },
    unlinkDoc: function(other) { }
}
/** @type {number} */
CodeMirror.prototype.lineCount;
CodeMirror.Pass;
CodeMirror.showHint = function(codeMirror, hintintFunction) { };
CodeMirror.commands = {};

/** @constructor */
CodeMirror.Pos = function(line, ch) { }
/** type {number} */
CodeMirror.Pos.prototype.line;
/** type {number} */
CodeMirror.Pos.prototype.ch;

/** @constructor */
CodeMirror.StringStream = function() { }
CodeMirror.StringStream.prototype = {
    backUp: function (n) { },
    column: function () { },
    current: function () { },
    eat: function (match) { },
    eatSpace: function () { },
    eatWhile: function (match) { },
    eol: function () { },
    indentation: function () { },
    /**
     * @param {RegExp|string} pattern
     * @param {boolean=} consume
     * @param {boolean=} caseInsensitive
     */
    match: function (pattern, consume, caseInsensitive) { },
    next: function () { },
    peek: function () { },
    skipTo: function (ch) { },
    skipToEnd: function () { },
    sol: function () { }
}

WebInspector.suggestReload = function() { }
WebInspector.reload = function() { }

/** @type {boolean} */
window.dispatchStandaloneTestRunnerMessages;

WebInspector.settings.continuousPainting = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showDebugBorders = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showFPSCounter = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showPaintRects = /** type {WebInspector.Setting} */ { }
WebInspector.settings.showFPSCounter = /** type {WebInspector.Setting} */ { }
<|endoftext|>