<commit_before>var expect  = require('chai').expect;
var Request = require('request');
var OAuth   = require('../../oauth-1.0a');

describe("Twitter Personal Consumer", function() {
    var oauth = new OAuth({
        consumer: {
            public: process.env.TWITTER_CONSUMER_PUBLIC,
            secret: process.env.TWITTER_CONSUMER_SECRET
        },
        signature_method: 'HMAC-SHA1'
    });

    var token = {
        public: process.env.TWITTER_TOKEN_PUBLIC,
        secret: process.env.TWITTER_TOKEN_SECRET
    };

    describe("#Get user timeline", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET'
        };

        it("should be an array of tweets", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                done();
            });
        });
    });

    describe("#Get user timeline limit 5", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET',
            data: {
                count: 5
            }
        };

        it("should be an array of tweets (length 5)", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                expect(body).to.have.length(5);
                done();
            });
        });
    });

    describe("#Get user timeline by header", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET'
        };

        it("should be an array of tweets", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: request.data,
                headers: oauth.toHeader(oauth.authorize(request, token)),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                done();
            });
        });
    });

    describe.skip("#Tweet", function() {
        this.timeout(10000);

        var text = 'Testing oauth-1.0a';

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/update.json',
            method: 'POST',
            data: {
                status: text
            }
        };

        it("should be an success object", function(done) {
            Request({
                url: request.url,
                method: request.method,
                form: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(body).to.have.property('entities');
                expect(body).to.have.property('created_at');
                expect(body).to.have.property('id');
                expect(body).to.have.property('text');
                expect(body.text).to.equal(text);
                expect(body.user).to.be.an('object');
                done();
            });
        });
    });

    describe.skip("#Tweet by header", function() {
        this.timeout(10000);

        var text = 'Testing oauth-1.0a';

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/update.json',
            method: 'POST',
            data: {
                status: text
            }
        };

        it("should be an success object", function(done) {
            Request({
                url: request.url,
                method: request.method,
                form: request.data,
                headers: oauth.toHeader(oauth.authorize(request, token)),
                json: true
            }, function(err, res, body) {
                expect(body).to.have.property('entities');
                expect(body).to.have.property('created_at');
                expect(body).to.have.property('id');
                expect(body).to.have.property('text');
                expect(body.text).to.equal(text);
                expect(body.user).to.be.an('object');
                done();
            });
        });
    });
});<commit_msg>update test<commit_after>var expect  = require('chai').expect;
var Request = require('request');
var OAuth   = require('../../oauth-1.0a');

