<commit_before>var stream = require('stream')
var eos = require('end-of-stream')
var util = require('util')

var SIGNAL_FLUSH = new Buffer([0])

var onuncork = function(self, fn) {
  if (self._corked) self.once('uncork', fn)
  else fn()
}

var destroyer = function(self, end) {
  return function(err) {
    if (err) self.destroy(err.message === 'premature close' ? null : err)
    else if (end && !self._ended) self.end()
  }
}

var end = function(ws, fn) {
  if (!ws) return fn()
  if (ws._writableState) return ws.end(fn)
  ws.end()
  fn()
}

var toStreams2 = function(rs) {
  return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
}

var Duplexify = function(writable, readable, opts) {
  if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  stream.Duplex.call(this, opts)

  this._writable = null
  this._readable = null
  this._readable2 = null

  this._forwardDestroy = !opts || opts.destroy !== false
  this._corked = 1 // start corked
  this._ondrain = null
  this._drained = false
  this._forwarding = false
  this._unwrite = null
  this._unread = null
  this._ended = false

  this.destroyed = false

  if (writable) this.setWritable(writable)
  if (readable) this.setReadable(readable)
}

util.inherits(Duplexify, stream.Duplex)

Duplexify.obj = function(writable, readable, opts) {
  if (!opts) opts = {}
  opts.objectMode = true
  opts.highWaterMark = 16
  return new Duplexify(writable, readable, opts)
}

Duplexify.prototype.cork = function() {
  if (++this._corked === 1) this.emit('cork')
}

Duplexify.prototype.uncork = function() {
  if (this._corked && --this._corked === 0) this.emit('uncork')
}

Duplexify.prototype.setWritable = function(writable) {
  if (this._unwrite) this._unwrite()

  if (this.destroyed) {
    if (writable && writable.destroy) writable.destroy()
    return
  }

  if (writable === null || writable === false) {
    this.end()
    return
  }

  var self = this
  var unend = eos(writable, {writable:true, readable:false}, destroyer(this, true))

  var ondrain = function() {
    var ondrain = self._ondrain
    self._ondrain = null
    if (ondrain) ondrain()
  }

  var clear = function() {
    self._writable.removeListener('drain', ondrain)
    unend()
  }

  if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks

  this._writable = writable
  this._writable.on('drain', ondrain)
  this._unwrite = clear

  this.uncork() // always uncork setWritable
}

Duplexify.prototype.setReadable = function(readable) {
  if (this._unread) this._unread()

  if (this.destroyed) {
    if (readable && readable.destroy) readable.destroy()
    return
  }

  if (readable === null || readable === false) {
    this.push(null)
    return
  }

  var self = this
  var unend = eos(readable, {writable:false, readable:true}, destroyer(this))

  var onreadable = function() {
    self._forward()
  }

  var onend = function() {
    self.push(null)
  }

  var clear = function() {
    self._readable2.removeListener('readable', onreadable)
    self._readable2.removeListener('end', onend)
    unend()
  }

  this._drained = true
  this._readable = readable
  this._readable2 = readable._readableState ? readable : toStreams2(readable)
  this._readable2.on('readable', onreadable)
  this._readable2.on('end', onend)
  this._unread = clear

  this._forward()
}

Duplexify.prototype._read = function() {
  this._drained = true
  this._forward()
}

Duplexify.prototype._forward = function() {
  if (this._forwarding || !this._readable2 || !this._drained) return
  this._forwarding = true

  var data
  while ((data = this._readable2.read()) !== null) {
    this._drained = this.push(data)
  }

  this._forwarding = false
}

Duplexify.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true

  var self = this
  process.nextTick(function() {
    self._destroy(err)
  })
}

Duplexify.prototype._destroy = function(err) {
  if (err) {
    var ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain(err)
    else this.emit('error', err)
  }

  if (this._forwardDestroy) {
    if (this._readable && this._readable.destroy) this._readable.destroy()
    if (this._writable && this._writable.destroy) this._writable.destroy()
  }

  this.emit('close')
}

Duplexify.prototype._write = function(data, enc, cb) {
  if (this.destroyed) return cb()
  if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  if (data === SIGNAL_FLUSH) return this._finish(cb)
  if (!this._writable) return cb()

  if (this._writable.write(data) === false) this._ondrain = cb
  else cb()
}

Duplexify.prototype._finish = function(cb) {
  var self = this
  this.emit('preend')
  onuncork(this, function() {
    end(self._writable, function() {
      self.emit('prefinish')
      onuncork(self, cb)
    })
  })
}

Duplexify.prototype.end = function(data, enc, cb) {
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  this._ended = true
  if (data) this.write(data)
  if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  return stream.Writable.prototype.end.call(this, cb)
}

module.exports = Duplexify<commit_msg>fix ending of finished streams<commit_after>var stream = require('stream')
var eos = require('end-of-stream')
var util = require('util')

var SIGNAL_FLUSH = new Buffer([0])

var onuncork = function(self, fn) {
  if (self._corked) self.once('uncork', fn)
  else fn()
}

var destroyer = function(self, end) {
  return function(err) {
    if (err) self.destroy(err.message === 'premature close' ? null : err)
    else if (end && !self._ended) self.end()
  }
}

var end = function(ws, fn) {
  if (!ws) return fn()
  if (ws._writableState && ws._writableState.finished) return fn()
  if (ws._writableState) return ws.end(fn)
  ws.end()
  fn()
}

var toStreams2 = function(rs) {
  return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
}

var Duplexify = function(writable, readable, opts) {
  if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  stream.Duplex.call(this, opts)

  this._writable = null
  this._readable = null
  this._readable2 = null

  this._forwardDestroy = !opts || opts.destroy !== false
  this._corked = 1 // start corked
  this._ondrain = null
  this._drained = false
  this._forwarding = false
  this._unwrite = null
  this._unread = null
  this._ended = false

  this.destroyed = false

  if (writable) this.setWritable(writable)
  if (readable) this.setReadable(readable)
}

util.inherits(Duplexify, stream.Duplex)

Duplexify.obj = function(writable, readable, opts) {
  if (!opts) opts = {}
  opts.objectMode = true
  opts.highWaterMark = 16
  return new Duplexify(writable, readable, opts)
}

Duplexify.prototype.cork = function() {
  if (++this._corked === 1) this.emit('cork')
}

Duplexify.prototype.uncork = function() {
  if (this._corked && --this._corked === 0) this.emit('uncork')
}

Duplexify.prototype.setWritable = function(writable) {
  if (this._unwrite) this._unwrite()

  if (this.destroyed) {
    if (writable && writable.destroy) writable.destroy()
    return
  }

  if (writable === null || writable === false) {
    this.end()
    return
  }

  var self = this
  var unend = eos(writable, {writable:true, readable:false}, destroyer(this, true))

  var ondrain = function() {
    var ondrain = self._ondrain
    self._ondrain = null
    if (ondrain) ondrain()
  }

  var clear = function() {
    self._writable.removeListener('drain', ondrain)
    unend()
  }

  if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks

  this._writable = writable
  this._writable.on('drain', ondrain)
  this._unwrite = clear

  this.uncork() // always uncork setWritable
}

Duplexify.prototype.setReadable = function(readable) {
  if (this._unread) this._unread()

  if (this.destroyed) {
    if (readable && readable.destroy) readable.destroy()
    return
  }

  if (readable === null || readable === false) {
    this.push(null)
    return
  }

  var self = this
  var unend = eos(readable, {writable:false, readable:true}, destroyer(this))

  var onreadable = function() {
    self._forward()
  }

  var onend = function() {
    self.push(null)
  }

  var clear = function() {
    self._readable2.removeListener('readable', onreadable)
    self._readable2.removeListener('end', onend)
    unend()
  }

  this._drained = true
  this._readable = readable
  this._readable2 = readable._readableState ? readable : toStreams2(readable)
  this._readable2.on('readable', onreadable)
  this._readable2.on('end', onend)
  this._unread = clear

  this._forward()
}

Duplexify.prototype._read = function() {
  this._drained = true
  this._forward()
}

Duplexify.prototype._forward = function() {
  if (this._forwarding || !this._readable2 || !this._drained) return
  this._forwarding = true

  var data
  while ((data = this._readable2.read()) !== null) {
    this._drained = this.push(data)
  }

  this._forwarding = false
}

Duplexify.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true

  var self = this
  process.nextTick(function() {
    self._destroy(err)
  })
}

Duplexify.prototype._destroy = function(err) {
  if (err) {
    var ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain(err)
    else this.emit('error', err)
  }

  if (this._forwardDestroy) {
    if (this._readable && this._readable.destroy) this._readable.destroy()
    if (this._writable && this._writable.destroy) this._writable.destroy()
  }

  this.emit('close')
}

Duplexify.prototype._write = function(data, enc, cb) {
  if (this.destroyed) return cb()
  if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  if (data === SIGNAL_FLUSH) return this._finish(cb)
  if (!this._writable) return cb()

  if (this._writable.write(data) === false) this._ondrain = cb
  else cb()
}

Duplexify.prototype._finish = function(cb) {
  var self = this
  this.emit('preend')
  onuncork(this, function() {
    end(self._writable, function() {
      self.emit('prefinish')
      onuncork(self, cb)
    })
  })
}

Duplexify.prototype.end = function(data, enc, cb) {
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  this._ended = true
  if (data) this.write(data)
  if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  return stream.Writable.prototype.end.call(this, cb)
}

module.exports = Duplexify<|endoftext|>


