<commit_before>var server = require('http').createServer(handler),
	io = require('socket.io').listen(server),
	fs = require('fs'),
	url = require('url'),
	irc = require('irc');

var HOST = 'localhost',
    PORT = 12445;

// HTTP handler
function handler(req, res) {
	path = url.parse(req.url).pathname;
	if (path === '/')  path = '/index.html'

	// Set content type
	var type = '';
	if (path.substr(-3) === '.js')
		type = 'text/javascript';
	else if (path.substr(-4) === '.css')
		type = 'text/css';
    else if (path.substr(-4) === '.png')
        type = 'image/png';
	else
		type = 'text/html';

 	fs.readFile(__dirname + path, function (err, data) {
	    if (err) {
	     	res.writeHead(500);
	     	return res.end('Error loading index.html');
	    }

        res.writeHead(200, {'Content-Type': type});
        res.end(data);
    });
}

server.listen(PORT, HOST);
console.log('Server running at http://' + HOST + ':' + PORT);

// Socket.IO
io.sockets.on('connection', function(socket) {

    // Events to signal TO the front-end
    var events = {
        'join': ['channel', 'nick'],
        'part': ['channel', 'nick'],
        'nick': ['oldNick', 'newNick', 'channels'],
        'names': ['channel', 'nicks'],
        'message': ['from', 'to', 'text'],
        'pm': ['nick', 'text'],
        'motd': ['motd'],
        'error': ['message']
    };

    socket.on('connect', function(data) {
        var client = new irc.Client(data.server, data.nick, {
            channels: data.channels
        });

        // Socket events sent FROM the front-end
        socket.on('join', function(name) { client.join(name); });
        socket.on('part', function(name) { client.part(name); });
        socket.on('say', function(data) { client.say(data.target, data.message); });
        socket.on('command', function(text) { console.log(text); client.send(text); });
        socket.on('disconnect', function() { client.disconnect(); });

        // Add a listener on client for the given event & argument names
        var activateListener = function(event, argNames) {
            client.addListener(event, function() {
                console.log('Event ' + event + ' sent');
                // Associate specified names with callback arguments
                // to avoid getting tripped up on the other side
                var callbackArgs = arguments;
                args = {};
                argNames.forEach(function(arg, index) {
                    args[arg] = callbackArgs[index];
                });
                console.log(args);
                socket.emit(event, args);
            });
        };

        for (var event in events) { activateListener(event, events[event]); }
    });
});<commit_msg>Big simplification of server.js thanks to express.js. No longer manually defining static types and such.<commit_after>var express = require('express'),
    app = express.createServer(),
	io = require('socket.io').listen(app),
	irc = require('irc');

app.configure(function() {
    app.use(express.static(__dirname + '/'));
    app.use(express.static(__dirname + '/js'));
    app.use(express.static(__dirname + '/images'));
    app.listen(8337);
});

app.configure('production', function() {
    app.listen(12445);
});

console.log('Express server started on port %s', app.address().port);

// Socket.IO
io.sockets.on('connection', function(socket) {

    // Events to signal TO the front-end
    var events = {
        'join': ['channel', 'nick'],
        'part': ['channel', 'nick'],
        'nick': ['oldNick', 'newNick', 'channels'],
        'names': ['channel', 'nicks'],
        'message': ['from', 'to', 'text'],
        'pm': ['nick', 'text'],
        'motd': ['motd'],
        'error': ['message']
    };

    socket.on('connect', function(data) {
        var client = new irc.Client(data.server, data.nick, {
            channels: data.channels
        });

        // Socket events sent FROM the front-end
        socket.on('join', function(name) { client.join(name); });
        socket.on('part', function(name) { client.part(name); });
        socket.on('say', function(data) { client.say(data.target, data.message); });
        socket.on('command', function(text) { console.log(text); client.send(text); });
        socket.on('disconnect', function() { client.disconnect(); });

        // Add a listener on client for the given event & argument names
        var activateListener = function(event, argNames) {
            client.addListener(event, function() {
                console.log('Event ' + event + ' sent');
                // Associate specified names with callback arguments
                // to avoid getting tripped up on the other side
                var callbackArgs = arguments;
                args = {};
                argNames.forEach(function(arg, index) {
                    args[arg] = callbackArgs[index];
                });
                console.log(args);
                socket.emit(event, args);
            });
        };

        for (var event in events) { activateListener(event, events[event]); }
    });
});<|endoftext|>


<commit_before>var DEFAULTPATH = __dirname+"/public/downloads/";
// Setup basic express server
var auth = require('http-auth');
var basic = auth.basic({
	realm: "Protected area. Please disperse !",
	file: __dirname+"/.htpasswd"
});

//file management
var fs = require('fs');
fs.writeFile("log.txt", "",'utf-8', function(err){
	if(err) throw err;
});

var cp = require('child_process');

//setup http server
var express = require('express');
var app = express();
var server = require('http').createServer(basic,app);
var port = process.env.PORT || 80;

server.listen(port, function () {
  log('Server listening at port '+port);
});
// Routing
app.use(express.static(__dirname + '/public'));

//socket io
var io = require('socket.io')(server);

//webtorrent
var WebTorrent = require('webtorrent');
var client = new WebTorrent();

var parseTorrent = require('parse-torrent');

var TorrentUrlToChild = {};
var TorrentHashToChild = {};
var TorrentWaitList = [];

io.on('connection', function (socket) {

	socket.on('ready',function(){
		for(var key in TorrentHashToChild){
			TorrentHashToChild[key].send({'type':"info"});
		}

		socket.on('download-t',function(url){
			startTorrent(url);
		});
	});

	socket.on('list-d',function(dir){
		fs.readdir(DEFAULTPATH+dir, function(err, files){
			if(err) return log(err);
	    	var list = {};
	    	if(files.length > 0){
		    	files.forEach(function(file){
		    		stats = fs.statSync(DEFAULTPATH+dir+file);
		    		if(stats.isFile()){
		    			list[file] = stats;
		    		} else {
		    			stats.size = sizeRecursif(DEFAULTPATH+dir+file);
		    			list[file] = stats;
		    		}
		    		list[file].isfile = stats.isFile();
		    		list[file].isdir = stats.isDirectory();

		    		if(Object.keys(list).length == files.length){
		    			socket.emit('list-d',list);
		    		}
		    	});
		    } else {
		    	socket.emit('list-d',{});
		    }
		});
	});

	socket.on('remove-t',function(hash){
		log('Remove torrent: '+hash);
		TorrentHashToChild[hash].send({'type': "remove"});
		socket.emit('finish-t',hash);
	});

	socket.on('remove-d',function(file){
		log("Remove file: "+file);
		fs.stat(DEFAULTPATH+file, function(err, stats){
			if(err) return log(err);
			if(stats.isDirectory()){
				removeRecursif(DEFAULTPATH+file);
				socket.emit('update-d');
			} else {
				fs.unlink(DEFAULTPATH+file, function(err){
  					if(err) return log(err);
					socket.emit('update-d');
				});
			}
		});
	});

	socket.on('rename-d',function(data){
		log("Rename: "+data.oldname+" In: "+data.newname);
		fs.rename(DEFAULTPATH+data.path+"/"+data.oldname, DEFAULTPATH+data.path+"/"+data.newname, function(err){
			if(err) return log(err);
			socket.emit('update-d');
		});
	});

	socket.on('mkdir',function(data){
		log('Mkdir: '+data.path+"/"+data.name);
		fs.mkdir(DEFAULTPATH+data.path+"/"+data.name, function(){
			socket.emit('update-d');
		});
	});

	socket.on('mv',function(data){
		fs.rename(DEFAULTPATH+data.path+data.file, DEFAULTPATH+data.path+data.folder+"/"+data.file,function(err){
			if(err) return log(err);
			socket.emit('update-d');
		});
	});
});

function log(text){
	console.log(text);
	fs.appendFile("log.txt", text+"\n", 'utf8', function(err){
		if(err) throw err;
	});
}