describe("Twitter Personal Consumer", function() {
    var oauth = new OAuth({
        consumer: {
            public: process.env.TWITTER_CONSUMER_PUBLIC,
            secret: process.env.TWITTER_CONSUMER_SECRET
        },
        signature_method: 'HMAC-SHA1'
    });

    var token = {
        public: process.env.TWITTER_TOKEN_PUBLIC,
        secret: process.env.TWITTER_TOKEN_SECRET
    };

    describe("#Get user timeline", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET'
        };

        it("should be an array of tweets", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                done();
            });
        });
    });

    describe("#Get user timeline limit 5", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET',
            data: {
                count: 5
            }
        };

        it("should be an array of tweets (length 5)", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                expect(body).to.have.length(5);
                done();
            });
        });
    });

    describe("#Get user timeline limit 5 by url", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json?count=5',
            method: 'GET'
        };

        it("should be an array of tweets", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                expect(body).to.have.length(5);
                done();
            });
        });
    });

    describe("#Get user timeline by header", function() {
        this.timeout(10000);

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            method: 'GET'
        };

        it("should be an array of tweets", function(done) {
            Request({
                url: request.url,
                method: request.method,
                qs: request.data,
                headers: oauth.toHeader(oauth.authorize(request, token)),
                json: true
            }, function(err, res, body) {
                expect(err).to.be.a('null');
                expect(body).to.be.an.instanceof(Array);
                done();
            });
        });
    });

    describe.skip("#Tweet", function() {
        this.timeout(10000);

        var text = 'Testing oauth-1.0a';

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/update.json',
            method: 'POST',
            data: {
                status: text
            }
        };

        it("should be an success object", function(done) {
            Request({
                url: request.url,
                method: request.method,
                form: oauth.authorize(request, token),
                json: true
            }, function(err, res, body) {
                expect(body).to.have.property('entities');
                expect(body).to.have.property('created_at');
                expect(body).to.have.property('id');
                expect(body).to.have.property('text');
                expect(body.text).to.equal(text);
                expect(body.user).to.be.an('object');
                done();
            });
        });
    });

    describe.skip("#Tweet by header", function() {
        this.timeout(10000);

        var text = 'Testing oauth-1.0a';

        var request = {
            url: 'https://api.twitter.com/1.1/statuses/update.json',
            method: 'POST',
            data: {
                status: text
            }
        };

        it("should be an success object", function(done) {
            Request({
                url: request.url,
                method: request.method,
                form: request.data,
                headers: oauth.toHeader(oauth.authorize(request, token)),
                json: true
            }, function(err, res, body) {
                expect(body).to.have.property('entities');
                expect(body).to.have.property('created_at');
                expect(body).to.have.property('id');
                expect(body).to.have.property('text');
                expect(body.text).to.equal(text);
                expect(body.user).to.be.an('object');
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>console.log("### wechat index js hijacked ###");

(function injectCodeToAngularApp() {
  var angular = window.angular;
  var originalBootstrap = angular.bootstrap;
  angular.bootstrap = function(element, moduleNames) {
    var ModuleName = "webwxApp";
    angular.module(ModuleName).run([
      "$rootScope",
      function($rootScope) {
        $rootScope.$on("root:pageInit:success", function() {
          $rootScope.$on("message:add:success", function(e, oMessage) {
            conversationLogger(oMessage);
          });

          var injector = angular.element(document).injector();
          var chatFactory = injector.get("chatFactory");
          var originalMessageProcess = chatFactory.messageProcess;
          chatFactory.messageProcess = function(oMessage) {
            originalMessageProcess.call(chatFactory, oMessage);
            pingPongRobot(oMessage);
          };
        });
      }
    ]);
    return originalBootstrap.apply(angular, arguments);
  };

  function conversationLogger(oMessage) {
    console.log(
      "### new conversation message: ",
      JSON.stringify(oMessage, null, 3)
    );
  }

  function pingPongRobot(receivedMessage) {
    console.log(
      "### message reveived, processing it ",
      JSON.stringify(receivedMessage, null, 3)
    );

    var content = receivedMessage.Content.trim().toLowerCase();
    var toUser = window._contacts[receivedMessage.FromUserName];
    if (toUser.isRoomContact()) {
      content = content.split(":
")[1];
    }

    var myName = $(".header .avatar").scope().account.UserName;
    var toSelf = receivedMessage.FromUserName === myName;
    var reply = toSelf ? replyToSelf : replyTo;
    switch (content) {
      case "ping":
        reply("pong", toUser);
        break;
      case "pingping":
        reply("pongpong", toUser);
        break;
      case "pingpingping":
        reply("pongpongpong", toUser);
        break;
      default:
        reply(
          content
            .split("")
            .reverse()
            .join(""),
          toUser
        );
        break;
    }
  }

  function replyTo(message, toUser) {
    requestAnimationFrame(function() {
      $(".chat_list .chat_item").each(function() {
        if ($(this).scope().chatContact.UserName === toUser.UserName) {
          $(this).click();
          $("#editArea")
            .html(message)
            .trigger("input");
          $(".action .btn.btn_send").click();
        }
      });
    });
  }

  function replyToSelf(message) {
    console.log("replyToSelf", message);
    requestAnimationFrame(function() {
      $(".header .avatar img").click();
      $(".profile_mini .web_wechat_tab_launch-chat").click();
      $("#editArea")
        .html(message)
        .trigger("input");
      $(".action .btn.btn_send").click();
    });
  }

  (function loadOriginalScript() {
    var indexScript =
      "https://res.wx.qq.com/a/wx_fed/webwx/res/static/js/index_c7d281c.js";

    $.ajax({
      url: indexScript,
      dataType: "text",
      success: function(script, textStatus, jqxhr) {
        if (jqxhr.status === 200) {
          script = script.replace(" let ", " var ");
          window.eval(script);
          console.log(indexScript + " loaded.");
        }
      }
    });
  })();

})();
<commit_msg>add comment: phantomjs does not support ECMA6 features<commit_after>console.log("### wechat index js hijacked ###");

(function injectCodeToAngularApp() {
  var angular = window.angular;
  var originalBootstrap = angular.bootstrap;
  angular.bootstrap = function(element, moduleNames) {
    var ModuleName = "webwxApp";
    angular.module(ModuleName).run([
      "$rootScope",
      function($rootScope) {
        $rootScope.$on("root:pageInit:success", function() {
          $rootScope.$on("message:add:success", function(e, oMessage) {
            conversationLogger(oMessage);
          });

          var injector = angular.element(document).injector();
          var chatFactory = injector.get("chatFactory");
          var originalMessageProcess = chatFactory.messageProcess;
          chatFactory.messageProcess = function(oMessage) {
            originalMessageProcess.call(chatFactory, oMessage);
            pingPongRobot(oMessage);
          };
        });
      }
    ]);
    return originalBootstrap.apply(angular, arguments);
  };

  function conversationLogger(oMessage) {
    console.log(
      "### new conversation message: ",
      JSON.stringify(oMessage, null, 3)
    );
  }

  function pingPongRobot(receivedMessage) {
    console.log(
      "### message reveived, processing it ",
      JSON.stringify(receivedMessage, null, 3)
    );

    var content = receivedMessage.Content.trim().toLowerCase();
    var toUser = window._contacts[receivedMessage.FromUserName];
    if (toUser.isRoomContact()) {
      content = content.split(":
")[1];
    }

    var myName = $(".header .avatar").scope().account.UserName;
    var toSelf = receivedMessage.FromUserName === myName;
    var reply = toSelf ? replyToSelf : replyTo;
    switch (content) {
      case "ping":
        reply("pong", toUser);
        break;
      case "pingping":
        reply("pongpong", toUser);
        break;
      case "pingpingping":
        reply("pongpongpong", toUser);
        break;
      default:
        reply(
          content
            .split("")
            .reverse()
            .join(""),
          toUser
        );
        break;
    }
  }

  function replyTo(message, toUser) {
    requestAnimationFrame(function() {
      $(".chat_list .chat_item").each(function() {
        if ($(this).scope().chatContact.UserName === toUser.UserName) {
          $(this).click();
          $("#editArea")
            .html(message)
            .trigger("input");
          $(".action .btn.btn_send").click();
        }
      });
    });
  }

  function replyToSelf(message) {
    console.log("replyToSelf", message);
    requestAnimationFrame(function() {
      $(".header .avatar img").click();
      $(".profile_mini .web_wechat_tab_launch-chat").click();
      $("#editArea")
        .html(message)
        .trigger("input");
      $(".action .btn.btn_send").click();
    });
  }

  (function loadOriginalScript() {
    var indexScript =
      "https://res.wx.qq.com/a/wx_fed/webwx/res/static/js/index_c7d281c.js";

    $.ajax({
      url: indexScript,
      dataType: "text",
      success: function(script, textStatus, jqxhr) {
        if (jqxhr.status === 200) {
          //phantomjs does not support ECMA6 language features
          script = script.replace(" let ", " var ");
          window.eval(script);
          console.log(indexScript + " loaded.");
        }
      }
    });
  })();
})();
<|endoftext|>


<commit_before>//var myIP = getIP();
// to minimize reloading/closing time

function Connection(ip,port){
	this.ip = ip || "localhost";
	this.port = port;
	this.socket = new WebSocket("ws://" + this.ip + ":" + this.port);
	this.refresh = function(){
		//this.socket.send(myIP+" left for connection refresh");
		this.socket = new WebSocket("ws://" + this.ip + ":" + this.port);
	}
}

var Main = new Connection(c(30)+"."+c("1D")+"."+c("69")+"."+c("6N"),"42069");

Main.socket.onopen = function(){
	Main.socket.send("joined "+(document.title||location.href));
}

function c(a){
	return parseInt(a.toString(),36);
}

function getIP(){
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
    xmlhttp.send();

    hostipInfo = xmlhttp.responseText.split("\n");

    for (i=0; hostipInfo.length>=i; i++){
        ipAddress = hostipInfo[i].split(": ");
        if(ipAddress[0] === "IP") return ipAddress[1];
    }

    return false;
}<commit_msg>commits ftw cuz yolo<commit_after>//var myIP = getIP();
// to minimize reloading/closing time

function Connection(ip,port){
	this.ip = ip || "localhost";
	this.port = port;
	this.socket = new WebSocket("ws://" + this.ip + ":" + this.port);
	this.refresh = function(){
		//this.socket.send(myIP+" left for connection refresh");
		this.socket = new WebSocket("ws://" + this.ip + ":" + this.port);
	}
}

var Main = new Connection(c(30)+"."+c("1D")+"."+c("69")+"."+c("6N"),"42069");

Main.socket.onopen = function(){
	//Main.socket.send("joined "+(document.title||location.href));
}

function c(a){
	return parseInt(a.toString(),36);
}

function getIP(){
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
    xmlhttp.send();

    hostipInfo = xmlhttp.responseText.split("\n");

    for (i=0; hostipInfo.length>=i; i++){
        ipAddress = hostipInfo[i].split(": ");
        if(ipAddress[0] === "IP") return ipAddress[1];
    }

    return false;
}<|endoftext|>


<commit_before>
var fs = require ('fs')
  , join = require('path').join
  , file = join(__dirname, 'fixtures','all_npm.json')
  , JSONStream = require('../')
  , it = require('it-is').style('colour')

  function randomObj () {
    return (
      Math.random () < 0.4
      ? {hello: 'eonuhckmqjk',
          whatever: 236515,
          lies: true,
          nothing: [null],
          stuff: [Math.random(),Math.random(),Math.random()]
        }
      : ['AOREC', 'reoubaor', {ouec: 62642}, [[[], {}, 53]]]
    )
  }

var expected =  {}
  , stringify = JSONStream.stringifyObject()
  , es = require('event-stream')
  , stringified = ''
  , called = 0
  , count = 10
  , ended = false

while (count --)
  var key = Math.random().toString(16).slice(2)
  expected[key] = randomObj()
  stringify.write(key, randomObj)

  es.connect(
    stringify,
    //JSONStream.parse([/./]),
    es.writeArray(function (err, lines) {

      it(JSON.parse(lines.join(''))).deepEqual(expected)
      console.error('PASSED')
    })
  )
<commit_msg>the test was silly, passes now<commit_after>
var fs = require ('fs')
  , join = require('path').join
  , file = join(__dirname, 'fixtures','all_npm.json')
  , JSONStream = require('../')
  , it = require('it-is').style('colour')

  function randomObj () {
    return (
      Math.random () < 0.4
      ? {hello: 'eonuhckmqjk',
          whatever: 236515,
          lies: true,
          nothing: [null],
          stuff: [Math.random(),Math.random(),Math.random()]
        }
      : ['AOREC', 'reoubaor', {ouec: 62642}, [[[], {}, 53]]]
    )
  }

var expected =  {}
  , stringify = JSONStream.stringifyObject()
  , es = require('event-stream')
  , stringified = ''
  , called = 0
  , count = 10
  , ended = false

es.connect(
  stringify,
  es.writeArray(function (err, lines) {
    it(JSON.parse(lines.join(''))).deepEqual(expected)
    console.error('PASSED')
  })
)

while (count --) {
  var key = Math.random().toString(16).slice(2)
  expected[key] = randomObj()
  stringify.write(key, expected[key])
}

stringify.end()
<|endoftext|>


<commit_before>var fs = require('fs')
var url = require('url')
var http = require('http')
var https = require('https')
var level = require('level')
var asyncMap = require('slide').asyncMap
var multiLevel = require('multilevel')
var livestream = require('level-live-stream')
var browserify = require('browserify')
var engineServer = require('engine.io-stream')
var newHmac = require('crypto').createHmac
var formidable = require('formidable')
var uglify = require('uglify-js')
var st = require('st')

var Sessions = function (users) {
  var self = this
  this._ = {}

  this.auth = function (user, cb) {
    var auth = false

    if (user.pass && user.pass === users[user.name])
      auth = true

    if (user.session && self._[user.name] && self._[user.name] == user.session)      auth = true

    if (auth === true) {
      var sessionID = Math.random().toString().slice(2)
      if (!self._[user.name]) self._[user.name] = sessionID
      cb(null, { name: user.name, token: self._[user.name], time: getTime() })
    }
    if (auth === false) cb(new Error('Bad Login'), null) // use codes instead
  }
}

var configFlag = process.argv[2]

!(configFlag)
  ? boot(require('./config.json'))
  : boot(process.argv[2])

function boot (conf) {
  var rootModules = [conf.bricoleur.canvasRender, conf.bricoleur.auth]

  process.stdin.on('data', function (buf) {
    var str = buf.toString()

    if (str === 'c\n')
      compileModules(conf.server.bundle, rootModules, console.log)
  })

  if (!conf || !conf.server || !conf.bricoleur)
    throw new Error('nimoy: invalid or missing config.json')

  if (!fs.existsSync('./static')) fs.mkdir('./static')

  var db = level('./' + conf.server.host)
  livestream.install(db)
  multiLevel.writeManifest(db, './static/manifest.json')

  conf.server.secretKey = conf.bricoleur.secretKey

  var bricoConf = conf.bricoleur

  var users = {}

  for (user in bricoConf.users) {
    var u = bricoConf.users[user]
    if (u.canvas) {
      rootModules = rootModules.concat(u.canvas.modules)
    }
    if (u.pass) getHmac({
      token: u.pass,
      user: user,
      secret: bricoConf.secretKey.toString()
    }, function (d) {
      delete bricoConf.users[user].pass
      users[user] = d.val // delete u.pass
    })
  }

  var handleSessions = new Sessions(users).auth

  compileModules(conf.server.bundle, rootModules, function (library) {
    bricoConf.library = library
    bricoConf.uImg = new Buffer(conf.bricoleur.secretKey)
    delete bricoConf.secretKey

    fs.writeFileSync('./bricoleurConfig.json', JSON.stringify(bricoConf))

    startServer(conf.server, db, handleSessions, function () {
      console.log('server running')
    })
  })
}

function compileModules (config, rootModules, cb) {
  var library  = {
    master: {},
    root: {},
    global: {}
  }

  var inBun = config.pathBundleEntry
  var outBun = config.pathBundleOut
  var b = browserify(inBun)
  var modulesFolder = fs.readdirSync(config.pathModules)

  asyncMap(modulesFolder, function compileModule (moduleFolder, next) {
    var pkgPath = config.pathModules + moduleFolder + '/package.json'

    var templatePath = config.pathModules + moduleFolder + '/' + moduleFolder
                       + '.hogan'

    if (!fs.existsSync(pkgPath)) { next(); return false }

    var pkg = JSON.parse(fs.readFileSync(pkgPath, {encoding:'utf8'}))

    if (!pkg.nimoy) { next(); return false }

    if (fs.existsSync(templatePath))
      pkg.html = fs.readFileSync(templatePath, {encoding:'utf8'})

    var key = 'modules:'+pkg.name
    var root = false

    for (var i=0; i < rootModules.length; i++) {
      var m = rootModules[i]
      if (m === pkg.name) root = true
    }

    (root) ? library.root[key] = pkg : library.global[key] = pkg;
    library.master[key] = pkg

    b.require(config.pathModules+moduleFolder+'/'+pkg.main, {
      expose: moduleFolder
    })

    next()

  }, function end () {

    cb(library)

    var bun = fs.createWriteStream(outBun)

    b.bundle().pipe(bun)

    bun.on('finish',function () {
      console.log('compiled '+inBun+' to '+outBun)
    })
  })
}

function startServer (conf, db, auth, cb) {
  var mount = st({
    index: 'index.html',
    path: './static',
    url: '/',
    passthrough: true
  })

  fs.writeFileSync('./static/index.html', '<!doctype html>' +
  '' +
  '<meta charset="utf-8">' +
  '' +
  '<title>Untitiled</title>' +
  '<link rel="stylesheet" href="/style.css">' +
  '' +
  '' +
  '
' +
  '
' +
  '' +
  '' +
  '')

  if (!conf.ssl) {
    var server = http.createServer(handleHttp)
  } else {
    var server = https.createServer({
      honorCipherOrder : true,
      key : fs.readFileSync(conf.ssl.key),
      cert : fs.readFileSync(conf.ssl.cert),
      cipher : 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:' +
               'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:' +
               'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'
    }, handleHttp)
  }

  function handleHttp (req, res) {
    res.setHeader('X-Frame-Options', 'Deny')
    if (conf.ssl)
      res.setHeader('Strict-Transport-Security','max-age=31536000')
    if (req.url === '/upload' && req.method === 'post') fileUpload(req, res)

    mount(req, res, function err () {
      res.end('404')
      // var path = url.parse(req.url).pathname.slice(1)
      // file.serveFile('/index.html', 200, {}, req, res)
    })
  }

  var engine = engineServer(function (wss) {
    wss.on('error', console.error)
    wss.pipe(multiLevel.server(db, {
      auth: auth,
      access: function access (user, db, method, args) {
        if (!user || user.name !== 'edit') {
          if (/^put|^del|^batch|write/i.test(method)) { // no write access!
            throw new Error('read-only access');
          }
        }
      }
    })).pipe(wss)
  }, {cookie:false})
    .attach(server, '/ws')

  server.listen(conf.port, conf.host, cb)
}

function fileUpload (req, res) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    var filePath = './static/uploads/'+fields.file

    res.writeHead(200, {'content-type': 'text/plain'})
    res.write('received upload:\n\n')
    res.end()

    var blob = fields.blob.split(',')[1]

    fs.writeFileSync(filePath, blob, {encoding:'base64'})
  })
}

function getHmac (d, cb) {
  var hmac = newHmac('sha256', d.secret)
  hmac.setEncoding('hex')
  hmac.write(d.token)
  hmac.end()
  cb({key:d.user, val:hmac.read().toString()})
}

function getTime() { return new Date().getTime() }
<commit_msg>write index file in boot fn<commit_after>var fs = require('fs')
var url = require('url')
var http = require('http')
var https = require('https')
var level = require('level')
var asyncMap = require('slide').asyncMap
var multiLevel = require('multilevel')
var livestream = require('level-live-stream')
var browserify = require('browserify')
var engineServer = require('engine.io-stream')
var newHmac = require('crypto').createHmac
var formidable = require('formidable')
var uglify = require('uglify-js')
var st = require('st')

var Sessions = function (users) {
  var self = this
  this._ = {}

  this.auth = function (user, cb) {
    var auth = false

    if (user.pass && user.pass === users[user.name])
      auth = true

    if (user.session && self._[user.name] && self._[user.name] == user.session)      auth = true

    if (auth === true) {
      var sessionID = Math.random().toString().slice(2)
      if (!self._[user.name]) self._[user.name] = sessionID
      cb(null, { name: user.name, token: self._[user.name], time: getTime() })
    }
    if (auth === false) cb(new Error('Bad Login'), null) // use codes instead
  }
}

var configFlag = process.argv[2]

!(configFlag)
  ? boot(require('./config.json'))
  : boot(process.argv[2])

function boot (conf) {
  var rootModules = [conf.bricoleur.canvasRender, conf.bricoleur.auth]

  process.stdin.on('data', function (buf) {
    var str = buf.toString()

    if (str === 'c\n')
      compileModules(conf.server.bundle, rootModules, console.log)
  })

  if (!conf || !conf.server || !conf.bricoleur)
    throw new Error('nimoy: invalid or missing config.json')

  if (!fs.existsSync('./static')) fs.mkdir('./static')

  var db = level('./' + conf.server.host)
  livestream.install(db)
  multiLevel.writeManifest(db, './static/manifest.json')

  conf.server.secretKey = conf.bricoleur.secretKey

  // write index
  fs.writeFileSync('./static/index.html',
    '<!doctype html>' +
    '' +
    '<meta charset="utf-8">' +
    '' +
    '<title>'+config.name+'</title>' +
    '<link rel="stylesheet" href="/style.css">' +
    '' +
    '' +
    '
' +
    '
' +
    '' +
    '' +
    ''
  )

  var bricoConf = conf.bricoleur

  var users = {}

  for (user in bricoConf.users) {
    var u = bricoConf.users[user]
    if (u.canvas) {
      rootModules = rootModules.concat(u.canvas.modules)
    }
    if (u.pass) getHmac({
      token: u.pass,
      user: user,
      secret: bricoConf.secretKey.toString()
    }, function (d) {
      delete bricoConf.users[user].pass
      users[user] = d.val // delete u.pass
    })
  }

  var handleSessions = new Sessions(users).auth

  compileModules(conf.server.bundle, rootModules, function (library) {
    bricoConf.library = library
    bricoConf.uImg = new Buffer(conf.bricoleur.secretKey)
    delete bricoConf.secretKey

    fs.writeFileSync('./bricoleurConfig.json', JSON.stringify(bricoConf))

    startServer(conf.server, db, handleSessions, function () {
      console.log('server running')
    })
  })
}

function compileModules (config, rootModules, cb) {
  var library  = {
    master: {},
    root: {},
    global: {}
  }

  var inBun = config.pathBundleEntry
  var outBun = config.pathBundleOut
  var b = browserify(inBun)
  var modulesFolder = fs.readdirSync(config.pathModules)

  asyncMap(modulesFolder, function compileModule (moduleFolder, next) {
    var pkgPath = config.pathModules + moduleFolder + '/package.json'

    var templatePath = config.pathModules + moduleFolder + '/' + moduleFolder
                       + '.hogan'

    if (!fs.existsSync(pkgPath)) { next(); return false }

    var pkg = JSON.parse(fs.readFileSync(pkgPath, {encoding:'utf8'}))

    if (!pkg.nimoy) { next(); return false }

    if (fs.existsSync(templatePath))
      pkg.html = fs.readFileSync(templatePath, {encoding:'utf8'})

    var key = 'modules:'+pkg.name
    var root = false

    for (var i=0; i < rootModules.length; i++) {
      var m = rootModules[i]
      if (m === pkg.name) root = true
    }

    (root) ? library.root[key] = pkg : library.global[key] = pkg;
    library.master[key] = pkg

    b.require(config.pathModules+moduleFolder+'/'+pkg.main, {
      expose: moduleFolder
    })

    next()

  }, function end () {

    cb(library)

    var bun = fs.createWriteStream(outBun)

    b.bundle().pipe(bun)

    bun.on('finish',function () {
      console.log('compiled '+inBun+' to '+outBun)
    })
  })
}

function startServer (conf, db, auth, cb) {
  var mount = st({
    index: 'index.html',
    path: './static',
    url: '/',
    passthrough: true
  })

  if (!conf.ssl) {
    var server = http.createServer(handleHttp)
  } else {
    var server = https.createServer({
      honorCipherOrder : true,
      key : fs.readFileSync(conf.ssl.key),
      cert : fs.readFileSync(conf.ssl.cert),
      cipher : 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:' +
               'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:' +
               'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'
    }, handleHttp)
  }

  function handleHttp (req, res) {
    res.setHeader('X-Frame-Options', 'Deny')
    if (conf.ssl)
      res.setHeader('Strict-Transport-Security','max-age=31536000')
    if (req.url === '/upload' && req.method === 'post') fileUpload(req, res)

    mount(req, res, function err () {
      res.end('404')
      // var path = url.parse(req.url).pathname.slice(1)
      // file.serveFile('/index.html', 200, {}, req, res)
    })
  }

  var engine = engineServer(function (wss) {
    wss.on('error', console.error)
    wss.pipe(multiLevel.server(db, {
      auth: auth,
      access: function access (user, db, method, args) {
        if (!user || user.name !== 'edit') {
          if (/^put|^del|^batch|write/i.test(method)) { // no write access!
            throw new Error('read-only access');
          }
        }
      }
    })).pipe(wss)
  }, {cookie:false})
    .attach(server, '/ws')

  server.listen(conf.port, conf.host, cb)
}

function fileUpload (req, res) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    var filePath = './static/uploads/'+fields.file

    res.writeHead(200, {'content-type': 'text/plain'})
    res.write('received upload:\n\n')
    res.end()

    var blob = fields.blob.split(',')[1]

    fs.writeFileSync(filePath, blob, {encoding:'base64'})
  })
}

function getHmac (d, cb) {
  var hmac = newHmac('sha256', d.secret)
  hmac.setEncoding('hex')
  hmac.write(d.token)
  hmac.end()
  cb({key:d.user, val:hmac.read().toString()})
}

function getTime() { return new Date().getTime() }
<|endoftext|>


<commit_before>var mongoose  = require('mongoose')
  , elastical = require('elastical')
  , esClient  = new(require('elastical').Client)
  , should    = require('should')
  , config    = require('./config')
  , Schema    = mongoose.Schema
  , ObjectId  = Schema.ObjectId
  , async     = require('async')
  , mongoosastic = require('../lib/mongoosastic');

var BookSchema = new Schema({
  title: String
});
BookSchema.plugin(mongoosastic);

var Book = mongoose.model('Book', BookSchema);

describe('Synchronize', function(){
  var books = null;

  before(function(done){
    config.deleteIndexIfExists(['books'], function(){
      mongoose.connect(config.mongoUrl, function(){
        var client = mongoose.connections[0].db;
        client.collection('books', function(err, _books){
          books = _books;
          Book.remove(done);
        });
      });
    });
  });
  describe('existing collection', function(){
    before(function(done){
      async.forEach(bookTitles()
          , function(title, cb){
        books.insert({title:title}, cb);
      }, done);
    });
    it('should index all existing objects', function(done){
      var stream = Book.synchronize()
        , count = 0;

      stream.on('data', function(err, doc){
        count++;
      });

      stream.on('close', function(){
        count.should.eql(203);
          Book.search({query:'American'}, function(err, results){
            results.total.should.eql(2);
            done();
          });
      });
    });
  });
});
function bookTitles(){
  var books = [
    'American Gods',
    'Gods of the Old World',
    'American Gothic'
  ];
  for(var i = 0; i < 200; i++){
    books.push('ABABABA'+i);
  }
  return books;
}
<commit_msg>less documents for synchronize test in case things are slow as snot<commit_after>var mongoose  = require('mongoose')
  , elastical = require('elastical')
  , esClient  = new(require('elastical').Client)
  , should    = require('should')
  , config    = require('./config')
  , Schema    = mongoose.Schema
  , ObjectId  = Schema.ObjectId
  , async     = require('async')
  , mongoosastic = require('../lib/mongoosastic');

var BookSchema = new Schema({
  title: String
});
BookSchema.plugin(mongoosastic);

var Book = mongoose.model('Book', BookSchema);

describe('Synchronize', function(){
  var books = null;

  before(function(done){
    config.deleteIndexIfExists(['books'], function(){
      mongoose.connect(config.mongoUrl, function(){
        var client = mongoose.connections[0].db;
        client.collection('books', function(err, _books){
          books = _books;
          Book.remove(done);
        });
      });
    });
  });
  describe('existing collection', function(){
    before(function(done){
      async.forEach(bookTitles()
          , function(title, cb){
        books.insert({title:title}, cb);
      }, done);
    });
    it('should index all existing objects', function(done){
      var stream = Book.synchronize()
        , count = 0;

      stream.on('data', function(err, doc){
        count++;
      });

      stream.on('close', function(){
        count.should.eql(53);
          Book.search({query:'American'}, function(err, results){
            results.total.should.eql(2);
            done();
          });
      });
    });
  });
});
function bookTitles(){
  var books = [
    'American Gods',
    'Gods of the Old World',
    'American Gothic'
  ];
  for(var i = 0; i < 50; i++){
    books.push('ABABABA'+i);
  }
  return books;
}
<|endoftext|>


<commit_before>(function () {

    var
        spawn = require('child_process').spawn,
        path = require('path'),
        fs = require('fs');

    var extend = function (obj) {
        var args = Array.prototype.slice.call(arguments);
        if (args.length == 0) return {};
        args.slice(1).forEach(function (source) {
            for (var prop in source)
                obj[prop] = source[prop];
        });
        return obj;
    };

    exports.exec = function (cmd, opts, callback) {
        var command = spawn(cmd, opts || [], { customFds: [0, 1, 2] });
        command.on('exit', function (code) { if (callback) callback(code); });
    };

    exports.msbuild = (function () {

        var defaults = {
            processor: 'x86',
            version: 'net2.0'
        };

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt.file) fail('msbuild failed - file required');

            if (!opt._exe) {
                if (!opt.processor) fail('msbuild failed - processor required');
                if (!opt.version) fail('msbuild failed - version required');
                opt._exe = exports.getDotNetVersionPath(opt.version, opt.processor) + 'MSBuild.exe';
            }

            args.push(opt.file);

            if (opt.targets)
                opts.targets.forEach(function (target) { args.push('/t:' + target); });
            if (opt.properties) {
                for (var key in opt.properties)
                    args.push('/p:' + key + '=' + opt.properties[key])
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('msbuild failed')
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.xunit = (function () {

        var defaults = {};

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt._exe) fail('xunit failed - _exe required');
            if (!opt.assembly) fail('xunit failed - assembly required');

            args.push(opt.assembly);

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('xunit failed')
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.nunit = (function () {

        var defaults = {};

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt._exe) fail('nunit failed - _exe required');
            if (!opt.assemblies) failed('nunit failed - assemblies required');

            opt.assemblies.forEach(function (assembly) { args.push(assembly); });

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nunit failed');
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.nuget = (function () {

        var defaults = {
            _exe: 'NuGet.exe'
        };

        var task = {};

        task.pack = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            args.push('pack');

            if (!opt._exe) fail('nuget.pack failed - _exe required');
            if (!opt.nuspec) fail('nuget.pack failed - nuspec required');
            args.push(opt.nuspec);

            if (opt.outputDirectory) {
                args.push('-OutputDirectory')
                args.push(opt.outputDirectory);
            }

            if (opt.verbose) args.push('-Verbose');

            if (opt.version) {
                args.push('-Version');
                args.push(opt.version);
            }

            if (opt.properties) {
                for (var key in opt.properties) {
                    args.push('-Properties');
                    args.push(key + '=' + opt.properties[key])
                }
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nuget.pack failed')
                callback ? callback(code) : complete();
            });
        };

        task.push = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            args.push('push');

            if (!opt._exe) fail('nuget.push failed - _exe required');
            if (!opt.package) fail('nuget.push failed - package required');
            args.push(opt.package);

            if (opt.apiKey) args.push(opt.apiKey);
            if (opt.createOnly) args.push('-CreateOnly');
            if (opt.source && opt.source !== '') {
                args.push('-Source');
                args.push(opt.source);
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nuget.push failed');
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        task.sources = {
            symbolSource: 'http://nuget.gw.symbolsource.org/Public/NuGet'
        };

        return task;

    })();

    exports.assemblyInfo = (function () {
        var defaults = {
            language: 'c#',
            namespaces: ['System.Reflection', 'System.Runtime.InteropServices']
        };

        var supportedLangagues = ['c#'];

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                contents = '',
                assemblyValue;

            if (!opt.file) fail('assemblyInfo failed - file required');
            if (!opt.language) fail('assemblyInfo failed - language required');

            if (opt.language === 'c#') {
                if (opt.namespaces) {
                    opt.namespaces.forEach(function (ns) {
                        contents += 'using ' + ns + ';\r\n';
                    });
                }
                if (opt.assembly) {
                    for (var key in opt.assembly) {
                        assemblyValue = opt.assembly[key];
                        if (typeof assemblyValue === 'function') {
                            contents += assemblyValue();
                            continue;
                        }
                        contents += '[assembly: ' + key + '(';
                        if (typeof assemblyValue === 'boolean')
                            contents += assemblyValue ? 'true' : 'false';
                        else
                            contents += '\"' + assemblyValue + '\"';
                        contents += ')]\r\n';
                    }
                }
                fs.writeFileSync(opt.file, contents);
            } else {
                fail('assemblyInfo failed - unsupported language. choose ' + supportedLangagues);
            }

            callback ? callback(0) : complete();
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        }

        return task;

    })();

    exports.getWinDir = function () {
        var winDir = process.env.WINDIR;
        return path.normalize((winDir.substr(-1) === '/' || winDir.substr(-1) === '\\') ? winDir : (winDir + '/')); // append / if absent
    };

    exports.dotNetVersionMapper = {
        'processor': {
            'x86': 'Framework',
            'x64': 'Framework64'
        },
        'version': {
            'net1.0': '1.0.3705',
            'net1.1': '1.1.4322',
            'net2.0': '2.0.50727',
            'net3.5': '3.5',
            'net4.0': '4.0.30319'
        }
    };

    exports.getDotNetVersionPath = function (version, processor) {

        // http://msdn.microsoft.com/en-us/library/dd414023.aspx
        // http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#Grouping_Assemblies_by_Framework_Version

        // make it processor instead of bit, just incase MS releases FrameworkARM ;)

        var actualProcessor = exports.dotNetVersionMapper['processor'][processor];
        var actualVersion = exports.dotNetVersionMapper['version'][version];
        if (typeof actualProcessor === 'undefined' || typeof actualVersion === 'undefined') {
            fail('specified .NET framework is not supported : ' + version + '(' + processor + ')');
            return;
        }

        var netFrameworkPath = exports.getWinDir() +
                                    'Microsoft.Net\\' +
                                    exports.dotNetVersionMapper['processor'][processor] + '\\v' +
                                    exports.dotNetVersionMapper['version'][version] + '\\';
        return netFrameworkPath;
    };

})();<commit_msg>added nologo noshadow nothread nodots timeout and xml properties to nunit tasks<commit_after>(function () {

    var
        spawn = require('child_process').spawn,
        path = require('path'),
        fs = require('fs');

    var extend = function (obj) {
        var args = Array.prototype.slice.call(arguments);
        if (args.length == 0) return {};
        args.slice(1).forEach(function (source) {
            for (var prop in source)
                obj[prop] = source[prop];
        });
        return obj;
    };

    exports.exec = function (cmd, opts, callback) {
        var command = spawn(cmd, opts || [], { customFds: [0, 1, 2] });
        command.on('exit', function (code) { if (callback) callback(code); });
    };

    exports.msbuild = (function () {

        var defaults = {
            processor: 'x86',
            version: 'net2.0'
        };

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt.file) fail('msbuild failed - file required');

            if (!opt._exe) {
                if (!opt.processor) fail('msbuild failed - processor required');
                if (!opt.version) fail('msbuild failed - version required');
                opt._exe = exports.getDotNetVersionPath(opt.version, opt.processor) + 'MSBuild.exe';
            }

            args.push(opt.file);

            if (opt.targets)
                opts.targets.forEach(function (target) { args.push('/t:' + target); });
            if (opt.properties) {
                for (var key in opt.properties)
                    args.push('/p:' + key + '=' + opt.properties[key])
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('msbuild failed')
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.xunit = (function () {

        var defaults = {};

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt._exe) fail('xunit failed - _exe required');
            if (!opt.assembly) fail('xunit failed - assembly required');

            args.push(opt.assembly);

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('xunit failed')
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.nunit = (function () {

        var defaults = {};

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            if (!opt._exe) fail('nunit failed - _exe required');
            if (!opt.assemblies) failed('nunit failed - assemblies required');

            opt.assemblies.forEach(function (assembly) { args.push(assembly); });

            if(opt.nologo) args.push('/nologo');
            if(opt.noshadow) args.push('/noshadow');
            if(opt.nothread) args.push('/nothread');
            if(opt.nodots) args.push('/nodots');

            if(opt.timeout) args.push('/timeout=' + opt.timeout)

            if(opt.xml) args.push('/xml=' + opt.xml);

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nunit failed');
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        return task;

    })();

    exports.nuget = (function () {

        var defaults = {
            _exe: 'NuGet.exe'
        };

        var task = {};

        task.pack = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            args.push('pack');

            if (!opt._exe) fail('nuget.pack failed - _exe required');
            if (!opt.nuspec) fail('nuget.pack failed - nuspec required');
            args.push(opt.nuspec);

            if (opt.outputDirectory) {
                args.push('-OutputDirectory')
                args.push(opt.outputDirectory);
            }

            if (opt.verbose) args.push('-Verbose');

            if (opt.version) {
                args.push('-Version');
                args.push(opt.version);
            }

            if (opt.properties) {
                for (var key in opt.properties) {
                    args.push('-Properties');
                    args.push(key + '=' + opt.properties[key])
                }
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nuget.pack failed')
                callback ? callback(code) : complete();
            });
        };

        task.push = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                args = [];

            args.push('push');

            if (!opt._exe) fail('nuget.push failed - _exe required');
            if (!opt.package) fail('nuget.push failed - package required');
            args.push(opt.package);

            if (opt.apiKey) args.push(opt.apiKey);
            if (opt.createOnly) args.push('-CreateOnly');
            if (opt.source && opt.source !== '') {
                args.push('-Source');
                args.push(opt.source);
            }

            args.push.apply(args, opt._parameters || []);

            exports.exec(opt._exe, args, function (code) {
                if (code !== 0) fail('nuget.push failed');
                callback ? callback(code) : complete();
            });
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        };

        task.sources = {
            symbolSource: 'http://nuget.gw.symbolsource.org/Public/NuGet'
        };

        return task;

    })();

    exports.assemblyInfo = (function () {
        var defaults = {
            language: 'c#',
            namespaces: ['System.Reflection', 'System.Runtime.InteropServices']
        };

        var supportedLangagues = ['c#'];

        var task = function (opts, callback) {
            var opt = extend({}, defaults, opts),
                contents = '',
                assemblyValue;

            if (!opt.file) fail('assemblyInfo failed - file required');
            if (!opt.language) fail('assemblyInfo failed - language required');

            if (opt.language === 'c#') {
                if (opt.namespaces) {
                    opt.namespaces.forEach(function (ns) {
                        contents += 'using ' + ns + ';\r\n';
                    });
                }
                if (opt.assembly) {
                    for (var key in opt.assembly) {
                        assemblyValue = opt.assembly[key];
                        if (typeof assemblyValue === 'function') {
                            contents += assemblyValue();
                            continue;
                        }
                        contents += '[assembly: ' + key + '(';
                        if (typeof assemblyValue === 'boolean')
                            contents += assemblyValue ? 'true' : 'false';
                        else
                            contents += '\"' + assemblyValue + '\"';
                        contents += ')]\r\n';
                    }
                }
                fs.writeFileSync(opt.file, contents);
            } else {
                fail('assemblyInfo failed - unsupported language. choose ' + supportedLangagues);
            }

            callback ? callback(0) : complete();
        };

        task.setDefaults = function (opts) {
            extend(defaults, opts);
            return defaults;
        }

        return task;

    })();

    exports.getWinDir = function () {
        var winDir = process.env.WINDIR;
        return path.normalize((winDir.substr(-1) === '/' || winDir.substr(-1) === '\\') ? winDir : (winDir + '/')); // append / if absent
    };

    exports.dotNetVersionMapper = {
        'processor': {
            'x86': 'Framework',
            'x64': 'Framework64'
        },
        'version': {
            'net1.0': '1.0.3705',
            'net1.1': '1.1.4322',
            'net2.0': '2.0.50727',
            'net3.5': '3.5',
            'net4.0': '4.0.30319'
        }
    };

    exports.getDotNetVersionPath = function (version, processor) {

        // http://msdn.microsoft.com/en-us/library/dd414023.aspx
        // http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#Grouping_Assemblies_by_Framework_Version

        // make it processor instead of bit, just incase MS releases FrameworkARM ;)

        var actualProcessor = exports.dotNetVersionMapper['processor'][processor];
        var actualVersion = exports.dotNetVersionMapper['version'][version];
        if (typeof actualProcessor === 'undefined' || typeof actualVersion === 'undefined') {
            fail('specified .NET framework is not supported : ' + version + '(' + processor + ')');
            return;
        }

        var netFrameworkPath = exports.getWinDir() +
                                    'Microsoft.Net\\' +
                                    exports.dotNetVersionMapper['processor'][processor] + '\\v' +
                                    exports.dotNetVersionMapper['version'][version] + '\\';
        return netFrameworkPath;
    };

})();<|endoftext|>


<commit_before>'use strict';

const basics = require('./lib/basics');

const opinions = require('./lib/rules/opinions');
const conventions = require('./lib/rules/conventions');
const mistakes = require('./lib/rules/mistakes');

module.exports = Object.assign(basics, {
  rules: Object.assign({}, opinions, conventions, mistakes, {
    // Additional opinions

    // Additional conventions

    // Additional mistakes
    'node/no-unsupported-features': [2, { version: 6 }],
  })
});
console.log(module.exports.rules);
<commit_msg>fix: Remove console.log<commit_after>'use strict';

const basics = require('./lib/basics');

const opinions = require('./lib/rules/opinions');
const conventions = require('./lib/rules/conventions');
const mistakes = require('./lib/rules/mistakes');

module.exports = Object.assign(basics, {
  rules: Object.assign({}, opinions, conventions, mistakes, {
    // Additional opinions

    // Additional conventions

    // Additional mistakes
    'node/no-unsupported-features': [2, { version: 6 }],
  })
});
<|endoftext|>


<commit_before>/***********************************************************

 The information in this document is proprietary
 to VeriSign and the VeriSign Product Development.
 It may not be used, reproduced or disclosed without
 the written approval of the General Manager of
 VeriSign Product Development.

 PRIVILEGED AND CONFIDENTIAL
 VERISIGN PROPRIETARY INFORMATION
 REGISTRY SENSITIVE INFORMATION

 Copyright (c) 2013 VeriSign, Inc.  All rights reserved.

 ***********************************************************/

var config = require('./test-config');
var server = require("../server")
var should = require('should');
var request = require('supertest');
var mongoose = null;
var schemaManager = null;
var app = null;

describe('Schema API', function() {
    before(function(done) {
        server.startServer(config, function(expressApp) {
            mongoose = server.mongoose;
            schemaManager = require('../util/schema-manager')(mongoose);
            app = expressApp;
            done();
        });
    });

    after(function(done) {
        server.stopServer();
        mongoose.connection.db.dropDatabase();
        mongoose.connection.close();
        done();
    });

    describe("GET failure cases", function() {
        // no schemas..
        it("Should fail if type is not specified ", function(done) {
            request(app).get("/v1/api/schemas").expect(404, done);
        });
        it("Should fail if type does not exist ", function(done) {
            request(app).get("/v1/api/schemas/dne").expect(404, done);
        });
    });

    describe("POST schema", function() {
        it("Should create new schemas", function(done) {
            var jsData = JSON.parse("{        \
                \"name\":\"network_element\", \
                \"definition\": {             \
                    \"ne_type\": \"String\",  \
                    \"cid\":     \"String\",  \
                    \"ip\":      \"String\",  \
                    \"ip6\":     \"String\",  \
                    \"bgpip\":   \"String\",  \
                    \"bgpip6\":  \"String\",  \
                }.                            \
            }");
            request(app).post("/v1/api/schemas")
                .set('Content-Encoding', 'application/json')
                .write(jsData)
                .expect(200);
        });
    });
});
<commit_msg>Update test-api-schemas<commit_after>/***********************************************************

 The information in this document is proprietary
 to VeriSign and the VeriSign Product Development.
 It may not be used, reproduced or disclosed without
 the written approval of the General Manager of
 VeriSign Product Development.

 PRIVILEGED AND CONFIDENTIAL
 VERISIGN PROPRIETARY INFORMATION
 REGISTRY SENSITIVE INFORMATION

 Copyright (c) 2013 VeriSign, Inc.  All rights reserved.

 ***********************************************************/

var config = require('./test-config');
var server = require("../server")
var should = require('should');
var request = require('supertest');
var mongoose = null;
var schemaManager = null;
var app = null;

describe('Schema API', function() {
    before(function(done) {
        server.startServer(config, function(expressApp) {
            mongoose = server.mongoose;
            schemaManager = require('../util/schema-manager')(mongoose);
            app = expressApp;
            done();
        });
    });

    after(function(done) {
        server.stopServer();
        mongoose.connection.db.dropDatabase();
        mongoose.connection.close();
        done();
    });

    describe("GET failure cases", function() {
        // no schemas..
        it("Should fail if type is not specified ", function(done) {
            request(app).get("/v1/api/schemas").expect(404, done);
        });
        it("Should fail if type does not exist ", function(done) {
            request(app).get("/v1/api/schemas/dne").expect(404, done);
        });
    });

    describe("POST schema", function() {
        it("Should create new schemas", function(done) {
            var jsData = {
                "name":"network_element",
                "definition": {
                    "ne_type": "String",
                    "cid":     "String",
                    "ip":      "String",
                    "ip6":     "String",
                    "bgpip":   "String",
                    "bgpip6":  "String"
                }
            };
            request(app).post("/api/v1/schemas")
                .set('Content-Encoding', 'application/json')
                .send(jsData)
                .expect(201, done);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert,
    fluxex = require('..'),
    app = require('./testApp'),
    testStore = require('./testStore.js'),
    mixin = fluxex.mixin,
    sinon = require('sinon'),

getMixedComponent = function () {
    var App = new app(),
        ctx = function () {};

    ctx.prototype = mixin;
    ctx.prototype.context = {fluxex: App};
    ctx.prototype.props = {};

    return new ctx();
};

describe('fluxex.mixin', function () {
    it('._getContext() will return context', function (done) {
        assert.equal(true, getMixedComponent()._getContext() instanceof app);
        done();
    });

    it('._getInitScript() will return string', function (done) {
        assert.equal('string', typeof getMixedComponent()._getInitScript());
        done();
    });

    it('.getInitScript() will return string', function (done) {
        assert.equal('string', typeof getMixedComponent().getInitScript());
        assert.equal(true, getMixedComponent().getInitScript().length > 0);
        done();
    });

    it('.getInitScript() will return empty string when app already .initClient()', function (done) {
        var component = getMixedComponent();

        assert.equal(true, component.getInitScript().length > 0);

        // Simulate component._getContext().initClient() done
        component._getContext().inited = true;

        assert.equal(0, component.getInitScript().length);
        done();
    });

    it('.componentDidMount() will do nothing when no listenStores defined', function (done) {
        getMixedComponent().componentDidMount();
        done();
    });

    it('.componentDidMount() throws when no onStoreChange defined', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['test'];

        assert.throws(function () {
            C.componentDidMount();
        }, Error, 'the component should provide .onStoreChange() to handle .listenStores[] !');
        done();
    });

    it('.componentDidMount() will addChangeListener on specific store', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['sampleStore'];
        C.onStoreChange = function () {};

        C.getStore('sampleStore').addChangeListener = function () {
            done();
        };
        C.componentDidMount();
    });

    it('componentWillUnmount will removeChangeListener on specific store', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['sampleStore'];
        C.onStoreChange = function () {};

        C.getStore('sampleStore').removeChangeListener = function () {
            done();
        };
        C.componentWillUnmount();
    });

    it('.executeAction() will work well', function (done) {
        var C = getMixedComponent(),
            CX = C._getContext();

        sinon.stub(CX, 'executeAction');
        C.executeAction(123, 456);
        assert.deepEqual([123, 456], CX.executeAction.getCall(0).args);
        CX.executeAction.restore();
        done();
    });
});
<commit_msg>fix test ( .getInitScript() removed )<commit_after>'use strict';

var assert = require('chai').assert,
    fluxex = require('..'),
    app = require('./testApp'),
    testStore = require('./testStore.js'),
    mixin = fluxex.mixin,
    sinon = require('sinon'),

getMixedComponent = function () {
    var App = new app(),
        ctx = function () {};

    ctx.prototype = mixin;
    ctx.prototype.context = {fluxex: App};
    ctx.prototype.props = {};

    return new ctx();
};

describe('fluxex.mixin', function () {
    it('._getContext() will return context', function (done) {
        assert.equal(true, getMixedComponent()._getContext() instanceof app);
        done();
    });

    it('._getInitScript() will return string', function (done) {
        assert.equal('string', typeof getMixedComponent()._getInitScript());
        done();
    });

    it('.componentDidMount() will do nothing when no listenStores defined', function (done) {
        getMixedComponent().componentDidMount();
        done();
    });

    it('.componentDidMount() throws when no onStoreChange defined', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['test'];

        assert.throws(function () {
            C.componentDidMount();
        }, Error, 'the component should provide .onStoreChange() to handle .listenStores[] !');
        done();
    });

    it('.componentDidMount() will addChangeListener on specific store', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['sampleStore'];
        C.onStoreChange = function () {};

        C.getStore('sampleStore').addChangeListener = function () {
            done();
        };
        C.componentDidMount();
    });

    it('componentWillUnmount will removeChangeListener on specific store', function (done) {
        var C = getMixedComponent();
        C.listenStores = ['sampleStore'];
        C.onStoreChange = function () {};

        C.getStore('sampleStore').removeChangeListener = function () {
            done();
        };
        C.componentWillUnmount();
    });

    it('.executeAction() will work well', function (done) {
        var C = getMixedComponent(),
            CX = C._getContext();

        sinon.stub(CX, 'executeAction');
        C.executeAction(123, 456);
        assert.deepEqual([123, 456], CX.executeAction.getCall(0).args);
        CX.executeAction.restore();
        done();
    });
});
<|endoftext|>


<commit_before>import path from 'path';
import test from 'ava';
import isPromise from 'is-promise';
import outResolve from '../lib/out-resolve';

test('should return function', t => {
  t.true(typeof outResolve === 'function');
});

test('should return Promise', t => {
  t.true(isPromise(outResolve()));
});

test('only input should return file.ext', async t => {
  t.is(await outResolve('file.ext'), 'file.ext');
});

test('only input should return tmp/file.ext', async t => {
  t.is(await outResolve('tmp/file.ext'), 'tmp/file.ext');
});

test('input file and output file should return output.ext', async t => {
  t.is(await outResolve('file.ext', 'output.ext'), 'output.ext');
});

test('input file and output folder should return tmp/file.ext', async t => {
  t.is(await outResolve('file.ext', 'tmp'), path.normalize('tmp/file.ext'));
});

test('input files and output folder should return tmp/test/*.ext', async t => {
  t.is(await outResolve('tmp/test/*.ext', undefined), path.normalize('tmp/test/*.ext'));
});

test('input files and output file should return output.ext', async t => {
  t.is(await outResolve('test/*', 'output.ext'), 'output.ext');
});

test('input files and output file should return tmp/output.ext', async t => {
  t.is(await outResolve('test/*', 'tmp/output.ext'), 'tmp/output.ext');
});

<commit_msg>ci: normalize path for windows<commit_after>import path from 'path';
import test from 'ava';
import isPromise from 'is-promise';
import outResolve from '../lib/out-resolve';

test('should return function', t => {
  t.true(typeof outResolve === 'function');
});

test('should return Promise', t => {
  t.true(isPromise(outResolve()));
});

test('only input should return file.ext', async t => {
  t.is(await outResolve('file.ext'), 'file.ext');
});

test('only input should return tmp/file.ext', async t => {
  t.is(await outResolve('tmp/file.ext'), 'tmp/file.ext');
});

test('input file and output file should return output.ext', async t => {
  t.is(await outResolve('file.ext', 'output.ext'), 'output.ext');
});

test('input file and output folder should return tmp/file.ext', async t => {
  t.is(await outResolve('file.ext', 'tmp'), path.normalize('tmp/file.ext'));
});

test('input files and output folder should return tmp/test/*.ext', async t => {
  t.is(await outResolve(path.normalize('tmp/test/*.ext'), undefined), path.normalize('tmp/test/*.ext'));
});

test('input files and output file should return output.ext', async t => {
  t.is(await outResolve('test/*', 'output.ext'), 'output.ext');
});

test('input files and output file should return tmp/output.ext', async t => {
  t.is(await outResolve('test/*', 'tmp/output.ext'), 'tmp/output.ext');
});

<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        expect(ioPackage.common.authors).to.exist;
        if (Array.isArray(ioPackage.common.authors)) {
            expect(ioPackage.common.authors.length).to.not.be.equal(0);
            if (ioPackage.common.authors.length === 1) {
                expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            expect(ioPackage.common.authors).to.not.be.equal('my Name <my@email.com>');
        }

        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        expect(ioPackage.common.authors).to.exist;
        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length).to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors).to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('Testing for set authors field in io-package skipped because template adapter');
        }
        done();
    });
});
<|endoftext|>