<commit_before>// Note some browser launchers should be installed before using karma start.
// For example:
// npm install karma-firefox-launcher
// karma start --browsers=Firefox
module.exports = function (config) {
  config.set({

    frameworks: ['mocha', 'chai'],

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
     'Chrome',
     'Firefox',
     'IE',
     'IE9',
      'PhantomJS'
    ],

    // you can define custom flags
    customLaunchers: {
      IE9: {
        base: 'IE',
        'x-ua-compatible': 'IE=EmulateIE9'
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    files: [
      'test/setup/*.js',
      'src/prouter.js',
      'test/*.spec.js'
    ],

    preprocessors: {
      'src/prouter.js': ['coverage']
    },

    coverageReporter: {
      dir: 'build/reports/coverage',
      reporters: [
        // reporters not supporting the `file` property
        {
          type: 'html',
          subdir: 'html'
        }, {
          type: 'lcov',
          subdir: 'lcov'
        }
      ]
    }
  });
};
<commit_msg>Commented out some browsers for passing cloud build (travis).<commit_after>// Note some browser launchers should be installed before using karma start.
// For example:
// npm install karma-firefox-launcher
// karma start --browsers=Firefox
module.exports = function (config) {
  config.set({

    frameworks: ['mocha', 'chai'],

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
//     'Chrome',
//     'Firefox',
//     'IE',
//     'IE9',
      'PhantomJS'
    ],

    // you can define custom flags
    customLaunchers: {
      IE9: {
        base: 'IE',
        'x-ua-compatible': 'IE=EmulateIE9'
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    files: [
      'test/setup/*.js',
      'src/prouter.js',
      'test/*.spec.js'
    ],

    preprocessors: {
      'src/prouter.js': ['coverage']
    },

    coverageReporter: {
      dir: 'build/reports/coverage',
      reporters: [
        // reporters not supporting the `file` property
        {
          type: 'html',
          subdir: 'html'
        }, {
          type: 'lcov',
          subdir: 'lcov'
        }
      ]
    }
  });
};
<|endoftext|>


<commit_before>var debug = require('debug')('oa-graphs')
var inherits = require('inherits');
var Map = require('es6-map');

var Graph = require('oa-graph');

function Graphs (options) {
  debug("constructor", options);
  // call new constructor if not already
  if (!(this instanceof Graphs)) {
    return new Graphs(options);
  }

  // setup graph db
  var level = options.db;
  delete options.db;

  this.db = require('levelgraph-jsonld')(
    require('levelgraph')(level, options)
  , options);

  // call Map constructor on this
  Map.call(this);
}
inherits(Graphs, Map);

Graphs.prototype.use = function (graph) {
  debug("set", graph);

  // if not instanceof Graph, assume it is type
  if (!(graph instanceof Graph)) {
    graph = new Graph({
      db: graph.db || this.db,
      types: graph.types || this.types,
      type: graph.type,
      name: graph.name,
    });
  }

  this.set(graph.name, graph);

  return graph;
};

module.exports = Graphs;
<commit_msg>setup types<commit_after>var debug = require('debug')('oa-graphs')
var inherits = require('inherits');
var Map = require('es6-map');

var Graph = require('oa-graph');

function Graphs (options) {
  debug("constructor", options);
  // call new constructor if not already
  if (!(this instanceof Graphs)) {
    return new Graphs(options);
  }

  // setup graph db
  var level = options.db;
  delete options.db;

  this.db = require('levelgraph-jsonld')(
    require('levelgraph')(level, options)
  , options);

  // setup type registry
  if (options.types) {
    this.types = options.types;
  } else {
    this.types = require('oa-types')();
  }

  // call Map constructor on this
  Map.call(this);
}
inherits(Graphs, Map);

Graphs.prototype.use = function (graph) {
  debug("set", graph);

  // if not instanceof Graph, assume it is type
  if (!(graph instanceof Graph)) {
    graph = new Graph({
      db: graph.db || this.db,
      types: graph.types || this.types,
      type: graph.type,
      name: graph.name,
    });
  }

  this.set(graph.name, graph);

  return graph;
};

module.exports = Graphs;
<|endoftext|>


<commit_before><commit_msg>completes main functionalites;<commit_after>'use strict';

'use strict';

module.exports = version;

var version = exports;

var fs = require('fs');
var node_path = require('path');

function version (cwd, callback) {
  var package_json = node_path.join(cwd, 'package.json');

  fs.readFile(package_json, function(err, content) {
    if (err) {
      return callback(version._error({
        code: 'ERROR_READ_PKG',
        message: 'fails to read "' + package_json + '", err: ' + err.stack,
        data: {
          file: package_json,
          error: err
        }
      }));
    }

    var pkg;

    try {
      pkg = JSON.parse(content.toString());

    } catch (e) {
      return callback(version._error({
        code: 'ERROR_PARSE_JSON',
        message: 'fails to parse package.json, path "' + package_json + '"',
        data: {
          file: package_json,
          error: e
        }
      }));
    }

    callback(null, pkg.version);
  });
};

version._error = function (info) {
  var err = new Error(info.message);
  err.code = info.code;
  err.data = err.data;
  return err;
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Oct 07 2013 10:25:42 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'vendor/*.js',
      'src/*.js',
      'test/*.coffee'
    ],

    // list of files to exclude
    exclude: [
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Firefox','Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>revert to ff<commit_after>// Karma configuration
// Generated on Mon Oct 07 2013 10:25:42 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'vendor/*.js',
      'src/*.js',
      'test/*.coffee'
    ],

    // list of files to exclude
    exclude: [
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)

    // NOTE: Only using Firefox, because Chrome will NOT run on
    // Travis CI which will result in build error
    browsers: ['Firefox'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<|endoftext|>


<commit_before>/**
 * Mongoose Versioner Plugin
 *
 * Adds the ability to version a document.  All document versions are
 * stored in a shadow collection with a shallow clone of the active
 * version's data residing in the original model.
 *
 * The original model is queried as normal when searching for
 * documents.  The shadow collection is only used by your CRUD system
 * through the use of static methods added to the model's schema
 * by this plugin.
 *
 * Property added to the original schema:
 * + versionId {ObjectId} Id of the active version in the shadow collection
 *
 * Instance Methods added to the original schema:
 * + findVersions - returns all versions of this document
 *
 * Static Methods added to the original schema:
 * + findVersionById - returns a document version matching the id
 * + findVersions - returns all document versions matching query
 * + saveVersion - saves a document as a version
 * + deleteVersion - deletes a document version
 * + activateVersion - make a document version the active version
 *
 * Property added to the shadow schema:
 * + versionOfId {ObjectId} Id of the document this version is linked to
 *
 * @param {Schema} schema
 * @param {Object} options
 */
module.exports = function (schema, options) {

  'use strict';

  if (!options || !options.mongoose) {
    console.log('mongoose-versioner requires mongoose to be passed in as an options reference.');
    return;
  }

  var mongoose = options.mongoose
    , Schema = mongoose.Schema
    , modelName = options.modelName
    , fields = {}
    , versionIdPath = options.versionIdPath || 'versionId'
    , shadowFields = {}
    , versionOfIdPath = options.versionOfIdPath || 'versionOfId';

  // Clone the schema to a shadowSchema
  schema.eachPath(function (key, value) {
    if (key !== '_id') {
      shadowFields[key] = value.options;
    }
  });

  // versionOfId holds a reference to the original document being versioned
  if (!shadowFields[versionOfIdPath]) {
    shadowFields[versionOfIdPath] = {type:Schema.ObjectId};
  }

  // versionId holds a reference to the versioned document that is "active"
  if (!schema.paths[versionIdPath]) {
    fields[versionIdPath] = {type:Schema.ObjectId};
  }
  schema.add(fields);

  var shadowSchema = new mongoose.Schema(shadowFields),
    shadowModel = mongoose.model(modelName + 'Shadow', shadowSchema);

  //-------------------------------------------------------------------------
  // Instance Methods
  //

  /**
   * findVersions
   *
   * When you have an instance to a document, calling this instance method
   * will return a list of document versions available for this document.
   *
   * @param callback
   * @return {Query}
   */
  schema.methods.findVersions = function (callback) {
    var filter = {};
    filter[versionOfIdPath] = this._id;
    return shadowModel.find(filter, function (err, result) {
      callback(err, result);
    });
  };

  //-------------------------------------------------------------------------
  // Class Methods
  //

  /**
   * findVersionById
   *
   * Returns a specific document version by Id
   *
   * @param {ObjectId} id   The Id of the document in the shadow schema
   * @param fields
   * @param options
   * @param {Function} callback
   * @return {Query}
   */
  schema.statics.findVersionById = function (id, fields, options, callback) {
    return shadowModel.findById(id, fields, options, callback);
  };

  /**
   * findVersions
   *
   * Returns a collection of document versions that
   * are linked as to the document with the passed in Id.
   *
   * @param {ObjectId} id   The Id of the active document in the original schema
   * @param fields
   * @param options
   * @param {Function} callback
   */
  schema.statics.findVersions = function (id, fields, options, callback) {
    var model = mongoose.model(modelName),
      returnObj = {
        activeId:null,
        docs:[]
      };

    model.findById(id, fields, options, function (err, activeDoc) {
      if (err) {
        callback(err);
      } else if (activeDoc === null) {
        callback(err, returnObj);
      } else {
        returnObj.activeId = activeDoc[versionIdPath];
        var filter = {};
        filter[versionOfIdPath] = activeDoc._id;
        shadowModel.find(filter, fields, options, function (err, result) {
          if (err) {
            callback(err);
          } else {
            returnObj.docs = result;
            callback(err, returnObj);
          }
        });
      }
    });
  };

  /**
   * saveVersion
   *
   * NOTE: This function should be used to save all documents in place of
   * the original schema's save() method.
   *
   * This function will first check to see if the document exists in
   * the original schema and create it there if it does not.
   *
   * Then, using this document reference, also create a version and store
   * it in the shadow collection linking it back to this reference.
   *
   * @param {Object} dataObj    The data to save
   * @param {Function} callback
   */
  schema.statics.saveVersion = function (dataObj, callback) {

    // 1) First look to see if this document exists
    shadowModel.findById(dataObj.versionId, function (err, result) {
      if (err) {
        callback(err);
      } else {
        var versDoc = result;
        if (versDoc === null) {
          // Document doesn't exist so create a new one
          versDoc = new shadowModel(dataObj.data);
        } else {
          // Document does exist so copy data to it
          for (var key in dataObj.data) {
            versDoc[key] = dataObj.data[key];
          }
        }
        versDoc.versionOfId = dataObj.versionOfId || null;
        // 2) Save this as a Version
        versDoc.save(function (err, versSaved) {
          if (err) {
            callback(err);
          } else {
            var versDocObj = versSaved.toObject(),
              model = mongoose.model(modelName);
            // 2) Lookup the Active version
            model.findById(dataObj.versionOfId, function (err, original) {
              if (err) {
                callback(err);
              } else {
                // 3) If the Active version doesn't exist, create a new object
                if (original === null) {
                  original = new model();
                  original[versionIdPath] = versSaved._id;
                }
                // 4) If the Active version is the Version we are editing, then update it
                if (original[versionIdPath].toString() == versSaved._id.toString()) {
                  // 4a) Copy all of the properties from the Version to the Active document
                  var versDocObj = versSaved.toObject();
                  for (var key in versDocObj) {
                    if (key !== '_id' && key !== versionOfIdPath && key !== schema.options.versionKey) {
                      original[key] = versDocObj[key];
                    }
                  }
                  // 4b) Save the Active document with the newly updated props
                  original.save(function (err, originalSaved) {
                    if (err) {
                      callback(err);
                    } else if (versDocObj[versionOfIdPath] !== originalSaved._id) {
                      // 5) If this was a new document save Version again with ref to Active document
                      versSaved[versionOfIdPath] = originalSaved._id;
                      versSaved.save(function (err, versSavedAgain) {
                        callback(err, versSavedAgain);
                      });
                    } else {
                      callback(null, versSaved);
                    }
                  });
                } else {
                  callback(null, versSaved);
                }
              }
            });
          }
        });
      }
    });
  };

  /**
   * deleteVersion
   *
   * This function will delete a document version from the shadow
   * collection provided it isn't linked as the active document.
   *
   * An object will be passed to the callback function with a
   * 'success' property with the value true if it deleted the
   * version and false if it did not.
   *
   * @param {ObjectId} id   The Id of the document version to delete
   * @param {Function} callback
   */
  schema.statics.deleteVersion = function (id, callback) {
    var model = mongoose.model(modelName),
      filter = {};

    // 1) Check to see if this Version is an Active document
    filter[versionIdPath] = id;
    model.findOne(filter, function (err, result) {
      if (err) {
        callback(err);
      } else if (result === null) {
        // 2a) Document not found so it's not Active.  Safe to delete.
        shadowModel.findById(id, function (err, version) {
          if (err) {
            callback(err);
          } else if (version === null) {
            callback(null, {'success':false});
          } else {
            version.remove(function (err, version) {
              if (err) {
                callback(err);
              } else {
                callback(null, {'success':true});
              }
            });
          }
        });
      } else {
        // 2b) Document found so it must be Active and therefore not safe to delete.
        callback(null, {'success':false});
      }
    });
  };

  /**
   * activateVersion
   *
   * This function will set a document version as the active version
   * by cloning it's data to the original collection and updating the
   * active version pointer.
   *
   * @param {ObjectId} id   The Id of the version document to activate
   * @param {Function} callback
   */
  schema.statics.activateVersion = function (id, callback) {
    // 1) First look to see if this document exists
    shadowModel.findById(id, function (err, result) {
      if (err) {
        callback(err);
      } else if (result === null) {
        callback({'success':false});
      } else {
        var model = mongoose.model(modelName);
        // 2) Find the Active document
        model.findById(result[versionOfIdPath], function (err, active) {
          if (err) {
            callback(err);
          } else if (active === null) {
            callback({'success':false});
          } else {
            // 3) Copy all of the properties from the Version to the Active document
            var versDocObj = result.toObject();
            for (var key in versDocObj) {
              if (key !== '_id' && key !== versionOfIdPath && key !== schema.options.versionKey) {
                active[key] = versDocObj[key];
              }
            }
            // 4) Set the version pointer to the Version we are activating
            active[versionIdPath] = id;
            active.save(function (err, activeSaved) {
              callback(err, activeSaved);
            });
          }
        });
      }
    });
  };
};
<commit_msg>added upsertVersion<commit_after>/**
 * Mongoose Versioner Plugin
 *
 * Adds the ability to version a document.  All document versions are
 * stored in a shadow collection with a shallow clone of the active
 * version's data residing in the original model.
 *
 * The original model is queried as normal when searching for
 * documents.  The shadow collection is only used by your CRUD system
 * through the use of static methods added to the model's schema
 * by this plugin.
 *
 * Property added to the original schema:
 * + versionId {ObjectId} Id of the active version in the shadow collection
 *
 * Instance Methods added to the original schema:
 * + findVersions - returns all versions of this document
 *
 * Static Methods added to the original schema:
 * + findVersionById - returns a document version matching the id
 * + findVersions - returns all document versions matching query
 * + saveVersion - saves a document as a version
 * + deleteVersion - deletes a document version
 * + activateVersion - make a document version the active version
 *
 * Property added to the shadow schema:
 * + versionOfId {ObjectId} Id of the document this version is linked to
 *
 * @param {Schema} schema
 * @param {Object} options
 */
module.exports = function (schema, options) {

  'use strict';

  if (!options || !options.mongoose) {
    console.log('mongoose-versioner requires mongoose to be passed in as an options reference.');
    return;
  }

  var mongoose = options.mongoose
    , Schema = mongoose.Schema
    , modelName = options.modelName
    , fields = {}
    , versionIdPath = options.versionIdPath || 'versionId'
    , shadowFields = {}
    , versionOfIdPath = options.versionOfIdPath || 'versionOfId';

  // Clone the schema to a shadowSchema
  schema.eachPath(function (key, value) {
    if (key !== '_id') {
      shadowFields[key] = value.options;
    }
  });

  // versionOfId holds a reference to the original document being versioned
  if (!shadowFields[versionOfIdPath]) {
    shadowFields[versionOfIdPath] = {type:Schema.ObjectId};
  }

  // versionId holds a reference to the versioned document that is "active"
  if (!schema.paths[versionIdPath]) {
    fields[versionIdPath] = {type:Schema.ObjectId};
  }
  schema.add(fields);

  var shadowSchema = new mongoose.Schema(shadowFields),
    shadowModel = mongoose.model(modelName + 'Shadow', shadowSchema);

  //-------------------------------------------------------------------------
  // Instance Methods
  //

  /**
   * findVersions
   *
   * When you have an instance to a document, calling this instance method
   * will return a list of document versions available for this document.
   *
   * @param callback
   * @return {Query}
   */
  schema.methods.findVersions = function (callback) {
    var filter = {};
    filter[versionOfIdPath] = this._id;
    return shadowModel.find(filter, function (err, result) {
      callback(err, result);
    });
  };

  //-------------------------------------------------------------------------
  // Class Methods
  //

  /**
   * findVersionById
   *
   * Returns a specific document version by Id
   *
   * @param {ObjectId} id   The Id of the document in the shadow schema
   * @param fields
   * @param options
   * @param {Function} callback
   * @return {Query}
   */
  schema.statics.findVersionById = function (id, fields, options, callback) {
    return shadowModel.findById(id, fields, options, callback);
  };

  /**
   * findVersions
   *
   * Returns a collection of document versions that
   * are linked as to the document with the passed in Id.
   *
   * @param {ObjectId} id   The Id of the active document in the original schema
   * @param fields
   * @param options
   * @param {Function} callback
   */
  schema.statics.findVersions = function (id, fields, options, callback) {
    var model = mongoose.model(modelName),
      returnObj = {
        activeId:null,
        docs:[]
      };

    model.findById(id, fields, options, function (err, activeDoc) {
      if (err) {
        callback(err);
      } else if (activeDoc === null) {
        callback(err, returnObj);
      } else {
        returnObj.activeId = activeDoc[versionIdPath];
        var filter = {};
        filter[versionOfIdPath] = activeDoc._id;
        shadowModel.find(filter, fields, options, function (err, result) {
          if (err) {
            callback(err);
          } else {
            returnObj.docs = result;
            callback(err, returnObj);
          }
        });
      }
    });
  };

  /**
   * saveVersion
   *
   * NOTE: This function should be used to save all documents in place of
   * the original schema's save() method.
   *
   * This function will first check to see if the document exists in
   * the original schema and create it there if it does not.
   *
   * Then, using this document reference, also create a version and store
   * it in the shadow collection linking it back to this reference.
   *
   * @param {Object} dataObj    The data to save
   * @param {Function} callback
   */
  schema.statics.saveVersion = function (dataObj, callback) {

    // 1) First look to see if this document exists
    shadowModel.findById(dataObj.versionId, function (err, result) {
      if (err) {
        callback(err);
      } else {
        var versDoc = result;
        if (versDoc === null) {
          // Document doesn't exist so create a new one
          versDoc = new shadowModel(dataObj.data);
        } else {
          // Document does exist so copy data to it
          for (var key in dataObj.data) {
            versDoc[key] = dataObj.data[key];
          }
        }
        versDoc.versionOfId = dataObj.versionOfId || null;
        // 2) Save this as a Version
        versDoc.save(function (err, versSaved) {
          if (err) {
            callback(err);
          } else {
            var versDocObj = versSaved.toObject(),
              model = mongoose.model(modelName);
            // 2) Lookup the Active version
            model.findById(dataObj.versionOfId, function (err, original) {
              if (err) {
                callback(err);
              } else {
                // 3) If the Active version doesn't exist, create a new object
                if (original === null) {
                  original = new model();
                  original[versionIdPath] = versSaved._id;
                }
                // 4) If the Active version is the Version we are editing, then update it
                if (original[versionIdPath].toString() == versSaved._id.toString()) {
                  // 4a) Copy all of the properties from the Version to the Active document
                  var versDocObj = versSaved.toObject();
                  for (var key in versDocObj) {
                    if (key !== '_id' && key !== versionOfIdPath && key !== schema.options.versionKey) {
                      original[key] = versDocObj[key];
                    }
                  }
                  // 4b) Save the Active document with the newly updated props
                  original.save(function (err, originalSaved) {
                    if (err) {
                      callback(err);
                    } else if (versDocObj[versionOfIdPath] !== originalSaved._id) {
                      // 5) If this was a new document save Version again with ref to Active document
                      versSaved[versionOfIdPath] = originalSaved._id;
                      versSaved.save(function (err, versSavedAgain) {
                        callback(err, versSavedAgain);
                      });
                    } else {
                      callback(null, versSaved);
                    }
                  });
                } else {
                  callback(null, versSaved);
                }
              }
            });
          }
        });
      }
    });
  };

  /**
   * deleteVersion
   *
   * This function will delete a document version from the shadow
   * collection provided it isn't linked as the active document.
   *
   * An object will be passed to the callback function with a
   * 'success' property with the value true if it deleted the
   * version and false if it did not.
   *
   * @param {ObjectId} id   The Id of the document version to delete
   * @param {Function} callback
   */
  schema.statics.deleteVersion = function (id, callback) {
    var model = mongoose.model(modelName),
      filter = {};

    // 1) Check to see if this Version is an Active document
    filter[versionIdPath] = id;
    model.findOne(filter, function (err, result) {
      if (err) {
        callback(err);
      } else if (result === null) {
        // 2a) Document not found so it's not Active.  Safe to delete.
        shadowModel.findById(id, function (err, version) {
          if (err) {
            callback(err);
          } else if (version === null) {
            callback(null, {'success':false});
          } else {
            version.remove(function (err, version) {
              if (err) {
                callback(err);
              } else {
                callback(null, {'success':true});
              }
            });
          }
        });
      } else {
        // 2b) Document found so it must be Active and therefore not safe to delete.
        callback(null, {'success':false});
      }
    });
  };

  /**
   * activateVersion
   *
   * This function will set a document version as the active version
   * by cloning it's data to the original collection and updating the
   * active version pointer.
   *
   * @param {ObjectId} id   The Id of the version document to activate
   * @param {Function} callback
   */
  schema.statics.activateVersion = function (id, callback) {
    // 1) First look to see if this document exists
    shadowModel.findById(id, function (err, result) {
      if (err) {
        callback(err);
      } else if (result === null) {
        callback({'success':false});
      } else {
        var model = mongoose.model(modelName);
        // 2) Find the Active document
        model.findById(result[versionOfIdPath], function (err, active) {
          if (err) {
            callback(err);
          } else if (active === null) {
            callback({'success':false});
          } else {
            // 3) Copy all of the properties from the Version to the Active document
            var versDocObj = result.toObject();
            for (var key in versDocObj) {
              if (key !== '_id' && key !== versionOfIdPath && key !== schema.options.versionKey) {
                active[key] = versDocObj[key];
              }
            }
            // 4) Set the version pointer to the Version we are activating
            active[versionIdPath] = id;
            active.save(function (err, activeSaved) {
              callback(err, activeSaved);
            });
          }
        });
      }
    });
  };

  /**
   * upsertVersion
   *
   * NOTE: This function should be used to save all documents in place of
   * the original schema's save() method.
   *
   * This function is a lightweight version of saveVersion to be used in
   * append-only situations when the application logic does not cater for
   * modifying not-active i.e. previous versions.
   *
   * If dataObj's _id is null i.e. undefined it creates a new document
   * if _id exists it uses findAndModify to ensure that the active version
   * gets modified. An attempt to modify a not-active version of a document
   * will result in an error.
   * In both cases (save or findAndModify) a new shadow document is created.
   *
   * @param {Object} dataObj    The data to save
   * @param {Function} callback
   */
  schema.statics.upsertVersion = function (dataObj, callback) {
    var model = mongoose.model(modelName);

    function create_shadow(originalObj, callback) {
			var input = {}, versDoc;
			if( originalObj instanceof model ) {
				input = originalObj.toObject();
			} else {
				Object.keys(originalObj).forEach(function(key) {
					if (originalObj.hasOwnProperty(key)) input[key] = originalObj[key];
				});
			}
			delete input._id;
      var versDoc = new shadowModel(input);
			versDoc[versionOfIdPath] = originalObj._id.toString();
			versDoc.save(function(err, versSaved) {
				if( err ) return callback(err.message || err);
				callback(undefined, versSaved);
			});
		}

		if( ! dataObj._id ) {
			// 1) Create a new document
			var original = new model(dataObj);
			// 2) Create a new shadow object
			create_shadow(original, function(err, versSaved) {
				if( err ) return callback(err.message || err);
				// 3) Pass the shadow version to the original document and create it
				original[versionIdPath] = versSaved._id.toString();
				original.save(function(err, origSaved) {
					if( err ) {
						versSaved.remove();
						return callback(err.message || err);
					}
					callback(origSaved);
				});
			});
		} else {
			// Updating an existing document
			if( ! dataObj[versionIdPath] ) return callback('Please specify the revision you would like to change.');
			// 1) Create a new shadow object
			create_shadow(dataObj, function(err, versSaved) {
				if( err ) return callback(err.message || err);
				var query = { _id: dataObj._id.toString() };
				query[versionIdPath] = dataObj[versionIdPath];
				dataObj[versionIdPath] = versSaved._id.toString();
				// 2) Update the original object (if the provided revision match the actual revision)
				model.findOneAndUpdate(query, dataObj, function(err, origSaved) {
					if( err ) {
						versSaved.remove();
						return callback(err.message || err);
					}
					if( ! origSaved ) {
						versSaved.remove();
						return callback('Your copy of the data set with revision ' + query[versionIdPath] + ' is not up-to-date, please refresh first, then try again.');
					}
					callback(undefined, origSaved);
				});
			});
		}
	};
};
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash'),
      request = require('request'),
      urljoin = require('url-join'),
      clientName = 'kugelblitz-client:';

class Client {
  constructor(options) {
    const _defaultOptions = {
      endpoint: null,
      token: null,
      intervalInSeconds: 5 * 60,
      requestTimeoutInSeconds: 1 * 60,
      production: process.env.NODE_ENV === 'production',
      debug: false
    };

    const mergedOptions = _.extend(
      _.clone(_defaultOptions),
      _.clone(options)
    );

    this.endpoint = mergedOptions.endpoint;
    this.intervalInSeconds = mergedOptions.intervalInSeconds;
    this.requestTimeoutInSeconds = mergedOptions.requestTimeoutInSeconds;
    this.token = mergedOptions.token;
    this.production = mergedOptions.production;
    this.debug = mergedOptions.debug;

    if(!this.endpoint) {
      throw new Error('An endpoint must be provided!');
    }

    if(!this.token) {
      throw new Error('A token must be provided!');
    }

    if(this.intervalInSeconds <= this.requestTimeoutInSeconds) {
      throw new Error(`The interval (${this.intervalInSeconds}s) must be greater than the request timeout (${this.requestTimeoutInSeconds}s)`);
    }

    if(!this.production) {
      console.log(clientName, 'The production option is set to false. No API calls will be made');
    }

    if(this.debug) {
      console.log(clientName, 'Debug mode is active');
    }

    this._sendHeartbeat();

    setInterval(() => {
        this._sendHeartbeat();
      }.bind(this),
      this.intervalInSeconds * 1000
    );
  }

  _sendHeartbeat() {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/heartbeat'),
      method: 'POST',
      json: true,
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-KUGELBITZ-TOKEN': this.token
      }
    };

    if(!this.production) {
      return;
    }

    request(options, (error, response, body) => {
      if(this.debug) {
        if(error || response.statusCode !== 200) {
          return console.error(clientName, 'Failed to send kugelblitz heartbeat:', error);
        }

        console.log(clientName, 'heartbeat sent!');
      }
    });
  }

  _sendReport(type, payload, cb) {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/report'),
      method: 'POST',
      json: true,
      body: { type: type, payload: JSON.stringify(payload) },
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-KUGELBLITZ-TOKEN': this.token
      }
    };

    request(options, (error, response, body) => {
      if(error || response.statusCode !== 201) {
        return cb(error || new Error(`Failed to send heartbeat. Server sent a HTTP ${response.statusCode}`));
      }

      return cb(null);
    });
  }

  reportError(error, cb) {
    return this._sendReport(
      'error',
      {
        message: error.message,
        stack: error.stack ? error.stack : null
      }, cb
    );
  }

}