function startTorrent(url){
	log('Trying to download: '+url);

	//evite de lancer deux fois le meme torrent
	if(TorrentUrlToChild[url] == null){
		//Si trop de torrent en cours
		if(Object.keys(TorrentUrlToChild).length < 3){
			var n = cp.fork(__dirname + '/tclient.js');
			TorrentUrlToChild[url] = n;
			io.sockets.emit('start-t');
			n.on('message',function(data){
				switch(data.type){
					case 'finish':
						io.sockets.emit('finish-t',data.hash);
						n.kill('SIGHUP');
						delete TorrentUrlToChild[url];
						delete TorrentHashToChild[data.hash];
						fs.renameSync(__dirname+"/public/torrents/"+data.name, DEFAULTPATH+data.name);
						//Relance un torrent si il y en a en attente
						if(TorrentWaitList.length > 0){
							var newUrl = TorrentWaitList[0];
							startTorrent(newUrl);
							TorrentWaitList.shift();
						}
						break;
					case 'info':
						io.sockets.emit('list-t',data.torrent);
						TorrentHashToChild[data.torrent.hash] = n;
						break;
					case 'remove':
						io.sockets.emit('finish-t',data.hash);
						n.kill('SIGHUP');
						delete TorrentUrlToChild[url];
						delete TorrentHashToChild[data.hash];
						fs.unlinkSync(__dirname+"/public/torrents/"+data.name);
						//Relance un torrent si il y en a en attente
						if(TorrentWaitList.length > 0){
							var newUrl = TorrentWaitList[0];
							startTorrent(newUrl);
							TorrentWaitList.shift();
						}
				}
			});

			n.send({'type': "download", 'torrent': url});

			} else {
				log("Too much client. Adding torrent to the waitlist.")
				//On push dans la liste d'attente
				if(TorrentWaitList.indexOf(url) == -1)
					TorrentWaitList.push(url);
			}
		} else {
			log("Torrent is already downloading.");
		}
	}

function removeRecursif(path){
	if(fs.existsSync(path)) {
		fs.readdirSync(path).forEach(function(file,index){
	    	var curPath = path + "/" + file;
	    	if(fs.lstatSync(curPath).isDirectory()) { // recurse
	        	removeRecursif(curPath);
	     	} else { // delete file
	        	fs.unlinkSync(curPath);
	      	}
	    });
	    fs.rmdirSync(path);
  	}
}

function sizeRecursif(path){
	var size = 0;
	if(fs.existsSync(path)) {
		fs.readdirSync(path).forEach(function(file,index){
	    	var curPath = path + "/" + file;
	    	if(fs.lstatSync(curPath).isDirectory()) { // recurse
	        	sizeRecursif(curPath);
	     	} else { // read size
	        	size += fs.statSync(curPath).size;
	      	}
	    });
	    return size;
  	}
}
<commit_msg>tring speed up expresse speed<commit_after>var DEFAULTPATH = __dirname+"/public/downloads/";
// Setup basic express server
var auth = require('http-auth');
var basic = auth.basic({
	realm: "Protected area. Please disperse !",
	file: __dirname+"/.htpasswd"
});

//file management
var fs = require('fs');
fs.writeFile("log.txt", "",'utf-8', function(err){
	if(err) throw err;
});

var cp = require('child_process');

//setup http server
var express = require('express');
var app = express();
var http = require('http')
http.globalAgent.maxSockets = Infinity;
var server = http.createServer(basic,app);

var port = process.env.PORT || 80;

server.listen(port, function () {
  log('Server listening at port '+port);
});
// Routing
app.use(express.static(__dirname + '/public'));

//socket io
var io = require('socket.io')(server);

//webtorrent
var WebTorrent = require('webtorrent');
var client = new WebTorrent();

var parseTorrent = require('parse-torrent');

var TorrentUrlToChild = {};
var TorrentHashToChild = {};
var TorrentWaitList = [];

io.on('connection', function (socket) {

	socket.on('ready',function(){
		for(var key in TorrentHashToChild){
			TorrentHashToChild[key].send({'type':"info"});
		}

		socket.on('download-t',function(url){
			startTorrent(url);
		});
	});

	socket.on('list-d',function(dir){
		fs.readdir(DEFAULTPATH+dir, function(err, files){
			if(err) return log(err);
	    	var list = {};
	    	if(files.length > 0){
		    	files.forEach(function(file){
		    		stats = fs.statSync(DEFAULTPATH+dir+file);
		    		if(stats.isFile()){
		    			list[file] = stats;
		    		} else {
		    			stats.size = sizeRecursif(DEFAULTPATH+dir+file);
		    			list[file] = stats;
		    		}
		    		list[file].isfile = stats.isFile();
		    		list[file].isdir = stats.isDirectory();

		    		if(Object.keys(list).length == files.length){
		    			socket.emit('list-d',list);
		    		}
		    	});
		    } else {
		    	socket.emit('list-d',{});
		    }
		});
	});

	socket.on('remove-t',function(hash){
		log('Remove torrent: '+hash);
		TorrentHashToChild[hash].send({'type': "remove"});
		socket.emit('finish-t',hash);
	});

	socket.on('remove-d',function(file){
		log("Remove file: "+file);
		fs.stat(DEFAULTPATH+file, function(err, stats){
			if(err) return log(err);
			if(stats.isDirectory()){
				removeRecursif(DEFAULTPATH+file);
				socket.emit('update-d');
			} else {
				fs.unlink(DEFAULTPATH+file, function(err){
  					if(err) return log(err);
					socket.emit('update-d');
				});
			}
		});
	});

	socket.on('rename-d',function(data){
		log("Rename: "+data.oldname+" In: "+data.newname);
		fs.rename(DEFAULTPATH+data.path+"/"+data.oldname, DEFAULTPATH+data.path+"/"+data.newname, function(err){
			if(err) return log(err);
			socket.emit('update-d');
		});
	});

	socket.on('mkdir',function(data){
		log('Mkdir: '+data.path+"/"+data.name);
		fs.mkdir(DEFAULTPATH+data.path+"/"+data.name, function(){
			socket.emit('update-d');
		});
	});

	socket.on('mv',function(data){
		fs.rename(DEFAULTPATH+data.path+data.file, DEFAULTPATH+data.path+data.folder+"/"+data.file,function(err){
			if(err) return log(err);
			socket.emit('update-d');
		});
	});
});

function log(text){
	console.log(text);
	fs.appendFile("log.txt", text+"\n", 'utf8', function(err){
		if(err) throw err;
	});
}

function startTorrent(url){
	log('Trying to download: '+url);

	//evite de lancer deux fois le meme torrent
	if(TorrentUrlToChild[url] == null){
		//Si trop de torrent en cours
		if(Object.keys(TorrentUrlToChild).length < 3){
			var n = cp.fork(__dirname + '/tclient.js');
			TorrentUrlToChild[url] = n;
			io.sockets.emit('start-t');
			n.on('message',function(data){
				switch(data.type){
					case 'finish':
						io.sockets.emit('finish-t',data.hash);
						n.kill('SIGHUP');
						delete TorrentUrlToChild[url];
						delete TorrentHashToChild[data.hash];
						fs.renameSync(__dirname+"/public/torrents/"+data.name, DEFAULTPATH+data.name);
						//Relance un torrent si il y en a en attente
						if(TorrentWaitList.length > 0){
							var newUrl = TorrentWaitList[0];
							startTorrent(newUrl);
							TorrentWaitList.shift();
						}
						break;
					case 'info':
						io.sockets.emit('list-t',data.torrent);
						TorrentHashToChild[data.torrent.hash] = n;
						break;
					case 'remove':
						io.sockets.emit('finish-t',data.hash);
						n.kill('SIGHUP');
						delete TorrentUrlToChild[url];
						delete TorrentHashToChild[data.hash];
						fs.unlinkSync(__dirname+"/public/torrents/"+data.name);
						//Relance un torrent si il y en a en attente
						if(TorrentWaitList.length > 0){
							var newUrl = TorrentWaitList[0];
							startTorrent(newUrl);
							TorrentWaitList.shift();
						}
				}
			});

			n.send({'type': "download", 'torrent': url});

			} else {
				log("Too much client. Adding torrent to the waitlist.")
				//On push dans la liste d'attente
				if(TorrentWaitList.indexOf(url) == -1)
					TorrentWaitList.push(url);
			}
		} else {
			log("Torrent is already downloading.");
		}
	}

function removeRecursif(path){
	if(fs.existsSync(path)) {
		fs.readdirSync(path).forEach(function(file,index){
	    	var curPath = path + "/" + file;
	    	if(fs.lstatSync(curPath).isDirectory()) { // recurse
	        	removeRecursif(curPath);
	     	} else { // delete file
	        	fs.unlinkSync(curPath);
	      	}
	    });
	    fs.rmdirSync(path);
  	}
}

function sizeRecursif(path){
	var size = 0;
	if(fs.existsSync(path)) {
		fs.readdirSync(path).forEach(function(file,index){
	    	var curPath = path + "/" + file;
	    	if(fs.lstatSync(curPath).isDirectory()) { // recurse
	        	sizeRecursif(curPath);
	     	} else { // read size
	        	size += fs.statSync(curPath).size;
	      	}
	    });
	    return size;
  	}
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.use(express.static('public'));
app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'),function(){
	console.log('app is running at port 5000');
});
<commit_msg>Delete server.js<commit_after><|endoftext|>


<commit_before>var express = require('express')
var bodyParser = require("body-parser");
var lcbo = require('./codybo.js');
var server = express()

server.set('PORT', (process.env.PORT || 5000));

server.use(express.static(__dirname + '/public'));
server.use(bodyParser.json());

server.get("/echo/:text", function(req, res) {
	res.send(req.params.text);
})

server.get("/lcbo/:storeId", function(req,res) {
	lcbo.getSalesAtStore(req.params.storeId).then((json) => res.send(json));
})