<commit_before>/*global describe,it,before*/
/*eslint-disable max-nested-callbacks*/

'use strict';

var kss = require('../index.js'),
  testUtils = require('./testUtils');

describe('KssSection object API', function() {
  before(function(done) {
    var self = this;
    testUtils.traverseFixtures({mask: '*.less|*.css'}, function(styleguide) {
      self.styleguide = styleguide;
      done();
    });
  });

  /*eslint-disable guard-for-in,no-loop-func*/
  [
    'header',
    'description',
    'deprecated',
    'experimental',
    'reference',
    'depth',
    'encodeReferenceURI',
    'referenceURI',
    'modifiers',
    'firstModifier'
  ].forEach(function(method) {
    it('has ' + method + '() method', function() {
      (new kss.KssSection({})).should.have.method(method);
    });
  });
  /*eslint-enable guard-for-in,no-loop-func*/

  describe('.header()', function() {
    it('should return data.header', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.header().should.be.equal(section.data.header);
      });
      done();
    });
  });

  describe('.description()', function() {
    it('should return data.description', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.description().should.be.equal(section.data.description);
      });
      done();
    });
  });

  describe('.deprecated()', function() {
    it('should return data.deprecated', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.deprecated().should.be.equal(section.data.deprecated);
      });
      done();
    });
  });

  describe('.experimental()', function() {
    it('should return data.experimental', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.experimental().should.be.equal(section.data.experimental);
      });
      done();
    });
  });

  describe('.reference()', function() {
    it('should return data.reference', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.reference().should.be.equal(section.data.reference);
      });
      done();
    });
  });

  describe('.depth()', function() {
    it('should return data.depth', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.depth().should.be.equal(section.data.depth);
        section.depth().should.be.equal(section.reference().split(section.styleguide.referenceDelimiter).length);
        section.depth().should.be.a.Number();
      });
      done();
    });
  });

  describe('.weight()', function() {
    it('should return data.weight', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.weight().should.be.equal(section.data.weight ? section.data.weight : 0);
        section.weight().should.be.a.Number();
      });
      done();
    });
  });

  describe('.encodeReferenceURI()', function() {
    it('should return .referenceURI() when given reference()', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.encodeReferenceURI(section.reference()).should.be.equal(section.referenceURI());
      });
      done();
    });
  });

  describe('.referenceURI()', function() {
    it('should return data.referenceURI', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.referenceURI().should.be.equal(section.data.referenceURI);
        section.referenceURI().should.be.equal(section.encodeReferenceURI(section.reference()));
      });
      done();
    });
  });

  describe('.modifiers()', function() {
    it('should return data.modifiers', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers().should.be.equal(section.data.modifiers);
      });
      done();
    });

    it('should return array of KssModifier', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers().map(function(modifier) {
          modifier.should.be.instanceof(kss.KssModifier);
        });
      });
      done();
    });

    it('should return data.modifiers[n] given an integer as number or string', function(done) {
      this.styleguide.data.sections.map(function(section) {
        var i = 0;
        section.data.modifiers.map(function(modifier) {
          section.modifiers(i).should.be.eql(modifier);
          section.modifiers(i.toString()).should.be.eql(modifier);
          i++;
        });
      });
      done();
    });

    it('should return false if number is not found', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers(section.data.modifiers.length + 1).should.be.false();
      });
      done();
    });

    it('should search by name when given a string', function(done) {
      this.styleguide.data.sections.map(function(section) {
        var i, j, queries = ['.red', '.yellow', ':hover', ':disabled'],
          q = queries.length,
          l = section.data.modifiers.length;

        // Loop through each modifier.
        for (i = 0; i < l; i += 1) {
          // If a modifier is equal to a query, run the search.
          for (j = 0; j < q; j += 1) {
            if (section.data.modifiers[i].data.name === queries[j]) {
              section.modifiers(queries[j]).should.be.eql(section.data.modifiers[i]);
            }
          }
        }
      });
      done();
    });

    it('should return false if name not found', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers('__should_not_find___').should.be.false();
      });
      done();
    });
  });

  describe('.firstModifier()', function() {
    it('should return data.modifiers[0]', function(done) {
      this.styleguide.data.sections.map(function(section) {
        if (section.data.modifiers.length) {
          section.firstModifier().should.be.equal(section.modifiers(0));
        } else {
          section.firstModifier().should.be.false();
        }
      });
      done();
    });
  });
});
<commit_msg>Add tests for KssSection.parameters().<commit_after>/*global describe,it,before*/
/*eslint-disable max-nested-callbacks*/