module.exports = Client
<commit_msg>Fixed auth header<commit_after>'use strict'

const _ = require('lodash'),
      request = require('request'),
      urljoin = require('url-join'),
      clientName = 'kugelblitz-client:';

class Client {
  constructor(options) {
    const _defaultOptions = {
      endpoint: null,
      token: null,
      intervalInSeconds: 5 * 60,
      requestTimeoutInSeconds: 1 * 60,
      production: process.env.NODE_ENV === 'production',
      debug: false
    };

    const mergedOptions = _.extend(
      _.clone(_defaultOptions),
      _.clone(options)
    );

    this.endpoint = mergedOptions.endpoint;
    this.intervalInSeconds = mergedOptions.intervalInSeconds;
    this.requestTimeoutInSeconds = mergedOptions.requestTimeoutInSeconds;
    this.token = mergedOptions.token;
    this.production = mergedOptions.production;
    this.debug = mergedOptions.debug;

    if(!this.endpoint) {
      throw new Error('An endpoint must be provided!');
    }

    if(!this.token) {
      throw new Error('A token must be provided!');
    }

    if(this.intervalInSeconds <= this.requestTimeoutInSeconds) {
      throw new Error(`The interval (${this.intervalInSeconds}s) must be greater than the request timeout (${this.requestTimeoutInSeconds}s)`);
    }

    if(!this.production) {
      console.log(clientName, 'The production option is set to false. No API calls will be made');
    }

    if(this.debug) {
      console.log(clientName, 'Debug mode is active');
    }

    this._sendHeartbeat();

    setInterval(() => {
        this._sendHeartbeat();
      }.bind(this),
      this.intervalInSeconds * 1000
    );
  }