server.get("/lcbo/nearby", function(req,res) {
	res.send(req.params.lat);
	// lcbo.getStoresNearby(req.params.lat,req.params.lon).then((json) => res.send(json));
})

var port = server.get('PORT');
server.listen(port, function() {
	console.log('codybo is running on port', port);
});<commit_msg>use req.query to access url parameter<commit_after>var express = require('express')
var bodyParser = require("body-parser");
var lcbo = require('./codybo.js');
var server = express()

server.set('PORT', (process.env.PORT || 5000));

server.use(express.static(__dirname + '/public'));
server.use(bodyParser.json());

server.get("/echo/:text", function(req, res) {
	res.send(req.params.text);
})

server.get("/lcbo/:storeId", function(req,res) {
	lcbo.getSalesAtStore(req.params.storeId).then((json) => res.send(json));
})

server.get("/lcbo/nearby", function(req,res) {
	res.send(req.query.lat);
	// lcbo.getStoresNearby(req.query.lat,req.query.lon).then((json) => res.send(json));
})

var port = server.get('PORT');
server.listen(port, function() {
	console.log('codybo is running on port', port);
});<|endoftext|>


<commit_before>'use strict';

// only pkg-ed run
if (!process.pkg) {
  console.log('ok');
  return;
}

var require2 = require('require-uncached');

try {
  require2('async');
} catch (error) {
  if (error.message.indexOf('Pkg') >= 0) {
    console.log('ok');
  }
}
<commit_msg>fix 'require-uncached' after 'callsites'<commit_after>'use strict';

var require2 = require('require-uncached');
var depsOfPkg = require('../../../package.json').dependencies;
var anyDep = Object.keys(depsOfPkg)[0];
var result = require2(anyDep);
if (typeof result !== 'undefined') {
  console.log('ok');
}
<|endoftext|>


<commit_before>const temp = require('temp')
const fs = require('fs')
const path = require('path')
const childProcess = require('child_process')
const GitHubApi = require('github')
const request = require('request')
const assert = require('assert')
const rootPackageJson = require('../package.json')

if (!process.env.ELECTRON_NPM_OTP) {
  console.error('Please set ELECTRON_NPM_OTP')
  process.exit(1)
}

const github = new GitHubApi({
  // debug: true,
  headers: { 'User-Agent': 'electron-npm-publisher' },
  followRedirects: false
})

let tempDir
temp.track()   // track and cleanup files at exit

const files = [
  'cli.js',
  'index.js',
  'install.js',
  'package.json',
  'README.md',
  'LICENSE'
]

const jsonFields = [
  'name',
  'version',
  'repository',
  'description',
  'license',
  'author',
  'keywords'
]

let npmTag = ''