'use strict';

var kss = require('../index.js'),
  testUtils = require('./testUtils');

describe('KssSection object API', function() {
  before(function(done) {
    var self = this;
    testUtils.traverseFixtures({mask: '*.less|*.css'}, function(styleguide) {
      self.styleguide = styleguide;
      done();
    });
  });

  /*eslint-disable guard-for-in,no-loop-func*/
  [
    'header',
    'description',
    'deprecated',
    'experimental',
    'reference',
    'depth',
    'encodeReferenceURI',
    'referenceURI',
    'modifiers',
    'firstModifier',
    'parameters'
  ].forEach(function(method) {
    it('has ' + method + '() method', function() {
      (new kss.KssSection({})).should.have.method(method);
    });
  });
  /*eslint-enable guard-for-in,no-loop-func*/

  describe('.header()', function() {
    it('should return data.header', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.header().should.be.equal(section.data.header);
      });
      done();
    });
  });

  describe('.description()', function() {
    it('should return data.description', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.description().should.be.equal(section.data.description);
      });
      done();
    });
  });

  describe('.deprecated()', function() {
    it('should return data.deprecated', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.deprecated().should.be.equal(section.data.deprecated);
      });
      done();
    });
  });

  describe('.experimental()', function() {
    it('should return data.experimental', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.experimental().should.be.equal(section.data.experimental);
      });
      done();
    });
  });

  describe('.reference()', function() {
    it('should return data.reference', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.reference().should.be.equal(section.data.reference);
      });
      done();
    });
  });

  describe('.depth()', function() {
    it('should return data.depth', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.depth().should.be.equal(section.data.depth);
        section.depth().should.be.equal(section.reference().split(section.styleguide.referenceDelimiter).length);
        section.depth().should.be.a.Number();
      });
      done();
    });
  });

  describe('.weight()', function() {
    it('should return data.weight', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.weight().should.be.equal(section.data.weight ? section.data.weight : 0);
        section.weight().should.be.a.Number();
      });
      done();
    });
  });

  describe('.encodeReferenceURI()', function() {
    it('should return .referenceURI() when given reference()', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.encodeReferenceURI(section.reference()).should.be.equal(section.referenceURI());
      });
      done();
    });
  });

  describe('.referenceURI()', function() {
    it('should return data.referenceURI', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.referenceURI().should.be.equal(section.data.referenceURI);
        section.referenceURI().should.be.equal(section.encodeReferenceURI(section.reference()));
      });
      done();
    });
  });

  describe('.modifiers()', function() {
    it('should return data.modifiers', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers().should.be.equal(section.data.modifiers);
      });
      done();
    });

    it('should return array of KssModifier', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers().map(function(modifier) {
          modifier.should.be.instanceof(kss.KssModifier);
        });
      });
      done();
    });

    it('should return data.modifiers[n] given an integer as number or string', function(done) {
      this.styleguide.data.sections.map(function(section) {
        var i = 0;
        section.data.modifiers.map(function(modifier) {
          section.modifiers(i).should.be.eql(modifier);
          section.modifiers(i.toString()).should.be.eql(modifier);
          i++;
        });
      });
      done();
    });

    it('should return false if number is not found', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers(section.data.modifiers.length + 1).should.be.false();
      });
      done();
    });

    it('should search by name when given a string', function(done) {
      this.styleguide.data.sections.map(function(section) {
        var i, j, queries = ['.red', '.yellow', ':hover', ':disabled'],
          q = queries.length,
          l = section.data.modifiers.length;

        // Loop through each modifier.
        for (i = 0; i < l; i += 1) {
          // If a modifier is equal to a query, run the search.
          for (j = 0; j < q; j += 1) {
            if (section.data.modifiers[i].data.name === queries[j]) {
              section.modifiers(queries[j]).should.be.eql(section.data.modifiers[i]);
            }
          }
        }
      });
      done();
    });

    it('should return false if name not found', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.modifiers('__should_not_find___').should.be.false();
      });
      done();
    });
  });

  describe('.firstModifier()', function() {
    it('should return data.modifiers[0]', function(done) {
      this.styleguide.data.sections.map(function(section) {
        if (section.data.modifiers.length) {
          section.firstModifier().should.be.equal(section.modifiers(0));
        } else {
          section.firstModifier().should.be.false();
        }
      });
      done();
    });
  });

  describe('.parameters()', function() {
    it('should return data.parameters', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.parameters().should.be.equal(section.data.parameters);
      });
      done();
    });

    it('should return array of KssParameter', function(done) {
      this.styleguide.data.sections.map(function(section) {
        section.parameters().map(function(parameter) {
          parameter.should.be.instanceof(kss.KssParameter);
        });
      });
      done();
    });
  });
});
<|endoftext|>