  _sendHeartbeat() {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/heartbeat'),
      method: 'POST',
      json: true,
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-KUGELBLITZ-TOKEN': this.token
      }
    };

    if(!this.production) {
      return;
    }

    request(options, (error, response, body) => {
      if(this.debug) {
        if(error || response.statusCode !== 200) {
          return console.error(clientName, 'Failed to send kugelblitz heartbeat:', error, response.statusCode);
        }

        console.log(clientName, 'heartbeat sent!');
      }
    });
  }

  _sendReport(type, payload, cb) {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/report'),
      method: 'POST',
      json: true,
      body: { type: type, payload: JSON.stringify(payload) },
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-KUGELBLITZ-TOKEN': this.token
      }
    };

    request(options, (error, response, body) => {
      if(error || response.statusCode !== 201) {
        return cb(error || new Error(`Failed to send heartbeat. Server sent a HTTP ${response.statusCode}`));
      }

      return cb(null);
    });
  }

  reportError(error, cb) {
    return this._sendReport(
      'error',
      {
        message: error.message,
        stack: error.stack ? error.stack : null
      }, cb
    );
  }

}

module.exports = Client
<|endoftext|>


<commit_before>module.exports = function(config) {
    var webdriverConfig = {
        hostname: 'fe.nhnent.com',
        port: 4444,
        remoteHost: true
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        // karma runner 의 웹 서버 root를 변경할 수 있음
        basePath: './',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        /*
         karma runner 의 웹 서버에 포함될 파일들을 적어주세요.

         included: false 가 아닌 항목은 전부 자동으로 테스트 페이지에 include 됩니다.

         테스트 코드 파일들은 전부 포함되어야 합니다.
         files: [
            'lib/jquery/jquery.js', // JS 추가
            'src/css/test.css',     // CSS 추가
            { pattern: 'test/app/model/*.test.js', included: false }    // 웹서버에 포함은 하지만 테스트 페이지에 include안함
            { pattern: 'test/fixtures/*.html', included: false }        // 웹서버에 올라가지만 jasmine.loadFixture 로 쓸것이므로 include안함.
         ]
         */
        files: [
            'bower_components/jquery/jquery.js',
            'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
            'src/common/common.js',
            'src/js/tree.js',
            'src/**/treemodel.js',
            'test/*Test.js',
            {
                pattern: 'test/fixture/**/*.html',
                included: false
            }
        ],

        /*
         무시할 파일들

         특정 테스트를 제외하고 수행할 때 유용합니다.
         */
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/js/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: [
            'IE7',
            'IE8',
            'IE9',
            'IE10',
            'IE11',
            'Chrome-WebDriver',
            'Firefox-WebDriver'
        ],

        /*
         사용가능한 테스트 브라우저 목록

         추가를 원하시면 말씀주세요
         */
        customLaunchers: {
            'IE7': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE7'
            },
            'IE8': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE8'
            },
            'IE9': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE9'
            },
            'IE10': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE10'
            },
            'IE11': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE11'
            },
            'Chrome-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'chrome'
            },
            'Firefox-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'firefox'
            }
        },

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
};
<commit_msg>karma update<commit_after>module.exports = function(config) {
    var webdriverConfig = {
        hostname: 'fe.nhnent.com',
        port: 4444,
        remoteHost: true
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        // karma runner 의 웹 서버 root를 변경할 수 있음
        basePath: './',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        reporters: [
            'dots',
            'coverage',
            'junit'
        ],
        /*
         karma runner 의 웹 서버에 포함될 파일들을 적어주세요.

         included: false 가 아닌 항목은 전부 자동으로 테스트 페이지에 include 됩니다.

         테스트 코드 파일들은 전부 포함되어야 합니다.
         files: [
            'lib/jquery/jquery.js', // JS 추가
            'src/css/test.css',     // CSS 추가
            { pattern: 'test/app/model/*.test.js', included: false }    // 웹서버에 포함은 하지만 테스트 페이지에 include안함
            { pattern: 'test/fixtures/*.html', included: false }        // 웹서버에 올라가지만 jasmine.loadFixture 로 쓸것이므로 include안함.
         ]
         */
        files: [
            'bower_components/jquery/jquery.js',
            'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
            'src/common/common.js',
            'src/js/tree.js',
            'src/**/treemodel.js',
            'test/*Test.js',
            {
                pattern: 'test/fixture/**/*.html',
                included: false
            }
        ],

        /*
         무시할 파일들

         특정 테스트를 제외하고 수행할 때 유용합니다.
         */
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/js/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        coverageReporter: {
            dir : 'report/coverage/',
            reporters: [
                {
                    type: 'html',
                    subdir: function(browser) {
                        return 'report-html/' + browser;
                    }
                },
                {
                    type: 'cobertura',
                    subdir: function(browser) {
                        return 'report-cobertura/' + browser;
                    },
                    file: 'cobertura.txt'
                }
            ]
        },

        junitReporter: {
            outputFile: 'report/junit-result.xml',
            suite: ''
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: [
            'IE7',
            'IE8',
            'IE9',
            'IE10',
            'IE11',
            'Chrome-WebDriver',
            'Firefox-WebDriver'
        ],

        /*
         사용가능한 테스트 브라우저 목록

         추가를 원하시면 말씀주세요
         */
        customLaunchers: {
            'IE7': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE7'
            },
            'IE8': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE8'
            },
            'IE9': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE9'
            },
            'IE10': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE10'
            },
            'IE11': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'IE11'
            },
            'Chrome-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'chrome'
            },
            'Firefox-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'firefox'
            }
        },

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
};
<|endoftext|>