new Promise((resolve, reject) => {
  temp.mkdir('electron-npm', (err, dirPath) => {
    if (err) {
      reject(err)
    } else {
      resolve(dirPath)
    }
  })
})
.then((dirPath) => {
  tempDir = dirPath
  // copy files from `/npm` to temp directory
  files.forEach((name) => {
    const noThirdSegment = name === 'README.md' || name === 'LICENSE'
    fs.writeFileSync(
      path.join(tempDir, name),
      fs.readFileSync(path.join(__dirname, '..', noThirdSegment ? '' : 'npm', name))
    )
  })
  // copy from root package.json to temp/package.json
  const packageJson = require(path.join(tempDir, 'package.json'))
  jsonFields.forEach((fieldName) => {
    packageJson[fieldName] = rootPackageJson[fieldName]
  })
  fs.writeFileSync(
    path.join(tempDir, 'package.json'),
    JSON.stringify(packageJson, null, 2)
  )

  return github.repos.getReleases({
    owner: 'electron',
    repo: rootPackageJson.version.indexOf('nightly') > 0 ? 'nightlies' : 'electron'
  })
})
.then((releases) => {
  // download electron.d.ts from release
  const release = releases.data.find(
    (release) => release.tag_name === `v${rootPackageJson.version}`
  )
  if (!release) {
    throw new Error(`cannot find release with tag v${rootPackageJson.version}`)
  }
  return release
})
.then((release) => {
  const tsdAsset = release.assets.find((asset) => asset.name === 'electron.d.ts')
  if (!tsdAsset) {
    throw new Error(`cannot find electron.d.ts from v${rootPackageJson.version} release assets`)
  }
  return new Promise((resolve, reject) => {
    request.get({
      url: tsdAsset.url,
      headers: {
        'accept': 'application/octet-stream',
        'user-agent': 'electron-npm-publisher'
      }
    }, (err, response, body) => {
      if (err || response.statusCode !== 200) {
        reject(err || new Error('Cannot download electron.d.ts'))
      } else {
        fs.writeFileSync(path.join(tempDir, 'electron.d.ts'), body)
        resolve(release)
      }
    })
  })
})
.then((release) => {
  npmTag = release.prerelease ? 'beta' : 'latest'
})
.then(() => childProcess.execSync('npm pack', { cwd: tempDir }))
.then(() => {
  // test that the package can install electron prebuilt from github release
  const tarballPath = path.join(tempDir, `${rootPackageJson.name}-${rootPackageJson.version}.tgz`)
  return new Promise((resolve, reject) => {
    childProcess.execSync(`npm install ${tarballPath} --force --silent`, {
      env: Object.assign({}, process.env, { electron_config_cache: tempDir }),
      cwd: tempDir
    })
    const checkVersion = childProcess.execSync(`${path.join(tempDir, 'node_modules', '.bin', 'electron')} -v`)
    assert.ok((`v${rootPackageJson.version}`.indexOf(checkVersion.toString().trim()) === 0), `Version is correct`)
    resolve(tarballPath)
  })
})
.then((tarballPath) => childProcess.execSync(`npm publish ${tarballPath} --tag ${npmTag} --otp=${process.env.ELECTRON_NPM_OTP}`))
.catch((err) => {
  console.error(`Error: ${err}`)
  process.exit(1)
})
<commit_msg>chore: fix npm nightly dist-tag (#14155)<commit_after>const temp = require('temp')
const fs = require('fs')
const path = require('path')
const childProcess = require('child_process')
const GitHubApi = require('github')
const request = require('request')
const assert = require('assert')
const rootPackageJson = require('../package.json')

if (!process.env.ELECTRON_NPM_OTP) {
  console.error('Please set ELECTRON_NPM_OTP')
  process.exit(1)
}

const github = new GitHubApi({
  // debug: true,
  headers: { 'User-Agent': 'electron-npm-publisher' },
  followRedirects: false
})

let tempDir
temp.track()   // track and cleanup files at exit

const files = [
  'cli.js',
  'index.js',
  'install.js',
  'package.json',
  'README.md',
  'LICENSE'
]

const jsonFields = [
  'name',
  'version',
  'repository',
  'description',
  'license',
  'author',
  'keywords'
]

let npmTag = ''

new Promise((resolve, reject) => {
  temp.mkdir('electron-npm', (err, dirPath) => {
    if (err) {
      reject(err)
    } else {
      resolve(dirPath)
    }
  })
})
.then((dirPath) => {
  tempDir = dirPath
  // copy files from `/npm` to temp directory
  files.forEach((name) => {
    const noThirdSegment = name === 'README.md' || name === 'LICENSE'
    fs.writeFileSync(
      path.join(tempDir, name),
      fs.readFileSync(path.join(__dirname, '..', noThirdSegment ? '' : 'npm', name))
    )
  })
  // copy from root package.json to temp/package.json
  const packageJson = require(path.join(tempDir, 'package.json'))
  jsonFields.forEach((fieldName) => {
    packageJson[fieldName] = rootPackageJson[fieldName]
  })
  fs.writeFileSync(
    path.join(tempDir, 'package.json'),
    JSON.stringify(packageJson, null, 2)
  )

  return github.repos.getReleases({
    owner: 'electron',
    repo: rootPackageJson.version.indexOf('nightly') > 0 ? 'nightlies' : 'electron'
  })
})
.then((releases) => {
  // download electron.d.ts from release
  const release = releases.data.find(
    (release) => release.tag_name === `v${rootPackageJson.version}`
  )
  if (!release) {
    throw new Error(`cannot find release with tag v${rootPackageJson.version}`)
  }
  return release
})
.then((release) => {
  const tsdAsset = release.assets.find((asset) => asset.name === 'electron.d.ts')
  if (!tsdAsset) {
    throw new Error(`cannot find electron.d.ts from v${rootPackageJson.version} release assets`)
  }
  return new Promise((resolve, reject) => {
    request.get({
      url: tsdAsset.url,
      headers: {
        'accept': 'application/octet-stream',
        'user-agent': 'electron-npm-publisher'
      }
    }, (err, response, body) => {
      if (err || response.statusCode !== 200) {
        reject(err || new Error('Cannot download electron.d.ts'))
      } else {
        fs.writeFileSync(path.join(tempDir, 'electron.d.ts'), body)
        resolve(release)
      }
    })
  })
})
.then((release) => {
  if (release.tag_name.indexOf('nightly') > 0) {
    npmTag = 'nightly'
  } else {
    npmTag = release.prerelease ? 'beta' : 'latest'
  }
})
.then(() => childProcess.execSync('npm pack', { cwd: tempDir }))
.then(() => {
  // test that the package can install electron prebuilt from github release
  const tarballPath = path.join(tempDir, `${rootPackageJson.name}-${rootPackageJson.version}.tgz`)
  return new Promise((resolve, reject) => {
    childProcess.execSync(`npm install ${tarballPath} --force --silent`, {
      env: Object.assign({}, process.env, { electron_config_cache: tempDir }),
      cwd: tempDir
    })
    const checkVersion = childProcess.execSync(`${path.join(tempDir, 'node_modules', '.bin', 'electron')} -v`)
    assert.ok((`v${rootPackageJson.version}`.indexOf(checkVersion.toString().trim()) === 0), `Version is correct`)
    resolve(tarballPath)
  })
})
.then((tarballPath) => childProcess.execSync(`npm publish ${tarballPath} --tag ${npmTag} --otp=${process.env.ELECTRON_NPM_OTP}`))
.catch((err) => {
  console.error(`Error: ${err}`)
  process.exit(1)
})
<|endoftext|>


<commit_before>var express = require('express'),
    fs = require('fs'),
    app = express(),
    _ = require('underscore'),
    urlparser = require("url");

// Fetching file by this function instead of internal pandoc method
// because of pandoc can't fetch files using https protocol
function getFile(url, cb) {

  var parts = urlparser.parse(url),
      protocol;

  // quick workaround
  // can be done better?
  if (parts.protocol === 'http:'){
    protocol = require('http');
  } else if(parts.protocol === 'https:') {
    protocol = require('https');
  }

  protocol.get(url, function(res) {
    var result = "";
    res.on('data', function ( d ) {
      result += d.toString();
    });
    res.on('end', function() {
    	console.log('processing')
      cb(null,result);
    });
  }).on('error', function( e ) {
    cb(err);
  });
}

// Spawn pandoc child process, run callback
// added some arguments for more capabilities
function toPandoc(url, from, to, cb) {
	var spawn = require('child_process').spawn,
    	args = [ '-f', from, '-t', to],
    	result = '',
    	error = '',
      child;
	getFile(url,function(err,res){
  	child = spawn('pandoc',args);
  	child.stdout.on('data', function (data) {
    	result += data;
  	});
  	child.stderr.on('data', function (data) {
    	error += data;
  	});
  	child.on('exit', function (code) {
    	if (code != 0)
      	return cb(new Error('pandoc exited with code ' + code + '.'));
    	if (error)
      	return cb(new Error(error));
    	cb(null, result);
  	});
		child.stdin.write(res, 'utf8');
  	child.stdin.end()
  });
}

// Convert pandoc JSON output into substance format
// Should output substance doc

function transformIn(json, cb) {

  var lastid = 0,
      offset = 0;

  function getId() {
    lastid += 1;
    return lastid;
  }

  var doc = {}//new Document({id: "a_new_doc"}, docSchema);
  var elements = json[1];

  var fragments = [];
  var offset = 0;
  var annotations = {
    "annotations": [],
    "strong": [],
    "emphasis": [],
    "inline-code": [],
    "link": [],
    "idea": [],
    "error": [],
    "question": [],
    "comment": []
  };

  // Process
  // -------

  function process (node) {
    var nodeType = '';

    // inspect element
    if(typeof node === 'object'){
        if(Array.isArray(node)) {

          _.each(node, function (subNode){
            process(subNode);
          });

        }else{
          nodeType = _.first(Object.keys(node));
        }
    } else {
      nodeType = node;
    }

    // Shared internal actions
    // -----------------------

    function processAtomic (str){
      offset += str.length;
      for (var ann in annotations) {
        annotations[ann].push(str);
      }
      fragments.push(str);
    }

    function processInline (type){
      annotations[type] = []; // reset
      var start = offset;
      var val = process(node[nodeType]);
      return val['annotations'][type];
    }

    function processBlock (item, ins) {
      fragments = []; // reset
      var res = process(item);
      return res['text'].join('');
    }

    function processSimple (item) {
      fragments = [];
      offset += item.length;
      fragments.push(item);
      return item;
    }

    function processList (type) {
      var list = '';
      _.each(node[nodeType], function (li){
        fragments = [];
        switch (type) {
          case 'bl':
            res = process(li[0]['Plain']);
            list += '* ' + res['text'].join('') + '\n';
            break;

          case 'ol':
            // TODO: implement
            // ..... needs a well formated example
            break;

          case 'ul':
            // TODO: implement
            // ..... needs example
            break;
        }
      });
      return list;
    }

    function insert (type, data, target) {
      var target = "back" || target;
      /*doc.apply(["insert", {
        "id": type + ":" + getId(),
        "type": type,
        "target": target,
        "data": data
      }]);*/
    }

    // Proceed Processing
    // ------------------

    switch (nodeType) {

      // Atomic content
      // --------------

      case 'Str':
        var str = node['Str'];
        processAtomic(str);
        break;

      case 'Space':
        var str = ' ';
        processAtomic(str);
        break;

      case 'LineBreak':
        var str = '\n';
        processAtomic(str);
        break;

      // Inline content
      // ---------------

      case 'Emph':
        var annType = 'emphasis';
        processInline(annType);
        break;

      case 'Strong':
        var annType = 'strong';
        processInline(annType);
        break;

      case 'Code':
        var annType = 'inline-code';
        processInline(annType);
        break;

      case 'Link':
        // var annType = 'link';
        // var start = offset;
        // var txt = processInline('link');
        // var len = txt.length;

        // doc.apply(["insert", {
        //   "id":  "annotation:" + getId(),
        //   "type": annType,
        //   "node": "text:??",
        //   "pos": [start,len]
        // }]);

        //  doc.apply(["insert", {
        //     "type": "link",
        //     "id": "annotation:351",
        //     "source": "text:350",
        //     "target": null,
        //     "key": "content",
        //     "content": "review process",
        //     "pos": [398, 14],
        //     "url": "http://www.elifesciences.org/the-journal/review-process"
        // }]);

        break;

      // Block content
      // -------------

      case 'Header':
        insert ('heading', {
          "level": node[nodeType][0],
          "content": processBlock(node[nodeType][1])
        });

        break;

      case 'Para':
      case 'Plain':
        insert ('text', {
          "content": processBlock(node[nodeType])
        });
        break;

      case 'OrderedList':
        insert ('text', {
          "subtype": "ol",
          "content": processList('ol')
        });
        break;

      case 'UnorderedList':
        insert ('text', {
          "subtype": "ul",
          "content": processList('ul')
        });
        break;

      case 'BulletList':
        insert ('text', {
          "subtype": "bl",
          "content": processList('bl')
        });
        break;

      case 'RawBlock':
      case 'CodeBlock':
        insert ('codeblock', {
          "lang": node[nodeType][0],
          "content": processSimple(node[nodeType][1])
        }, ["figures", "back"]);
        break;

      case 'BlockQuote':
        // Find out why Para and if it always appears or further functionalities for BlockQuotes
        // Needs nodetype in the Document
        insert ('codeblock', {
          "subtype": "blocQuote",
          "content": processBlock(node[nodeType][0]['Para'])
        });
        break;

      case 'HorizontalRule':
        // for now we fake HR
        // should we skip it all the way?
        offset += 1;
        insert ('text', {
          "content": '------'
        });
        break;

      case 'Image':
        // var alt = process(node[nodeType][0]);
        fragments = []; // reset
        var res = process(node[nodeType][0]);
        var alt = res['text'].join('');
        var url = node[nodeType][1][0];
        var title = node[nodeType][1][1];

        insert('image', {
                  "alt": alt,
                  "title": title,
                  "large_url": url,
                  "url": url
        });
        break;

      default:
        // if(nodeType.length > 1)
          // console.log(nodeType);
        // console.log('node', node);
        break;

    }
    return {"text": fragments, "annotations": annotations};
  }

  _.each(elements, function (n) {
      process(n);
  });

  cb(null, doc/*doc.toJSON()*/);
}

// Convert to SUBSTANCE
// --------------------

// _mql: https and github works perfectly for me! you should fix your issues ;)

// var url = 'http://bywordapp.com/markdown/guide.md';
// var url = 'https://dl.dropboxusercontent.com/u/606131/gh-flavored.md';
//var url = 'https://raw.github.com/michael/documents/master/2013-05-26-lens.md';
// var url = 'https://raw.github.com/dtao/lazy.js/master/README.md';
var url = 'https://dl.dropboxusercontent.com/u/606131/lens-intro.md';

var doc = '';

app.get('/', function(req, res) {
	console.log('started')
	toPandoc(url, 'markdown', 'json', function(err, pandocAST) {
		transformIn(pandocAST, function(err,result){
			console.log(result)
		});
	});
});

app.listen(process.env.PORT || 5001);
<commit_msg>First results<commit_after>var express = require('express'),
    fs = require('fs'),
    app = express(),
    _ = require('underscore'),
    urlparser = require("url");

// Fetching file by this function instead of internal pandoc method
// because of pandoc can't fetch files using https protocol
function getFile(url, cb) {

  var parts = urlparser.parse(url),
      protocol;

  // quick workaround
  // can be done better?
  if (parts.protocol === 'http:'){
    protocol = require('http');
  } else if(parts.protocol === 'https:') {
    protocol = require('https');
  }

  protocol.get(url, function(res) {
    var result = "";
    res.on('data', function ( d ) {
      result += d.toString();
    });
    res.on('end', function() {
    	console.log('processing')
      cb(null,result);
    });
  }).on('error', function( e ) {
    cb(err);
  });
}

// Spawn pandoc child process, run callback
// added some arguments for more capabilities
function toPandoc(url, from, to, cb) {
	var spawn = require('child_process').spawn,
    	args = [ '-f', from, '-t', to],
    	result = '',
    	error = '',
      child;
	getFile(url,function(err,res){
  	child = spawn('pandoc',args);
  	child.stdout.on('data', function (data) {
    	result += data;
  	});
  	child.stderr.on('data', function (data) {
    	error += data;
  	});
  	child.on('exit', function (code) {
    	if (code != 0)
      	return cb(new Error('pandoc exited with code ' + code + '.'));
    	if (error)
      	return cb(new Error(error));
    	cb(null, JSON.parse(result));
  	});
		child.stdin.write(res, 'utf8');
  	child.stdin.end()
  });
}

// Convert pandoc JSON output into substance format
// Should output substance doc

function transformIn(json, cb) {

  var lastid = 0,
      offset = 0;

  function getId() {
    lastid += 1;
    return lastid;
  }

  var doc = {id: "a_new_doc"}//new Document({id: "a_new_doc"}, docSchema);
  var elements = json[1];
  var fragments = [];
  var offset = 0;
  var annotations = {
    "annotations": [],
    "strong": [],
    "emphasis": [],
    "inline-code": [],
    "link": [],
    "idea": [],
    "error": [],
    "question": [],
    "comment": []
  };

  // Process
  // -------

  function process (node) {
    var nodeType = '';

    // inspect element
    if(typeof node === 'object'){
        if(Array.isArray(node)) {

          _.each(node, function (subNode){
            process(subNode);
          });

        }else{
          nodeType = _.first(Object.keys(node));
        }
    } else {
      nodeType = node;
    }
		//console.log(nodeType)
    // Shared internal actions
    // -----------------------

    function processAtomic (str){
      offset += str.length;
      for (var ann in annotations) {
        annotations[ann].push(str);
      }
      fragments.push(str);
    }

    function processInline (type){
      annotations[type] = []; // reset
      var start = offset;
      var val = process(node[nodeType]);
      return val['annotations'][type];
    }

    function processBlock (item, ins) {
      fragments = []; // reset
      var res = process(item);
      return res['text'].join('');
    }

    function processSimple (item) {
      fragments = [];
      offset += item.length;
      fragments.push(item);
      return item;
    }

    function processList (type) {
      var list = '';
      _.each(node[nodeType], function (li){
        fragments = [];
        switch (type) {
          case 'bl':
            res = process(li[0]['Plain']);
            list += '* ' + res['text'].join('') + '\n';
            break;

          case 'ol':
            // TODO: implement
            // ..... needs a well formated example
            break;

          case 'ul':
            // TODO: implement
            // ..... needs example
            break;
        }
      });
      return list;
    }

    function insert (type, data, target) {
      var target = "back" || target;
      var id = type+'_'+getId();
      doc[id] = {type: type, id: id}
      _.each(data, function(prop,key){
      	doc[id][key] = prop;
      })
    }

    // Proceed Processing
    // ------------------

    switch (nodeType) {

      // Atomic content
      // --------------

      case 'Str':
        var str = node['Str'];
        processAtomic(str);
        break;

      case 'Space':
        var str = ' ';
        processAtomic(str);
        break;

      case 'LineBreak':
        var str = '\n';
        processAtomic(str);
        break;

      // Inline content
      // ---------------

      case 'Emph':
        var annType = 'emphasis';
        processInline(annType);
        break;

      case 'Strong':
        var annType = 'strong';
        processInline(annType);
        break;

      case 'Code':
        var annType = 'inline-code';
        processInline(annType);
        break;

      case 'Link':
        // var annType = 'link';
        // var start = offset;
        // var txt = processInline('link');
        // var len = txt.length;

        // doc.apply(["insert", {
        //   "id":  "annotation:" + getId(),
        //   "type": annType,
        //   "node": "text:??",
        //   "pos": [start,len]
        // }]);

        //  doc.apply(["insert", {
        //     "type": "link",
        //     "id": "annotation:351",
        //     "source": "text:350",
        //     "target": null,
        //     "key": "content",
        //     "content": "review process",
        //     "pos": [398, 14],
        //     "url": "http://www.elifesciences.org/the-journal/review-process"
        // }]);

        break;

      // Block content
      // -------------

      case 'Header':
        insert ('heading', {
          "level": node[nodeType][0],
          "content": processBlock(node[nodeType][1])
        });

        break;

      case 'Para':
      case 'Plain':
        insert ('text', {
          "content": processBlock(node[nodeType])
        });
        break;

      case 'OrderedList':
        insert ('text', {
          "subtype": "ol",
          "content": processList('ol')
        });
        break;

      case 'UnorderedList':
        insert ('text', {
          "subtype": "ul",
          "content": processList('ul')
        });
        break;

      case 'BulletList':
        insert ('text', {
          "subtype": "bl",
          "content": processList('bl')
        });
        break;

      case 'RawBlock':
      case 'CodeBlock':
        insert ('codeblock', {
          "lang": node[nodeType][0],
          "content": processSimple(node[nodeType][1])
        }, ["figures", "back"]);
        break;

      case 'BlockQuote':
        // Find out why Para and if it always appears or further functionalities for BlockQuotes
        // Needs nodetype in the Document
        insert ('codeblock', {
          "subtype": "blocQuote",
          "content": processBlock(node[nodeType][0]['Para'])
        });
        break;

      case 'HorizontalRule':
        // for now we fake HR
        // should we skip it all the way?
        offset += 1;
        insert ('text', {
          "content": '------'
        });
        break;

      case 'Image':
        // var alt = process(node[nodeType][0]);
        fragments = []; // reset
        var res = process(node[nodeType][0]);
        var alt = res['text'].join('');
        var url = node[nodeType][1][0];
        var title = node[nodeType][1][1];

        insert('image', {
                  "alt": alt,
                  "title": title,
                  "large_url": url,
                  "url": url
        });
        break;

      default:
        // if(nodeType.length > 1)
          // console.log(nodeType);
        // console.log('node', node);
        break;

    }
    return {"text": fragments, "annotations": annotations};
  }

  _.each(elements, function (n) {
      process(n);
  });

  cb(null, doc/*doc.toJSON()*/);
}

// Convert to SUBSTANCE
// --------------------

// _mql: https and github works perfectly for me! you should fix your issues ;)

// var url = 'http://bywordapp.com/markdown/guide.md';
// var url = 'https://dl.dropboxusercontent.com/u/606131/gh-flavored.md';
//var url = 'https://raw.github.com/michael/documents/master/2013-05-26-lens.md';
// var url = 'https://raw.github.com/dtao/lazy.js/master/README.md';
var url = 'https://dl.dropboxusercontent.com/u/606131/lens-intro.md';

var doc = '';

toPandoc(url, 'markdown', 'json', function(err, pandocJSON) {
		transformIn(pandocJSON, function(err,result){
			console.log(result)
		});
	});
app.get('/', function(req, res) {
	console.log('started')
	toPandoc(url, 'markdown', 'json', function(err, pandocAST) {
		transformIn(pandocAST, function(err,result){
			console.log(result)
		});
	});
});

app.listen(process.env.PORT || 5001);
<|endoftext|>


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

'use strict';

var should = require('should'),
    async = require('async'),
    apply = async.apply,
    lwm2mServer = require('../../../').server,
    lwm2mClient = require('../../../').client,
    config = require('../../../config'),
    testInfo = {};

describe('Client-side information management', function() {
    var deviceInformation,
        deviceId;

    beforeEach(function(done) {
        lwm2mServer.start(config.server, function (error, srvInfo) {
            testInfo.serverInfo = srvInfo;

            lwm2mClient.register('localhost', config.server.port, 'testEndpoint', function (error, result) {
                deviceInformation = result;
                deviceId = deviceInformation.location.split('/')[2];
                lwm2mClient.registry.create('/3/6', done);
            });
        });
    });

    afterEach(function(done) {
        async.series([
            apply(lwm2mClient.registry.remove, '/3/6'),
            apply(lwm2mClient.unregister, deviceInformation),
            apply(lwm2mServer.stop, testInfo.serverInfo)
        ], done);
    });

    describe('When a write request arrives to the client', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '1',
            value: 'TheValue'
        };

        it('should change the appropriate value in the selected object', function (done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'write',
                function (objectType, objectId, resourceId, value, callback) {
                    should.exist(objectType);
                    should.exist(objectId);
                    should.exist(resourceId);
                    should.exist(value);
                    objectType.should.equal(obj.type);
                    objectId.should.equal(obj.id);
                    resourceId.should.equal(obj.resource);
                    value.should.equal(obj.value);
                    handlerCalled = true;
                    callback();
                });

            lwm2mServer.write(deviceId, obj.type, obj.id, obj.resource, obj.value, function(error) {
                should.not.exist(error);
                handlerCalled.should.equal(true);
                done();
            });
        });
    });
    describe('When a read request arrives to the client for an existent resource of an existent object', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should send a response with the required object value', function(done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
                function (objectType, objectId, resourceId, resourceValue, callback) {
                    should.exist(objectType);
                    should.exist(objectId);
                    should.exist(resourceId);
                    objectType.should.equal(obj.type);
                    objectId.should.equal(obj.id);
                    resourceId.should.equal(obj.resource);
                    handlerCalled = true;
                    callback(null, resourceValue);
                });

            lwm2mServer.read(deviceId, obj.type, obj.id, obj.resource, function(error, result) {
                should.not.exist(error);
                should.exist(result);
                result.should.equal(obj.value);
                handlerCalled.should.equal(true);
                done();
            });
        });
    });
    describe('When a read request arrives to the client for an unexistent object instance', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should raise a 4.04 OBJECT_NOT_FOUND error', function (done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'write',
                function (objectType, objectId, resourceId, value, callback) {
                    handlerCalled = true;
                    callback();
                });

            lwm2mServer.write(deviceId, obj.type, '19', obj.resource, obj.value, function(error) {
                should.exist(error);
                handlerCalled.should.equal(false);
                error.name.should.equal('OBJECT_NOT_FOUND');
                done();
            });
        });
    });
    describe('When a read request arrives to the client for an unexistent resource of an object', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should raise a 4.04 RESOURCE_NOT_FOUND error', function(done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
                function (objectType, objectId, resourceId, resourceValue, callback) {
                    handlerCalled = true;
                    callback(null, resourceValue);
                });

            lwm2mServer.read(deviceId, obj.type, '75', obj.resource, function(error, result) {
                should.exist(error);
                should.not.exist(result);
                error.name.should.equal('RESOURCE_NOT_FOUND');
                handlerCalled.should.equal(false);
                done();
            });
        });
    });
});<commit_msg>ADD Test cases for discovery and attribute writting<commit_after>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-lwm2m-lib
 *
 * iotagent-lwm2m-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-lwm2m-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-lwm2m-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */

'use strict';

var should = require('should'),
    async = require('async'),
    apply = async.apply,
    lwm2mServer = require('../../../').server,
    lwm2mClient = require('../../../').client,
    config = require('../../../config'),
    testInfo = {};

describe('Client-side information management', function() {
    var deviceInformation,
        deviceId;

    beforeEach(function(done) {
        lwm2mServer.start(config.server, function (error, srvInfo) {
            testInfo.serverInfo = srvInfo;

            lwm2mClient.register('localhost', config.server.port, 'testEndpoint', function (error, result) {
                deviceInformation = result;
                deviceId = deviceInformation.location.split('/')[2];
                lwm2mClient.registry.create('/3/6', done);
            });
        });
    });

    afterEach(function(done) {
        async.series([
            apply(lwm2mClient.registry.remove, '/3/6'),
            apply(lwm2mClient.unregister, deviceInformation),
            apply(lwm2mServer.stop, testInfo.serverInfo)
        ], done);
    });

    describe('When a Write request arrives to the client', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '1',
            value: 'TheValue'
        };

        it('should change the appropriate value in the selected object', function (done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'write',
                function (objectType, objectId, resourceId, value, callback) {
                    should.exist(objectType);
                    should.exist(objectId);
                    should.exist(resourceId);
                    should.exist(value);
                    objectType.should.equal(obj.type);
                    objectId.should.equal(obj.id);
                    resourceId.should.equal(obj.resource);
                    value.should.equal(obj.value);
                    handlerCalled = true;
                    callback();
                });

            lwm2mServer.write(deviceId, obj.type, obj.id, obj.resource, obj.value, function(error) {
                should.not.exist(error);
                handlerCalled.should.equal(true);
                done();
            });
        });
    });
    describe('When a Read request arrives to the client for an existent resource of an existent object', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should send a response with the required object value', function(done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
                function (objectType, objectId, resourceId, resourceValue, callback) {
                    should.exist(objectType);
                    should.exist(objectId);
                    should.exist(resourceId);
                    objectType.should.equal(obj.type);
                    objectId.should.equal(obj.id);
                    resourceId.should.equal(obj.resource);
                    handlerCalled = true;
                    callback(null, resourceValue);
                });

            lwm2mServer.read(deviceId, obj.type, obj.id, obj.resource, function(error, result) {
                should.not.exist(error);
                should.exist(result);
                result.should.equal(obj.value);
                handlerCalled.should.equal(true);
                done();
            });
        });
    });
    describe('When a Read request arrives to the client for an unexistent object instance', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should raise a 4.04 OBJECT_NOT_FOUND error', function (done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'write',
                function (objectType, objectId, resourceId, value, callback) {
                    handlerCalled = true;
                    callback();
                });

            lwm2mServer.write(deviceId, obj.type, '19', obj.resource, obj.value, function(error) {
                should.exist(error);
                handlerCalled.should.equal(false);
                error.name.should.equal('OBJECT_NOT_FOUND');
                done();
            });
        });
    });
    describe('When a Read request arrives to the client for an unexistent resource of an object', function() {
        var obj = {
            type: '3',
            id: '6',
            resource: '2',
            value: 'ValueToBeRead',
            uri: '/3/6'
        };

        beforeEach(function(done) {
            lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
        });
        afterEach(function(done) {
            lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
        });
        it('should raise a 4.04 RESOURCE_NOT_FOUND error', function(done) {
            var handlerCalled = false;

            lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
                function (objectType, objectId, resourceId, resourceValue, callback) {
                    handlerCalled = true;
                    callback(null, resourceValue);
                });

            lwm2mServer.read(deviceId, obj.type, '75', obj.resource, function(error, result) {
                should.exist(error);
                should.not.exist(result);
                error.name.should.equal('RESOURCE_NOT_FOUND');
                handlerCalled.should.equal(false);
                done();
            });
        });
    });

    describe('When a Discover request arrives targeting an existent resource ID', function() {
        it('should return all the attributes of the selected resource ID');
    });
    describe('When a Write attributes request arrives targeting an existent resource ID', function() {
        it('should overwrite the given attributes in the selected resource ID');
    });
    describe('When a Discover request arrives targeting an unexistent resource ID', function() {
        it('should raise a RESOURCE_NOT_FOUND error');
    });
    describe('When a Write attributes request arrives targeting an existent resource ID', function() {
        it('should raise a RESOURCE_NOT_FOUND error');
    });
    describe('When a Discover request arrives targeting an existent object ID', function() {
        it('should return all the attributes of the selected object ID');
    });
    describe('When a Write attributes request arrives targeting an existent object ID', function() {
        it('should overwrite the given attributes in the selected object ID');
    });
    describe('When a Discover request arrives targeting an unexistent object ID', function() {
        it('should raise a OBJECT_NOT_FOUND error');
    });
    describe('When a Write attributes request arrives targeting an existent object ID', function() {
        it('should raise a OBJECT_NOT_FOUND error');
    });
});<|endoftext|>


<commit_before><commit_msg>Removing trailing whitespace.<commit_after><|endoftext|>


<commit_before>/** A docstring that tells us 'informative' information about server.js
 *
 * The Node.js serverside script to tell it what ot do to ensure we get all the
 * magical goodness that is (Karma + Sassy) * Facebook - Hipchat = Kassy
 *
 * Written By:
 * 		Matt Knox,
 * 		Dion Woolley
 * 		Jay Harris
 * 		Matt Hartstonge
 * 		(Mainly strange people)
 *
 * Date written: 21/07/2015
 *
 */

// Facebook API
var facebook = require('./facebook.js');

// Optional module scripts
var anim = require('./modules/anim.js');
var associate = require('./modules/associate.js');
var disable = require('./modules/disable.js');
var fawlty = require('./modules/fawlty.js');
var karma = require('./modules/karma.js');
var magic8Ball = require('./modules/8Ball.js');
var runbot = require('./modules/runbot.js');
var profound = require('./modules/profound.js');

// Optional Modules to be included
var modules = [
	anim,
	associate,
	disable,
	fawlty,
	karma,
	magic8Ball,
	runbot,
	profound
];

// Add useful prototypes
if (typeof String.prototype.startsWith != 'function') {
	String.prototype.startsWith = function (str){
		return this.indexOf(str) === 0;
	};
}
if (typeof String.prototype.toProperCase != 'function') {
	String.prototype.toProperCase = function () {
		return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	};
}
if (typeof String.prototype.endsWith != 'function') {
	String.prototype.endsWith = function(suffix) {
		return this.indexOf(suffix, this.length - suffix.length) !== -1;
	};
}