<commit_before>function spice(arr, slice) {
  var isString = false;
  if (typeof arr === 'string') {
    arr = arr.split('');
    isString = true;
  }

  var spice = arr.slice(0);
  slice = slice.split(':');

  if (slice.length === 2) { // Standard slice
    if (slice[0] && slice[1]) {
      spice = arr.slice(slice[0], slice[1]);
    } else if (!slice[0] && slice[1]) {
      spice = arr.slice(0, slice[1]);
    } else if (!slice[1] && slice[0]) {
      spice = arr.slice(slice[0]);
    }
  } else if (slice.length === 3) { // Extended slice

  }

  if (isString) {
    spice = spice.join('');
  }

  return spice;
}

module.exports = spice;
<commit_msg>Some beginning extended slices<commit_after>function isInteger(str) {
  var n = ~~Number(str);
  return String(n) === str;
}

function spice(arr, slice) {
  var isString = false;
  if (typeof arr === 'string') {
    arr = arr.split('');
    isString = true;
  }

  var spiced = arr.slice(0);
  slice = slice.split(':');

  // Check to make sure slice indices are integers
  for (var i = 0; i < slice.length; i++) {
    if (slice[i] !== '' && !isInteger(slice[i])) {
      console.log(slice[i])
      throw 'slice indices must be integers or blank';
    }
  }

  if (slice.length === 2) { // Standard slice
    if (slice[0] && slice[1]) {
      spiced = arr.slice(slice[0], slice[1]);
    } else if (!slice[0] && slice[1]) {
      spiced = arr.slice(0, slice[1]);
    } else if (!slice[1] && slice[0]) {
      spiced = arr.slice(slice[0]);
    }
  } else if (slice.length === 3) { // Extended slice
    sliced = spice(arr, slice[0] + ':' + slice[1]);
    var step = slice[2];
    if (step === 0) {
      throw 'slice step cannot be zero'
    } else if (step > 0) {
    } else {
    }
  }

  if (isString) {
    spiced = spiced.join('');
  }

  return spiced;
}

module.exports = spice;
<|endoftext|>