// Load Optional Modules
for (var i = 0; i < modules.length; i++) {
	modules[i].load();
}

// Start the all knowing, all extensible kassy bot..
facebook.start('spamme@facebook.com', 'averysecurepassword', function(api, event) {
	if (event.body === '/kassy') {
		var help = 'KASSY 1.1\n--------------------\n' +
			'https://github.com/mrkno/Kassy\n\n';
		for (var i = 0; i < modules.length; i++) {
			help += modules[i].help() + '\n';
		}
		api.sendMessage(help, event.thread_id);
		return;
	}

	for (var i = 0; i < modules.length; i++) {
		if (modules[i].match(event.body, event.thread_id)) {
			modules[i].run(api, event);
			return;
		}
	}
});
<commit_msg>Date removed; Docstring reworked to be literal; Ensured the keeping of Matthew happy; Modules alphabetically included;<commit_after>/** Node.js server configuration for Kassy
 *
 * Herein lies the Node.js serverside script to tell node what to do to ensure
 * we get all the magical goodness that is:
 * 		(Karma + Sassy) * Facebook - Hipchat = Kassy
 *
 * Written By:
 * 		Matthew Knox
 *
 * Contributors:
 * 		Dion Woolley
 * 		Jay Harris
 * 		Matt Hartstonge
 * 		(Mainly strange people)
 *
 */

// Facebook API
var facebook = require('./facebook.js');

// Optional module scripts
var anim = require('./modules/anim.js');
var associate = require('./modules/associate.js');
var disable = require('./modules/disable.js');
var fawlty = require('./modules/fawlty.js');
var karma = require('./modules/karma.js');
var magic8Ball = require('./modules/8Ball.js');
var runbot = require('./modules/runbot.js');
var profound = require('./modules/profound.js');

// Optional Modules to be included
var modules = [
	anim,
	associate,
	disable,
	fawlty,
	karma,
	magic8Ball,
	runbot,
	profound
];

// Add useful prototypes
if (typeof String.prototype.startsWith != 'function') {
	String.prototype.startsWith = function (str){
		return this.indexOf(str) === 0;
	};
}
if (typeof String.prototype.toProperCase != 'function') {
	String.prototype.toProperCase = function () {
		return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	};
}
if (typeof String.prototype.endsWith != 'function') {
	String.prototype.endsWith = function(suffix) {
		return this.indexOf(suffix, this.length - suffix.length) !== -1;
	};
}

// Load Optional Modules
for (var i = 0; i < modules.length; i++) {
	modules[i].load();
}

// Start the all knowing, all extensible kassy bot..
facebook.start('spamme@facebook.com', 'averysecurepassword', function(api, event) {
	if (event.body === '/kassy') {
		var help = 'KASSY 1.1\n--------------------\n' +
			'https://github.com/mrkno/Kassy\n\n';
		for (var i = 0; i < modules.length; i++) {
			help += modules[i].help() + '\n';
		}
		api.sendMessage(help, event.thread_id);
		return;
	}

	for (var i = 0; i < modules.length; i++) {
		if (modules[i].match(event.body, event.thread_id)) {
			modules[i].run(api, event);
			return;
		}
	}
});
<|endoftext|>


<commit_before>
var test = require('tape')
require('rewire-global').enable()
const sinon = require('sinon')
const proxyquire = require('proxyquire')

const consumeMessages = proxyquire('../../../messages/consumeMessages', {'node-queue-adapter': sinon.stub().returns({})})

test('if it is already reading, then it should just return ', t => {
  t.plan(1)
  const readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', true)

  consumeMessages.__get__('readMessageUnlessReading')()

  t.equal(readMessage.called, false)
})

test('if it is not already reading, then it should call readMessage ', t => {
  t.plan(1)
  const consumeMessages = require('../../../messages/consumeMessages')
  const readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', false)

  consumeMessages.__get__('readMessageUnlessReading')()
  t.equal(readMessage.called, true)
})
<commit_msg>mock node-queue-adapter<commit_after>
var test = require('tape')
require('rewire-global').enable()
const sinon = require('sinon')
const proxyquire = require('proxyquire')

const consumeMessages = proxyquire('../../../messages/consumeMessages', {'node-queue-adapter': sinon.stub().returns({})})

test('if it is already reading, then it should just return ', t => {
  t.plan(1)
  const readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', true)

  consumeMessages.__get__('readMessageUnlessReading')()

  t.equal(readMessage.called, false)
})

test('if it is not already reading, then it should call readMessage ', t => {
  t.plan(1)
  const consumeMessages = require('../../../messages/consumeMessages')
  const readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', false)

  consumeMessages.__get__('readMessageUnlessReading')()
  t.equal(readMessage.called, true)
})
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var webpack = require('webpack');
var browserSync = require('browser-sync').create();

var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpackConfig = require('./webpack.development.config');

var app = express();
var webpackBundler = webpack(webpackConfig);

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

app.listen(3000, function (err) {
  if (err) {
    return console.error(err);
  }

  console.log('Listening at http://localhost:3000/');

  browserSync.init(null, {
    server: {
      baseDir: 'public',
      middleware: [
        webpackDevMiddleware(webpackBundler, {
          publicPath: webpackConfig.output.publicPath,
          noInfo: false,
          stats: {
            colors: true,
            version: false,
            timings: false,
            chunks: false,
            chunkModules: false
          },
          historyApiFallback: false
        }),
        webpackHotMiddleware(webpackBundler)
      ],
    },
    files: [
      'dist/index.html'
    ],
    reloadOnRestart: true,
    notify: true,
    tunnel: true, // LocalTunnel url
    logLevel: 'debug',
    logSnippet: 'false',
    open: false, // Change to 'local' to open on start
    xip: true
  });
});
<commit_msg>Revert back to 9b3a88c<commit_after>var express = require('express');
var path = require('path');
var app = express();

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

app.listen(3000, function (err) {
  if (err) {
    return console.error(err);
  }

  console.log('Listening at http://localhost:3000/');

  var bs = require('browser-sync').create();
  var webpack = require('webpack');
  var webpackDevMiddleware = require('webpack-dev-middleware');
  var webpackHotMiddleware = require('webpack-hot-middleware');
  var webpackConfig = require('./webpack.development.config');
  var webpackBundler = webpack(webpackConfig);

  bs.init(null, {
    server: {
      baseDir: 'dist',
      middleware: [
        webpackDevMiddleware(webpackBundler, {
          publicPath: webpackConfig.output.publicPath,
          noInfo: false,
          stats: {
            colors: true,
            version: false,
            timings: false,
            chunks: false,
            chunkModules: false
          },
          historyApiFallback: false
        }),
        webpackHotMiddleware(webpackBundler)
      ],
    },
    files: [
      'public/index.html',
      'src/**/*.css'
    ],
    reloadOnRestart: true,
    injectChanges: true,
    notify: true,
    tunnel: true, // LocalTunnel url
    logLevel: 'debug',
    logSnippet: 'false',
    open: false, // Change to 'local' to open on start
    xip: true
  });
});
<|endoftext|>


<commit_before>import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'web/util/index'
import { nextFrame } from 'web/runtime/modules/transition'

if (!isIE9) {
  describe('Transition mode', () => {
    const duration = injectStyles()
    const components = {
      one: { template: '
one
' },
      two: { template: '
two
' }
    }

    let el
    beforeEach(() => {
      el = document.createElement('div')
      document.body.appendChild(el)
    })

    it('dynamic components, simultaneous', done => {
      const vm = new Vue({
        template: `

          <component
            :is="view"
            class="test"
            transition>
          </component>

`,
        data: { view: 'one' },
        components
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
' +
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
' +
          '
one
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('dynamic components, out-in', done => {
      let next
      const vm = new Vue({
        template: `

          <component
            :is="view"
            class="test"
            transition="test"
            transition-mode="out-in">
          </component>

`,
        data: { view: 'one' },
        components,
        transitions: {
          test: {
            afterLeave () {
              next()
            }
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe('')
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('dynamic components, in-out', done => {
      let next
      const vm = new Vue({
        template: `

          <component
            :is="view"
            class="test"
            transition="test"
            transition-mode="in-out">
          </component>

`,
        data: { view: 'one' },
        components,
        transitions: {
          test: {
            afterEnter () {
              next()
            }
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, simultaneous', done => {
      const vm = new Vue({
        template: `

{{view}}

`,
        data: { view: 'one' },
        components
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
' +
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
' +
          '
one
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, out-in', done => {
      let next
      const vm = new Vue({
        template: `

{{view}}

`,
        data: { view: 'one' },
        components,
        transitions: {
          test: {
            afterLeave () {
              next()
            }
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe('')
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, in-out', done => {
      let next
      const vm = new Vue({
        template: `

{{view}}

`,
        data: { view: 'one' },
        components,
        transitions: {
          test: {
            afterEnter () {
              next()
            }
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })
  })
}
<commit_msg>update transition mode specs<commit_after>import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'web/util/index'
import { nextFrame } from 'web/runtime/modules/transition'

if (!isIE9) {
  describe('Transition mode', () => {
    const duration = injectStyles()
    const components = {
      one: { template: '
one
' },
      two: { template: '
two
' }
    }

    let el
    beforeEach(() => {
      el = document.createElement('div')
      document.body.appendChild(el)
    })

    it('dynamic components, simultaneous', done => {
      const vm = new Vue({
        template: `

          <transition>
            <component :is="view" class="test">
            </component>
          </transition>

`,
        data: { view: 'one' },
        components
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('dynamic components, out-in', done => {
      let next
      const vm = new Vue({
        template: `

          <transition name="test" mode="out-in" @after-leave="afterLeave">
            <component :is="view" class="test">
            </component>
          </transition>

`,
        data: { view: 'one' },
        components,
        methods: {
          afterLeave () {
            next()
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe('')
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('dynamic components, in-out', done => {
      let next
      const vm = new Vue({
        template: `

          <transition name="test" mode="in-out" @after-enter="afterEnter">
            <component :is="view" class="test">
            </component>
          </transition>

`,
        data: { view: 'one' },
        components,
        methods: {
          afterEnter () {
            next()
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, simultaneous', done => {
      const vm = new Vue({
        template: `

          <transition>

{{view}}

          </transition>

`,
        data: { view: 'one' },
        components
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, out-in', done => {
      let next
      const vm = new Vue({
        template: `

          <transition name="test" mode="out-in" @after-leave="afterLeave">

{{view}}

          </transition>

`,
        data: { view: 'one' },
        components,
        methods: {
          afterLeave () {
            next()
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe('')
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })

    it('normal elements with different keys, in-out', done => {
      let next
      const vm = new Vue({
        template: `

          <transition name="test" mode="in-out" @after-enter="afterEnter">

{{view}}

          </transition>

`,
        data: { view: 'one' },
        components,
        methods: {
          afterEnter () {
            next()
          }
        }
      }).$mount(el)
      expect(vm.$el.textContent).toBe('one')
      vm.view = 'two'
      waitForUpdate(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(_next => { next = _next }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(nextFrame).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
one
' +
          '
two
'
        )
      }).thenWaitFor(duration + 10).then(() => {
        expect(vm.$el.innerHTML).toBe(
          '
two
'
        )
      }).then(done)
    })
  })
}
<|endoftext|>


<commit_before>var express = require('express')
  , app = express()
  , BearerStrategy = require('passport-http-bearer').Strategy
  , config = require('./config')
  , controllers = require('./controllers')
  , faye = require('faye')
  , middleware = require('./middleware')
  , models = require('./models')
  , mongoose = require('mongoose')
  , passport = require('passport')
  , services = require('./services');

console.log("connecting to mongodb instance: " + config.mongodb_connection_string);
mongoose.connect(config.mongodb_connection_string);

var port = process.env.PORT || config.http_port || 3030;
var server = app.listen(port);
console.log('listening for http connections on ' + config.base_url);

app.use(express.bodyParser());

app.use(passport.initialize());
passport.use(new BearerStrategy({}, services.accessTokens.verify));

app.use(middleware.crossOrigin);

// only establish routing to endpoints
mongoose.connection.once('open', function () {
    // REST endpoints

    app.get(config.api_prefix + 'v1/headwaiter',                                     controllers.headwaiter.index);

    app.get(config.api_prefix + 'v1/blobs/:id',      middleware.authenticateRequest, controllers.blobs.show);
    app.post(config.api_prefix + 'v1/blobs',         /*middleware.authenticateRequest,*/ controllers.blobs.create);

    app.get(config.api_prefix + 'v1/ops/health',                                     controllers.ops.health);

    app.get(config.api_prefix + 'v1/principals/:id', middleware.authenticateRequest, controllers.principals.show);
    app.get(config.api_prefix + 'v1/principals',     middleware.authenticateRequest, controllers.principals.index);
    app.post(config.api_prefix + 'v1/principals',                                    controllers.principals.create);
    app.post(config.api_prefix + 'v1/principals/auth',                               controllers.principals.authenticate);

    //app.put(config.api_prefix + 'v1/principals/:id',   /* authenticateRequest, */ controllers.principals.update);
    //app.delete(config.api_prefix + 'v1/principals/:id',   /* authenticateRequest, */ controllers.principals.update);

    app.get(config.api_prefix + 'v1/messages/:id',   middleware.authenticateRequest, controllers.messages.show);
    app.get(config.api_prefix + 'v1/messages',       middleware.authenticateRequest, controllers.messages.index);
    app.post(config.api_prefix + 'v1/messages',      middleware.authenticateRequest, controllers.messages.create);

    // static serving endpoint

    app.use(express.static(__dirname + '/static'));
});

// Realtime endpoint setup

global.bayeux = new faye.NodeAdapter({
    mount: config.path_prefix + config.realtime_path,
    timeout: config.realtime_endpoint_timeout
});

global.bayeux.attach(server);
console.log('listening for realtime connections on ' + config.path_prefix + config.realtime_path);

// TODO: log errors once we have real logging solution in place.
//mongoose.connection.on('error', function(err) {
//    console.error('MongoDB error: %s', err);
//});
<commit_msg>dynamically set config http port if not already set in config<commit_after>var express = require('express')
  , app = express()
  , BearerStrategy = require('passport-http-bearer').Strategy
  , config = require('./config')
  , controllers = require('./controllers')
  , faye = require('faye')
  , middleware = require('./middleware')
  , models = require('./models')
  , mongoose = require('mongoose')
  , passport = require('passport')
  , services = require('./services');

console.log("connecting to mongodb instance: " + config.mongodb_connection_string);
mongoose.connect(config.mongodb_connection_string);

config.http_port = process.env.PORT || config.http_port || 3030;
var server = app.listen(config.http_port);
console.log('listening for http connections on ' + config.base_url);

app.use(express.bodyParser());

app.use(passport.initialize());
passport.use(new BearerStrategy({}, services.accessTokens.verify));

app.use(middleware.crossOrigin);

// only establish routing to endpoints
mongoose.connection.once('open', function () {
    // REST endpoints

    app.get(config.api_prefix + 'v1/headwaiter',                                     controllers.headwaiter.index);

    app.get(config.api_prefix + 'v1/blobs/:id',      middleware.authenticateRequest, controllers.blobs.show);
    app.post(config.api_prefix + 'v1/blobs',         /*middleware.authenticateRequest,*/ controllers.blobs.create);

    app.get(config.api_prefix + 'v1/ops/health',                                     controllers.ops.health);

    app.get(config.api_prefix + 'v1/principals/:id', middleware.authenticateRequest, controllers.principals.show);
    app.get(config.api_prefix + 'v1/principals',     middleware.authenticateRequest, controllers.principals.index);
    app.post(config.api_prefix + 'v1/principals',                                    controllers.principals.create);
    app.post(config.api_prefix + 'v1/principals/auth',                               controllers.principals.authenticate);

    //app.put(config.api_prefix + 'v1/principals/:id',   /* authenticateRequest, */ controllers.principals.update);
    //app.delete(config.api_prefix + 'v1/principals/:id',   /* authenticateRequest, */ controllers.principals.update);

    app.get(config.api_prefix + 'v1/messages/:id',   middleware.authenticateRequest, controllers.messages.show);
    app.get(config.api_prefix + 'v1/messages',       middleware.authenticateRequest, controllers.messages.index);
    app.post(config.api_prefix + 'v1/messages',      middleware.authenticateRequest, controllers.messages.create);

    // static serving endpoint

    app.use(express.static(__dirname + '/static'));
});

// Realtime endpoint setup

global.bayeux = new faye.NodeAdapter({
    mount: config.path_prefix + config.realtime_path,
    timeout: config.realtime_endpoint_timeout
});

global.bayeux.attach(server);
console.log('listening for realtime connections on ' + config.path_prefix + config.realtime_path);

// TODO: log errors once we have real logging solution in place.
//mongoose.connection.on('error', function(err) {
//    console.error('MongoDB error: %s', err);
//});
<|endoftext|>