<commit_before>'use strict';
// Karma configuration
// Generated on Tue Sep 30 2014 10:36:32 GMT+0300 (IDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/jquery/dist/jquery.min.js',
      'bower_components/angular/angular.min.js',
      'bower_components/angular-mocks/angular-mocks.js',
      '**/src/**/*Spec.coffee',
    ],

    webpack: {
  		cache: true,
  		module: {
  			loaders: [
          { test: /\.jade$/, loader: "jade" },
  				{ test: /\.coffee$/, loader: "coffee-loader" }
  			]
  		}
  	},

  	webpackServer: {
  		stats: {
  			colors: true
  		}
  	},

    webpackPort: 1234,

    plugins: [
        require("karma-jasmine"),
        require("karma-webpack"),
        require("karma-chrome-launcher")
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor

    preprocessors: {
      '**/*.coffee': ['coffee'],
      '**/*.jade': ['jade'],
      '**/src/**/*Spec.coffee': ['webpack']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>chore: replace Karma launcher chrome -> phantomjs<commit_after>'use strict';
// Karma configuration
// Generated on Tue Sep 30 2014 10:36:32 GMT+0300 (IDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/jquery/dist/jquery.min.js',
      'bower_components/angular/angular.min.js',
      'bower_components/angular-mocks/angular-mocks.js',
      '**/src/**/*Spec.coffee',
    ],

    webpack: {
  		cache: true,
  		module: {
  			loaders: [
          { test: /\.jade$/, loader: "jade" },
  				{ test: /\.coffee$/, loader: "coffee-loader" }
  			]
  		}
  	},

  	webpackServer: {
  		stats: {
  			colors: true
  		}
  	},

    webpackPort: 1234,

    plugins: [
        require("karma-jasmine"),
        require("karma-webpack"),
        require("karma-phantomjs-launcher")
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor

    preprocessors: {
      '**/*.coffee': ['coffee'],
      '**/*.jade': ['jade'],
      '**/src/**/*Spec.coffee': ['webpack']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>(function() {
  'use strict';
  var TRELLO_KEY = process.env.TRELLO_KEY;
  var TRELLO_TOKEN = process.env.TRELLO_TOKEN;
  var BOARD = process.env.BOARD_ID;
  var TEMPLATE_LIST = process.env.TEMPLATE_LIST_ID;
  var DESTINATION_LIST = process.env.DESTINATION_LIST_ID;
  var MEMBER_IDS = process.env.MEMBER_IDS;
  var SCHEDULE = process.env.SCHEDULE;

  var Promise = require('bluebird');
  var Trello = require('node-trello');
  var moment = require('moment-timezone');
  var t = Promise.promisifyAll(new Trello(TRELLO_KEY, TRELLO_TOKEN));

  var today = moment().utc().tz('America/Los_Angeles').startOf('day');

  SCHEDULE.split(';').forEach(function(e, idx) {
    var entry = e.split(':');
    var day = +entry[0];
    var cardId = entry[1];
    console.log("Considering " + entry + "...");
    var targetDay = (today.day() + 3) % 7;
    if (day === targetDay) {
      console.log("   matched!");
    } else {
      console.log("   didn't match, continuing.");
      return;
    }

    var trelloParams = {
      pos: 'top',
      due: moment(today).add(73, 'hours'),
      idList: DESTINATION_LIST,
      idMembers: MEMBER_IDS,
      idCardSource: cardId
    };
    t.postAsync("/1/cards", trelloParams)
      .then(function(data) {
        console.log("Successfully cloned " + cardId + " to " + data.url);
      });
  });
})();
<commit_msg>Remove unused declarations<commit_after>(function() {
  'use strict';
  var TRELLO_KEY = process.env.TRELLO_KEY;
  var TRELLO_TOKEN = process.env.TRELLO_TOKEN;
  var DESTINATION_LIST = process.env.DESTINATION_LIST_ID;
  var MEMBER_IDS = process.env.MEMBER_IDS;
  var SCHEDULE = process.env.SCHEDULE;

  var Promise = require('bluebird');
  var Trello = require('node-trello');
  var moment = require('moment-timezone');
  var t = Promise.promisifyAll(new Trello(TRELLO_KEY, TRELLO_TOKEN));

  var today = moment().utc().tz('America/Los_Angeles').startOf('day');

  SCHEDULE.split(';').forEach(function(e) {
    var entry = e.split(':');
    var day = +entry[0];
    var cardId = entry[1];
    console.log("Considering " + entry + "...");
    var targetDay = (today.day() + 3) % 7;
    if (day === targetDay) {
      console.log("   matched!");
    } else {
      console.log("   didn't match, continuing.");
      return;
    }

    var trelloParams = {
      pos: 'top',
      due: moment(today).add(73, 'hours'),
      idList: DESTINATION_LIST,
      idMembers: MEMBER_IDS,
      idCardSource: cardId
    };
    t.postAsync("/1/cards", trelloParams)
      .then(function(data) {
        console.log("Successfully cloned " + cardId + " to " + data.url);
      });
  });
})();
<|endoftext|>


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

var through = require('through2');
var Readable = require('readable-stream').Readable;

var concat = require('concat-stream');
var duplexer = require('duplexer2');
var falafel = require('falafel');
var unparse = require('escodegen').generate;
var inspect = require('object-inspect');
var evaluate = require('static-eval');
var copy = require('shallow-copy');

module.exports = function parse (modules, opts) {
    if (!opts) opts = {};
    var vars = opts.vars || {};
    var varNames = opts.varNames || {};
    var seen = opts.seen || {};
    var seenOffset = opts.seenOffset || 0;
    var pending = 0;
    var updates = [];

    function pushUpdate (node, s) {
        var rep = String(s);
        var prev = node.range[1] - node.range[0];
        updates.push({ offset: prev - rep.length });
        node.update(rep);
    }

    var output = through();
    return duplexer(concat(function (body) {
        try { var src = falafel(body.toString('utf8'), walk) }
        catch (err) { return error(err) }
        if (pending === 0) finish(src);
    }), output);

    function finish (src) {
        var offset = 0, pos = 0;
        src = String(src);

        (function next () {
            if (updates.length === 0) return done();

            var s = updates.shift();
            if (!s.stream) {
                offset += s.offset;
                return next();
            }

            output.push(src.slice(pos, s.range[0] - offset));
            pos = s.range[0] - offset;
            offset += s.range[1] - s.range[0];

            s.stream.on('end', next);
            s.stream.pipe(output, { end: false });
        })();

        function done () {
            output.push(src.slice(pos));
            output.push(null);
        }
    }

    function error (msg) {
        var err = typeof msg === 'string' ? new Error(msg) : msg;
        output.emit('error', err);
    }

    function walk (node) {
        var isreq = false, reqid;
        if (isRequire(node)) {
            reqid = node.arguments[0].value;
            isreq = has(modules, reqid);
        }

        if (isreq && node.parent.type === 'VariableDeclarator'
        && node.parent.id.type === 'Identifier') {
            varNames[node.parent.id.name] = reqid;
            var decs = node.parent.parent.declarations;
            var ix = decs.indexOf(node.parent);
            var dec;
            if (ix >= 0) {
                decs.splice(ix, 1);
            }

            var rep;
            if (decs.length === 0) {
                rep = '';
            }
            else {
                var src = unparse(node.parent.parent);
                updates.push({
                    range: [ 0, src.length ],
                    stream: st('var ')
                });
                decs.forEach(function (d, i) {
                    var s = parse(modules, {
                        seen: seen,
                        seenOffset: seenOffset + d.range[0],
                        vars: vars,
                        varNames: varNames
                    });
                    updates.push({
                        range: [
                            d.range[0],
                            d.range[1] + 1
                        ],
                        stream: s
                    });
                    s.end(unparse(d));
                });
                rep = '';
            }
            pushUpdate(node.parent.parent, rep);
        }
        else if (isreq && node.parent.type === 'AssignmentExpression'
        && node.parent.left.type === 'Identifier') {
            varNames[node.parent.left.name] = reqid;
            var cur = node.parent.parent;
            if (cur.type === 'SequenceExpression') {
                var ex = cur.expressions;
                var ix = ex.indexOf(node.parent);
                if (ix >= 0) ex.splice(ix, 1);
                pushUpdate(
                    node.parent.parent,
                    unparse(node.parent.parent)
                );
            }
            else pushUpdate(cur, '');
        }
        else if (isreq && node.parent.type === 'MemberExpression'
        && node.parent.property.type === 'Identifier'
        && node.parent.parent.type === 'VariableDeclarator'
        && node.parent.parent.id.type === 'Identifier') {
            varNames[node.parent.parent.id.name] = [
                reqid, node.parent.property.name
            ];
            var decs = node.parent.parent.parent.declarations;
            var ix = decs.indexOf(node.parent.parent);
            if (ix >= 0) decs.splice(ix, 1);

            if (decs.length === 0) {
                pushUpdate(node.parent.parent.parent, '');
            }
            else {
                pushUpdate(
                    node.parent.parent.parent,
                    unparse(node.parent.parent.parent)
                );
            }
        }
        else if (isreq && node.parent.type === 'MemberExpression'
        && node.parent.property.type === 'Identifier') {
            var name = node.parent.property.name;
            var cur = copy(node.parent.parent);
            cur.callee = copy(node.parent.property);
            cur.callee.parent = cur;
            traverse(cur.callee, modules[reqid][name]);
        }
        else if (isreq && node.parent.type === 'CallExpression') {
            var cur = copy(node.parent);
            var iname = Math.pow(16,8) * Math.random();
            cur.callee = {
                type: 'Identifier',
                name: '_' + Math.floor(iname).toString(16),
                parent: cur
            };
            traverse(cur.callee, modules[reqid]);
        }

        if (node.type === 'Identifier' && has(varNames, node.name)) {
            var vn = varNames[node.name];
            if (Array.isArray(vn)) {
                traverse(node, modules[vn[0]][vn[1]]);
            }
            else traverse(node, modules[vn]);
        }
    }

    function traverse (node, val) {
        var key = (node.range[0] + seenOffset)
            + ',' + (node.range[1] + seenOffset)
        ;

        if (node.parent.type === 'CallExpression') {
            if (typeof val !== 'function') {
                return error(
                    'tried to statically call ' + inspect(val)
                    + ' as a function'
                );
            }
            var xvars = copy(vars);
            xvars[node.name] = val;
            var res = evaluate(node.parent, xvars);

            if (isStream(res)) {
                if (seen[key]) return;
                seen[key] = true;
                updates.push({
                    range: node.parent.range,
                    stream: wrapStream(res)
                });
                pushUpdate(node.parent, '');
            }
            else if (res !== undefined) pushUpdate(node.parent, res);
        }
        else if (node.parent.type === 'MemberExpression') {
            if (node.parent.property.type !== 'Identifier') {
                return error(
                    'dynamic property in member expression: '
                    + node.parent.source()
                );
            }

            var cur = node.parent.parent;

            if (cur.type === 'MemberExpression') {
                cur = cur.parent;
                if (cur.type !== 'CallExpression'
                && cur.parent.type === 'CallExpression') {
                    cur = cur.parent;
                }
            }
            if (node.parent.type === 'MemberExpression'
            && (cur.type !== 'CallExpression'
            && cur.type !== 'MemberExpression')) {
                cur = node.parent;
            }

            var xvars = copy(vars);
            xvars[node.name] = val;

            var res = evaluate(cur, xvars);
            if (isStream(res)) {
                if (!seen[key]) {
                    updates.push({
                        range: cur.range,
                        stream: wrapStream(res)
                    });
                }
                seen[key] = true;
                cur.update('');
            }
            else if (res !== undefined) {
                pushUpdate(cur, res);
            }
        }
        else {
            output.emit('error', new Error(
                'unsupported type for static module: ' + node.parent.type
                + '\nat expression:\n\n  ' + unparse(node.parent) + '\n'
            ));
        }
    }
}

function isRequire (node) {
    var c = node.callee;
    return c
        && node.type === 'CallExpression'
        && c.type === 'Identifier'
        && c.name === 'require'
    ;
}

function has (obj, key) {
    return {}.hasOwnProperty.call(obj, key);
}

function isStream (s) {
    return s && typeof s === 'object' && typeof s.pipe === 'function';
}

function wrapStream (s) {
    if (typeof s.read === 'function') return s
    else return (new Readable).wrap(s)
}

function st (msg) {
    var r = new Readable;
    r._read = function () {};
    r.push(msg);
    r.push(null);
    return r;
}
<commit_msg>passing the vars test, not passing many or brfs<commit_after>var fs = require('fs');
var path = require('path');

var through = require('through2');
var Readable = require('readable-stream').Readable;

var concat = require('concat-stream');
var duplexer = require('duplexer2');
var falafel = require('falafel');
var unparse = require('escodegen').generate;
var inspect = require('object-inspect');
var evaluate = require('static-eval');
var copy = require('shallow-copy');

module.exports = function parse (modules, opts) {
    if (!opts) opts = {};
    var vars = opts.vars || {};
    var varNames = opts.varNames || {};
    var skip = opts.skip || {};
    var skipOffset = opts.skipOffset || 0;
    var pending = 0;
    var updates = [];

    function pushUpdate (node, s) {
        var rep = String(s);
        var prev = node.range[1] - node.range[0];
        updates.push({ offset: prev - rep.length });
        node.update(rep);
    }

    var output = through();
    return duplexer(concat(function (body) {
        try { var src = falafel(body.toString('utf8'), walk) }
        catch (err) { return error(err) }
        if (pending === 0) finish(src);
    }), output);

    function finish (src) {
        var offset = 0, pos = 0;
        src = String(src);

        (function next () {
            if (updates.length === 0) return done();

            var s = updates.shift();
            if (!s.stream) {
                offset += s.offset;
                return next();
            }

            output.push(src.slice(pos, s.range[0] - offset));
            pos = s.range[0] - offset;
            offset += s.range[1] - s.range[0];

            s.stream.on('end', next);
            s.stream.pipe(output, { end: false });
        })();

        function done () {
            output.push(src.slice(pos));
            output.push(null);
        }
    }

    function error (msg) {
        var err = typeof msg === 'string' ? new Error(msg) : msg;
        output.emit('error', err);
    }

    function walk (node) {
        var isreq = false, reqid;
        if (isRequire(node)) {
            reqid = node.arguments[0].value;
            isreq = has(modules, reqid);
        }

        if (isreq && node.parent.type === 'VariableDeclarator'
        && node.parent.id.type === 'Identifier') {
            varNames[node.parent.id.name] = reqid;
            var decs = node.parent.parent.declarations;
            var ix = decs.indexOf(node.parent);
            var dec;
            if (ix >= 0) {
                decs.splice(ix, 1);
            }

            var rep;
            if (decs.length === 0) {
                rep = '';
            }
            else {
                var src = unparse(node.parent.parent);
                updates.push({
                    range: [ 0, src.length ],
                    stream: st('var ')
                });
                decs.forEach(function (d, i) {
                    var key = (d.range[0] + node.range[0] + skipOffset)
                        + ',' + (d.range[0] + node.range[0] + 2 + skipOffset)
                    ;
                    skip[key] = true;

                    var s = parse(modules, {
                        skip: skip,
                        skipOffset: skipOffset + d.range[0],
                        vars: vars,
                        varNames: varNames
                    });
                    updates.push({
                        range: [
                            d.range[0],
                            d.range[1] + 1
                        ],
                        stream: s
                    });
                    if (i < decs.length - 1) {
                        updates.push({
                            range: [
                                d.range[1], d.range[1] + 2
                            ],
                            stream: st(', ')
                        });
                    }
                    s.end(unparse(d));
                });
                rep = '';
            }
            pushUpdate(node.parent.parent, rep);
        }
        else if (isreq && node.parent.type === 'AssignmentExpression'
        && node.parent.left.type === 'Identifier') {
            varNames[node.parent.left.name] = reqid;
            var cur = node.parent.parent;
            if (cur.type === 'SequenceExpression') {
                var ex = cur.expressions;
                var ix = ex.indexOf(node.parent);
                if (ix >= 0) ex.splice(ix, 1);
                pushUpdate(
                    node.parent.parent,
                    unparse(node.parent.parent)
                );
            }
            else pushUpdate(cur, '');
        }
        else if (isreq && node.parent.type === 'MemberExpression'
        && node.parent.property.type === 'Identifier'
        && node.parent.parent.type === 'VariableDeclarator'
        && node.parent.parent.id.type === 'Identifier') {
            varNames[node.parent.parent.id.name] = [
                reqid, node.parent.property.name
            ];
            var decs = node.parent.parent.parent.declarations;
            var ix = decs.indexOf(node.parent.parent);
            if (ix >= 0) decs.splice(ix, 1);

            if (decs.length === 0) {
                pushUpdate(node.parent.parent.parent, '');
            }
            else {
                pushUpdate(
                    node.parent.parent.parent,
                    unparse(node.parent.parent.parent)
                );
            }
        }
        else if (isreq && node.parent.type === 'MemberExpression'
        && node.parent.property.type === 'Identifier') {
            var name = node.parent.property.name;
            var cur = copy(node.parent.parent);
            cur.callee = copy(node.parent.property);
            cur.callee.parent = cur;
            traverse(cur.callee, modules[reqid][name]);
        }
        else if (isreq && node.parent.type === 'CallExpression') {
            var cur = copy(node.parent);
            var iname = Math.pow(16,8) * Math.random();
            cur.callee = {
                type: 'Identifier',
                name: '_' + Math.floor(iname).toString(16),
                parent: cur
            };
            traverse(cur.callee, modules[reqid]);
        }

        if (node.type === 'Identifier' && has(varNames, node.name)) {
            var vn = varNames[node.name];
            if (Array.isArray(vn)) {
                traverse(node, modules[vn[0]][vn[1]]);
            }
            else traverse(node, modules[vn]);
        }
    }

    function traverse (node, val) {
        var key = (node.range[0] + skipOffset)
            + ',' + (node.range[1] + skipOffset)
        ;
console.log(key, skip[key]);
        if (skip[key]) {
            skip[key] = false;
            return;
        }

        if (node.parent.type === 'CallExpression') {
            if (typeof val !== 'function') {
                return error(
                    'tried to statically call ' + inspect(val)
                    + ' as a function'
                );
            }
            var xvars = copy(vars);
            xvars[node.name] = val;
            var res = evaluate(node.parent, xvars);

            if (isStream(res)) {
                updates.push({
                    range: node.parent.range,
                    stream: wrapStream(res)
                });
                pushUpdate(node.parent, '');
            }
            else if (res !== undefined) pushUpdate(node.parent, res);
        }
        else if (node.parent.type === 'MemberExpression') {
            if (node.parent.property.type !== 'Identifier') {
                return error(
                    'dynamic property in member expression: '
                    + node.parent.source()
                );
            }

            var cur = node.parent.parent;

            if (cur.type === 'MemberExpression') {
                cur = cur.parent;
                if (cur.type !== 'CallExpression'
                && cur.parent.type === 'CallExpression') {
                    cur = cur.parent;
                }
            }
            if (node.parent.type === 'MemberExpression'
            && (cur.type !== 'CallExpression'
            && cur.type !== 'MemberExpression')) {
                cur = node.parent;
            }

            var xvars = copy(vars);
            xvars[node.name] = val;

            var res = evaluate(cur, xvars);
            if (isStream(res)) {
                updates.push({
                    range: cur.range,
                    stream: wrapStream(res)
                });
                cur.update('');
            }
            else if (res !== undefined) {
                pushUpdate(cur, res);
            }
        }
        else {
            output.emit('error', new Error(
                'unsupported type for static module: ' + node.parent.type
                + '\nat expression:\n\n  ' + unparse(node.parent) + '\n'
            ));
        }
    }
}

function isRequire (node) {
    var c = node.callee;
    return c
        && node.type === 'CallExpression'
        && c.type === 'Identifier'
        && c.name === 'require'
    ;
}

function has (obj, key) {
    return {}.hasOwnProperty.call(obj, key);
}

function isStream (s) {
    return s && typeof s === 'object' && typeof s.pipe === 'function';
}

function wrapStream (s) {
    if (typeof s.read === 'function') return s
    else return (new Readable).wrap(s)
}

function st (msg) {
    var r = new Readable;
    r._read = function () {};
    r.push(msg);
    r.push(null);
    return r;
}
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var csso = require("csso");
var SourceMapGenerator = require("source-map").SourceMapGenerator;
var loaderUtils = require("loader-utils");

module.exports = function(content) {
	this.cacheable && this.cacheable();
	var result = [];
	var queryString = this.query || "";
	var query = loaderUtils.parseQuery(this.query);
	var root = query.root;
	var forceMinimize = query.minimize;
	var minimize = typeof forceMinimize !== "undefined" ? !!forceMinimize : (this && this.minimize);
	var tree = csso.parse(content, "stylesheet");
	if(tree && minimize) {
		tree = csso.compress(tree, query.disableStructuralMinification);
		tree = csso.cleanInfo(tree);
	}

	if(tree) {
		var imports = extractImports(tree);
		annotateUrls(tree);

		imports.forEach(function(imp) {
			if(!loaderUtils.isUrlRequest(imp.url)) {
				result.push("exports.push([module.id, " + JSON.stringify("@import url(" + imp.url + ");") + ", " + JSON.stringify(imp.media.join("")) + "]);");
			} else {
				var importUrl = "-!" +
					this.loaders.slice(this.loaderIndex).map(function(x) { return x.request; }).join("!") + "!" +
					loaderUtils.urlToRequest(imp.url);
				result.push("require(" + JSON.stringify(require.resolve("./mergeImport")) + ")(exports, require(" + JSON.stringify(importUrl) + "), " + JSON.stringify(imp.media.join("")) + ");");
			}
		}, this);
	}

	var css = JSON.stringify(tree ? csso.translate(tree) : "");
	var uriRegExp = /%CSSURL\[%(.*?)%\]CSSURL%/g;
	css = css.replace(uriRegExp, function(str) {
		var match = /^%CSSURL\[%(["']?(.*?)["']?)%\]CSSURL%$/.exec(JSON.parse('"' + str + '"'));
		var url = loaderUtils.parseString(match[2]);
		if(!loaderUtils.isUrlRequest(match[2], root)) return JSON.stringify(match[1]).replace(/^"|"$/g, "");
		var idx = url.indexOf("?");
		if(idx < 0) idx = url.indexOf("#");
		if(idx > 0) {
			// in cases like url('webfont.eot?#iefix')
			var request = url.substr(0, idx);
			return "\"+require(" + JSON.stringify(loaderUtils.urlToRequest(request, root)) + ")+\"" + url.substr(idx);
		} else if(idx === 0) {
			// only hash
			return JSON.stringify(match[1]).replace(/^"|"$/g, "");
		}
		return "\"+require(" + JSON.stringify(loaderUtils.urlToRequest(url, root)) + ")+\"";
	});
	if(query.sourceMap && !minimize) {
		var cssRequest = loaderUtils.getRemainingRequest(this);
		var request = loaderUtils.getCurrentRequest(this);
		var sourceMap = new SourceMapGenerator({
			file: request
		});
		var lines = content.split("\n").length;
		for(var i = 0; i < lines; i++) {
			sourceMap.addMapping({
				generated: {
					line: i+1,
					column: 0
				},
				source: cssRequest,
				original: {
					line: i+1,
					column: 0
				},
			});
		}
		sourceMap.setSourceContent(cssRequest, content);
		result.push("exports.push([module.id, " + css + ", \"\", " + JSON.stringify(sourceMap.toJSON()) + "]);");
	} else {
		result.push("exports.push([module.id, " + css + ", \"\"]);");
	}
	return "exports = module.exports = require(" + JSON.stringify(require.resolve("./cssToString")) + ")();\n" +
		result.join("\n");
}

function extractImports(tree) {
	var results = [];
	var removes = [];
	for(var i = 1; i < tree.length; i++) {
		var rule = tree[i];
		if(rule[0] === "atrules" &&
			rule[1][0] === "atkeyword" &&
			rule[1][1][0] === "ident" &&
			rule[1][1][1] === "import") {
			var imp = {
				url: null,
				media: []
			};
			for(var j = 2; j < rule.length; j++) {
				var item = rule[j];
				if(item[0] === "string") {
					imp.url = loaderUtils.parseString(item[1]);
				} else if(item[0] === "uri") {
					imp.url = item[1][0] === "string" ? loaderUtils.parseString(item[1][1]) : item[1][1];
				} else if(item[0] === "ident" && item[1] !== "url") {
					imp.media.push(csso.translate(item));
				} else if(item[0] !== "s" || imp.media.length > 0) {
					imp.media.push(csso.translate(item));
				}
			}
			while(imp.media.length > 0 &&
				/^\s*$/.test(imp.media[imp.media.length-1]))
				imp.media.pop();
			if(imp.url !== null) {
				results.push(imp);
				removes.push(i);
			}
		}
	}
	removes.reverse().forEach(function(i) {
		tree.splice(i, 1);
	});
	return results;
}
function annotateUrls(tree) {
	function iterateChildren() {
		for(var i = 1; i < tree.length; i++) {
			annotateUrls(tree[i]);
		}
	}
	switch(tree[0]) {
	case "stylesheet": return iterateChildren();
	case "ruleset": return iterateChildren();
	case "block": return iterateChildren();
	case "atruleb": return iterateChildren();
	case "atruler": return iterateChildren();
	case "atrulers": return iterateChildren();
	case "declaration": return iterateChildren();
	case "value": return iterateChildren();
	case "uri":
		for(var i = 1; i < tree.length; i++) {
			var item = tree[i];
			switch(item[0]) {
			case "ident":
			case "raw":
				item[1] = "%CSSURL[%" + item[1] + "%]CSSURL%";
				return;
			case "string":
				item[1] = "%CSSURL[%" + item[1] + "%]CSSURL%";
				return;
			}
		}
	}
}

<commit_msg>fixes webpack/url-loader#7<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var csso = require("csso");
var SourceMapGenerator = require("source-map").SourceMapGenerator;
var loaderUtils = require("loader-utils");

module.exports = function(content) {
	this.cacheable && this.cacheable();
	var result = [];
	var queryString = this.query || "";
	var query = loaderUtils.parseQuery(this.query);
	var root = query.root;
	var forceMinimize = query.minimize;
	var minimize = typeof forceMinimize !== "undefined" ? !!forceMinimize : (this && this.minimize);
	var tree = csso.parse(content, "stylesheet");
	if(tree && minimize) {
		tree = csso.compress(tree, query.disableStructuralMinification);
		tree = csso.cleanInfo(tree);
	}

	if(tree) {
		var imports = extractImports(tree);
		annotateUrls(tree);

		imports.forEach(function(imp) {
			if(!loaderUtils.isUrlRequest(imp.url)) {
				result.push("exports.push([module.id, " + JSON.stringify("@import url(" + imp.url + ");") + ", " + JSON.stringify(imp.media.join("")) + "]);");
			} else {
				var importUrl = "-!" +
					this.loaders.slice(this.loaderIndex).map(function(x) { return x.request; }).join("!") + "!" +
					loaderUtils.urlToRequest(imp.url);
				result.push("require(" + JSON.stringify(require.resolve("./mergeImport")) + ")(exports, require(" + JSON.stringify(importUrl) + "), " + JSON.stringify(imp.media.join("")) + ");");
			}
		}, this);
	}

	var css = JSON.stringify(tree ? csso.translate(tree) : "");
	var uriRegExp = /%CSSURL\[%(.*?)%\]CSSURL%/g;
	css = css.replace(uriRegExp, function(str) {
		var match = /^%CSSURL\[%(["']?(.*?)["']?)%\]CSSURL%$/.exec(JSON.parse('"' + str + '"'));
		var url = loaderUtils.parseString(match[2]);
		if(!loaderUtils.isUrlRequest(match[2], root)) return JSON.stringify(match[1]).replace(/^"|"$/g, "");
		var idx = url.indexOf("?#");
		if(idx < 0) idx = url.indexOf("#");
		if(idx > 0) {
			// in cases like url('webfont.eot?#iefix')
			var request = url.substr(0, idx);
			return "\"+require(" + JSON.stringify(loaderUtils.urlToRequest(request, root)) + ")+\"" + url.substr(idx);
		} else if(idx === 0) {
			// only hash
			return JSON.stringify(match[1]).replace(/^"|"$/g, "");
		}
		return "\"+require(" + JSON.stringify(loaderUtils.urlToRequest(url, root)) + ")+\"";
	});
	if(query.sourceMap && !minimize) {
		var cssRequest = loaderUtils.getRemainingRequest(this);
		var request = loaderUtils.getCurrentRequest(this);
		var sourceMap = new SourceMapGenerator({
			file: request
		});
		var lines = content.split("\n").length;
		for(var i = 0; i < lines; i++) {
			sourceMap.addMapping({
				generated: {
					line: i+1,
					column: 0
				},
				source: cssRequest,
				original: {
					line: i+1,
					column: 0
				},
			});
		}
		sourceMap.setSourceContent(cssRequest, content);
		result.push("exports.push([module.id, " + css + ", \"\", " + JSON.stringify(sourceMap.toJSON()) + "]);");
	} else {
		result.push("exports.push([module.id, " + css + ", \"\"]);");
	}
	return "exports = module.exports = require(" + JSON.stringify(require.resolve("./cssToString")) + ")();\n" +
		result.join("\n");
}

function extractImports(tree) {
	var results = [];
	var removes = [];
	for(var i = 1; i < tree.length; i++) {
		var rule = tree[i];
		if(rule[0] === "atrules" &&
			rule[1][0] === "atkeyword" &&
			rule[1][1][0] === "ident" &&
			rule[1][1][1] === "import") {
			var imp = {
				url: null,
				media: []
			};
			for(var j = 2; j < rule.length; j++) {
				var item = rule[j];
				if(item[0] === "string") {
					imp.url = loaderUtils.parseString(item[1]);
				} else if(item[0] === "uri") {
					imp.url = item[1][0] === "string" ? loaderUtils.parseString(item[1][1]) : item[1][1];
				} else if(item[0] === "ident" && item[1] !== "url") {
					imp.media.push(csso.translate(item));
				} else if(item[0] !== "s" || imp.media.length > 0) {
					imp.media.push(csso.translate(item));
				}
			}
			while(imp.media.length > 0 &&
				/^\s*$/.test(imp.media[imp.media.length-1]))
				imp.media.pop();
			if(imp.url !== null) {
				results.push(imp);
				removes.push(i);
			}
		}
	}
	removes.reverse().forEach(function(i) {
		tree.splice(i, 1);
	});
	return results;
}
function annotateUrls(tree) {
	function iterateChildren() {
		for(var i = 1; i < tree.length; i++) {
			annotateUrls(tree[i]);
		}
	}
	switch(tree[0]) {
	case "stylesheet": return iterateChildren();
	case "ruleset": return iterateChildren();
	case "block": return iterateChildren();
	case "atruleb": return iterateChildren();
	case "atruler": return iterateChildren();
	case "atrulers": return iterateChildren();
	case "declaration": return iterateChildren();
	case "value": return iterateChildren();
	case "uri":
		for(var i = 1; i < tree.length; i++) {
			var item = tree[i];
			switch(item[0]) {
			case "ident":
			case "raw":
				item[1] = "%CSSURL[%" + item[1] + "%]CSSURL%";
				return;
			case "string":
				item[1] = "%CSSURL[%" + item[1] + "%]CSSURL%";
				return;
			}
		}
	}
}

<|endoftext|>


<commit_before>module.exports = function (config) {
    config.set({
        files: [{ pattern: 'tests/**/*.ts', type: 'module' }],

        plugins: [require.resolve('@open-wc/karma-esm'), 'karma-*'],

        esm: {
            nodeResolve: true,
            compatibility: 'all',
            fileExtensions: ['.ts'],
            babel: true,
        },

        reporters: ['progress'],
        frameworks: ['esm', 'mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['ChromeHeadless'],
        autoWatch: true,
        singleRun: true,
        concurrency: Infinity,
    });
};
<commit_msg>Remove deprecated flag<commit_after>module.exports = function (config) {
    config.set({
        files: [{ pattern: 'tests/**/*.ts', type: 'module' }],

        plugins: [require.resolve('@open-wc/karma-esm'), 'karma-*'],

        esm: {
            nodeResolve: true,
            fileExtensions: ['.ts'],
            babel: true,
        },

        reporters: ['progress'],
        frameworks: ['esm', 'mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['ChromeHeadless'],
        autoWatch: true,
        singleRun: true,
        concurrency: Infinity,
    });
};
<|endoftext|>