<commit_before>dojo.provide("dojox.date.tests.timezoneFormatting");
dojo.require("dojox.date.timezone");
dojo.require("dojo.date");

tests.register("dojox.date.tests.timezoneFormatting",
	[
		{
			name: "timezone format",
			setUp: function(){
				var partLocaleList = ["en-us", "fr-fr", "es", "de-at", "ja-jp", "zh-cn"];

				dojo.forEach(partLocaleList, function(locale){
					dojo.requireLocalization("dojo.cldr", "gregorian", locale);
				});
			},
			runTest: function(t){
				var date = new Date(1155257712345);
					// This translates to:
					//   GMT		Friday, August 11, 2006 at 00:55:12 GMT
					//   Denver		Thursday, August 10, 2006 at 6:55:12 PM MDT
					//   Anchorage	Thursday, August 10, 2006 at 4:55:12 PM AKDT
					//   Jerusalem	Friday, August 11, 2006 at 3:55:12 AM IDT
					//   Sydney		Friday, August 11, 2006 at 10:55:12 AM EST
					//   Tokyo		Friday, August 11, 2006 at 9:55:12 AM JST
					//   Shanghai	Friday, August 11, 2006 at 8:55:12 AM CST
					//   Paris		Friday, August 11, 2006 at 2:55:12 AM CEST
					//   Vienna		Friday, August 11, 2006 at 2:55:12 AM CEST
					//   Madrid		Friday, August 11, 2006 at 2:55:12 AM CEST

				//////////////////////
				//  Custom Selector:
				var selectorOpts = {datePattern: "EEEE, MMMM d, y 'at'", timePattern: "HH:mm:ss z", locale: "en-us"};
				doh.is("Friday, August 11, 2006 at 00:55:12 GMT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'GMT'})));
				doh.is("Thursday, August 10, 2006 at 18:55:12 MDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'America/Denver'})));
				doh.is("Thursday, August 10, 2006 at 16:55:12 AKDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'America/Anchorage'})));
				doh.is("Friday, August 11, 2006 at 03:55:12 IDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Jerusalem'})));
				doh.is("Friday, August 11, 2006 at 10:55:12 EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Australia/Sydney'})));
				doh.is("Friday, August 11, 2006 at 09:55:12 JST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Tokyo'})));
				doh.is("Friday, August 11, 2006 at 08:55:12 CST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Shanghai'})));
				doh.is("Friday, August 11, 2006 at 02:55:12 CEST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Europe/Madrid'})));

				//////////////////////
				//  Full Selectors:
				// New York (in en-us)
				doh.is("Thursday, August 10, 2006 8:55:12 PM EDT", dojo.date.locale.format(date, {formatLength:'full',locale:'en-us',timezone:'America/New_York'}));
				// Tokyo (in ja-jp)
				doh.is("2006\u5e748\u670811\u65e5\u91d1\u66dc\u65e59\u664255\u520612\u79d2 JST", dojo.date.locale.format(date, {formatLength:'full',locale:'ja-jp',timezone:'Asia/Tokyo'}));
				// Shanghai (in zh-cn)
				doh.is("2006\u5e748\u670811\u65e5\u661f\u671f\u4e94CST\u4e0a\u53488\u65f655\u520612\u79d2", dojo.date.locale.format(date, {formatLength:'full',locale:'zh-cn',timezone:'Asia/Shanghai'}));
				// Paris (in fr-fr)
				doh.is("vendredi 11 août 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'fr-fr',timezone:'Europe/Paris'}));
				// Vienna (in de-at)
				doh.is("Freitag, 11. August 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'de-at',timezone:'Europe/Vienna'}));
				// Madrid (in es)
				doh.is("viernes 11 de agosto de 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'es',timezone:'Europe/Madrid'}));

				//////////////////////
				//  Tricky Dates:
				date = new Date(1225605599000); // 1 second before New York goes off DST - NY and LA are 3 hours apart
				selectorOpts = {formatLength: "full", locale: "en-us"};
				doh.is("Sunday, November 2, 2008 1:59:59 AM EDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Saturday, November 1, 2008 10:59:59 PM PDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1225605600000); // New York goes off DST - NY and LA are 2 hours apart
				doh.is("Sunday, November 2, 2008 1:00:00 AM EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Saturday, November 1, 2008 11:00:00 PM PDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1225616400000); // LA goes off DST - NY and LA are 3 hours apart again
				doh.is("Sunday, November 2, 2008 4:00:00 AM EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Sunday, November 2, 2008 1:00:00 AM PST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1257062399000); // Denver on DST - Denver is 1 hr ahead of Phoenix
				doh.is("Sunday, November 1, 2009 1:59:59 AM MDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Denver'})));
				doh.is("Sunday, November 1, 2009 12:59:59 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Phoenix'})));

				date = new Date(1257062400000); // Denver off DST - Denver is same time as Phoenix
				doh.is("Sunday, November 1, 2009 1:00:00 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Denver'})));
				doh.is("Sunday, November 1, 2009 1:00:00 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Phoenix'})));
			}
		}
	]
);<commit_msg>Update results to match CLDR v21.0 Fixes #15424<commit_after>dojo.provide("dojox.date.tests.timezoneFormatting");
dojo.require("dojox.date.timezone");
dojo.require("dojo.date");

tests.register("dojox.date.tests.timezoneFormatting",
	[
		{
			name: "timezone format",
			setUp: function(){
				var partLocaleList = ["en-us", "fr-fr", "es", "de-at", "ja-jp", "zh-cn"];

				dojo.forEach(partLocaleList, function(locale){
					dojo.requireLocalization("dojo.cldr", "gregorian", locale);
				});
			},
			runTest: function(t){
				var date = new Date(1155257712345);
					// This translates to:
					//   GMT		Friday, August 11, 2006 at 00:55:12 GMT
					//   Denver		Thursday, August 10, 2006 at 6:55:12 PM MDT
					//   Anchorage	Thursday, August 10, 2006 at 4:55:12 PM AKDT
					//   Jerusalem	Friday, August 11, 2006 at 3:55:12 AM IDT
					//   Sydney		Friday, August 11, 2006 at 10:55:12 AM EST
					//   Tokyo		Friday, August 11, 2006 at 9:55:12 AM JST
					//   Shanghai	Friday, August 11, 2006 at 8:55:12 AM CST
					//   Paris		Friday, August 11, 2006 at 2:55:12 AM CEST
					//   Vienna		Friday, August 11, 2006 at 2:55:12 AM CEST
					//   Madrid		Friday, August 11, 2006 at 2:55:12 AM CEST

				//////////////////////
				//  Custom Selector:
				var selectorOpts = {datePattern: "EEEE, MMMM d, y 'at'", timePattern: "HH:mm:ss z", locale: "en-us"};
				doh.is("Friday, August 11, 2006 at 00:55:12 GMT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'GMT'})));
				doh.is("Thursday, August 10, 2006 at 18:55:12 MDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'America/Denver'})));
				doh.is("Thursday, August 10, 2006 at 16:55:12 AKDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'America/Anchorage'})));
				doh.is("Friday, August 11, 2006 at 03:55:12 IDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Jerusalem'})));
				doh.is("Friday, August 11, 2006 at 10:55:12 EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Australia/Sydney'})));
				doh.is("Friday, August 11, 2006 at 09:55:12 JST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Tokyo'})));
				doh.is("Friday, August 11, 2006 at 08:55:12 CST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Asia/Shanghai'})));
				doh.is("Friday, August 11, 2006 at 02:55:12 CEST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone: 'Europe/Madrid'})));

				//////////////////////
				//  Full Selectors:
				// New York (in en-us)
				doh.is("Thursday, August 10, 2006 8:55:12 PM EDT", dojo.date.locale.format(date, {formatLength:'full',locale:'en-us',timezone:'America/New_York'}));
				// Tokyo (in ja-jp)
				doh.is("2006\u5e748\u670811\u65e5\u91d1\u66dc\u65e5 9\u664255\u520612\u79d2 JST", dojo.date.locale.format(date, {formatLength:'full',locale:'ja-jp',timezone:'Asia/Tokyo'}));
				// Shanghai (in zh-cn)
				doh.is("2006\u5e748\u670811\u65e5\u661f\u671f\u4e94CST\u4e0a\u53488\u65f655\u520612\u79d2", dojo.date.locale.format(date, {formatLength:'full',locale:'zh-cn',timezone:'Asia/Shanghai'}));
				// Paris (in fr-fr)
				doh.is("vendredi 11 août 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'fr-fr',timezone:'Europe/Paris'}));
				// Vienna (in de-at)
				doh.is("Freitag, 11. August 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'de-at',timezone:'Europe/Vienna'}));
				// Madrid (in es)
				doh.is("viernes, 11 de agosto de 2006 02:55:12 CEST", dojo.date.locale.format(date, {formatLength:'full',locale:'es',timezone:'Europe/Madrid'}));

				//////////////////////
				//  Tricky Dates:
				date = new Date(1225605599000); // 1 second before New York goes off DST - NY and LA are 3 hours apart
				selectorOpts = {formatLength: "full", locale: "en-us"};
				doh.is("Sunday, November 2, 2008 1:59:59 AM EDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Saturday, November 1, 2008 10:59:59 PM PDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1225605600000); // New York goes off DST - NY and LA are 2 hours apart
				doh.is("Sunday, November 2, 2008 1:00:00 AM EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Saturday, November 1, 2008 11:00:00 PM PDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1225616400000); // LA goes off DST - NY and LA are 3 hours apart again
				doh.is("Sunday, November 2, 2008 4:00:00 AM EST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/New_York'})));
				doh.is("Sunday, November 2, 2008 1:00:00 AM PST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Los_Angeles'})));

				date = new Date(1257062399000); // Denver on DST - Denver is 1 hr ahead of Phoenix
				doh.is("Sunday, November 1, 2009 1:59:59 AM MDT", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Denver'})));
				doh.is("Sunday, November 1, 2009 12:59:59 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Phoenix'})));

				date = new Date(1257062400000); // Denver off DST - Denver is same time as Phoenix
				doh.is("Sunday, November 1, 2009 1:00:00 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Denver'})));
				doh.is("Sunday, November 1, 2009 1:00:00 AM MST", dojo.date.locale.format(date, dojo.delegate(selectorOpts, {timezone:'America/Phoenix'})));
			}
		}
	]
);<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012, Martin Borho.
 * Licensed under the Affero General Public License version 3 or later.
 * See LICENSE for details.
 */
var nconf = require('nconf')
    , lib = require('../lib')
    , express = require('express')
    , socket_io = require('socket.io')
    , passport = require('passport')
    , request = require('request')
    , LocalStrategy = require('passport-local').Strategy
    , sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 })
    , parseCookie = require('connect').utils.parseCookie
    , sanitize = require('validator').sanitize
    , _base_path = __dirname+'/..';

nconf.use('file', { file: _base_path+'/config.json' });
nconf.load();

// db connection
var db = lib.storage.getDb(nconf.get('db'))

// libs and services
if(nconf.get('twitter:enabled')) {
    var twit = new lib.twitter.Twitter(nconf.get('twitter'), db);
    twit.userstream(nconf.get('twitter:user'));
}

if(nconf.get('superfeedr:enabled')) {
    lib.superfeedr.listen(db, nconf.get('superfeedr'));
}

if(nconf.get('poller:enabled')) {
    var poller = new lib.Poller(db);
    poller.start();
}

var connector = new lib.connector.Connector(db);

var app = express.createServer();
var io = socket_io.listen(app);
io.set('log level', 2)
var _SOCKET_ENDPOINT = '';

passport.use(new LocalStrategy(
    function(username, password, done) {
        if(username == nconf.get('app:user') && password == nconf.get('app:password')) {
            return done(null, {id: username});
        } else {
            return done(null, false);
        }
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
//   User.findOne(id, function (err, user) {
    done(null,  {id: id});
//   });
});

function checkSession(req, res, next) {
    if(req.user !== undefined) {
        next();
        return;
    }
    res.writeHead(301, {'Location':'/login'});
    res.end();
}

function checkAjaxSession(req, res, next) {
    if(req.user !== undefined) {
        next();
        return;
    }
    console.log('AJAX UNAUTHORIZED');
    res.writeHead(401);
    res.end();
}

// express configuration
app.configure(function() {
    app.use(express.static(_base_path + '/lib/static'));
    app.set('views', _base_path + '/lib/views');
    app.set('view engine', 'ejs');
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({store: sessionStore, secret: 'keyboard cat' }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    //app.use(basic_auth);
});

// routes
app.get('/login', function(req, res){
    res.render('login', {layout: false});
});

app.post('/login',
  passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })
);

app.get('/logout', function(req, res){
  req.logOut();
  res.redirect('/');
});

app.get('/', checkSession,  function(req, res){
    res.render('index', {locals: {
        title: 'Silozippr',
        docs: false,//docs,
        socket_endpoint: _SOCKET_ENDPOINT
    }});
});

app.get('/api/list/docs', checkAjaxSession, function(req, res){
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    var startkey = (req.query["startkey"]) ? sanitize(req.query["startkey"]).xss() : false;
    if(skey && skey !== "") {
        connector.get_source_docs(res, skey, startkey);
    } else {
        connector.get_index_docs(res, startkey);
    }
});

app.get('/api/source/clear', checkAjaxSession, function(req, res) {
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    if(skey) connector.clear_source(res, skey);
});

app.get('/api/toc/get', checkAjaxSession, function(req, res) {
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    connector.get_toc(res, skey);
});

app.post('/api/subs/add', checkAjaxSession, function(req, res) {
    connector.add_sub(req, res, nconf.get('superfeedr:enabled'));
});

app.post('/api/subs/remove', checkAjaxSession, function(req, res) {
    connector.remove_sub(req, res, nconf.get('superfeedr:enabled'));
});

app.get('/api/subs/list', checkAjaxSession, function(req, res) {
    connector.get_subs(req, res);
});

app.post('/api/tweet', checkAjaxSession, function(req, res) {
    var text = (req.body.text) ? sanitize(req.body.text).xss() : false;
    if(text && twit !== undefined) {
        twit.tweet(res, text);
    } else {
        return res.json({success:false});
    }
});

app.post('/api/retweet', checkAjaxSession, function(req, res) {
    var doc_id = (req.body.id) ? sanitize(req.body.id).xss() : false;
    if(doc_id && twit !== undefined) {
        db.get(doc_id, function(err, doc) {
            if(err || doc.custom === undefined) return res.json({success:false});
            return twit.retweet(res, doc.custom.id);
        });
    } else {
        return res.json({success:false});
    }
});

app.get('/api/url/short', checkAjaxSession, function(req, res) {
    var longurl = (req.query["url"]) ? sanitize(req.query["url"]).xss() : false;
    var api_url = 'http://is.gd/api.php?longurl='+encodeURIComponent(longurl);
    if(longurl) {
        console.log(longurl);
        var api_req = request(api_url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                res.json({success:true, short: body, long: longurl});
            } else {
                res.json({success:false});
            }
        });
    }
});

io.set('authorization', function (data, accept) {
    var cookies = parseCookie(data.headers.cookie),
        sessionId = cookies['connect.sid'];
    if(!sessionId) {
        console.log('no session id');
        return accept('No session id transmitted.', false);
    } else {
        sessionStore.get(sessionId, function(err, session) {
            if(err) {
                return accept(err, false);
            } else if(session) {
                data.sessionId = sessionId;
                data.user = session.passport.user;
                return accept(null, true);
            }
            return accept('No cookie transmitted.', false);
        });
    }
});

var pipe = io.sockets.on('connection', function (socket) {
    socket.on('removeDoc', function (doc) {
//         console.log(socket.handshake.sessionId+' :: '+socket.handshake.user);
        connector.remove_doc(socket, doc);
    });
    socket.on('removeDocs', function (data) {
        connector.remove_docs(socket, data);
    });
    socket.on('getFeedDocs', function (data) {
        if(data) {
            connector.get_feed_docs(socket, data);
        } else {
            connector.get_index_docs(socket);
        }
    });
});

var initializeStream = function() {
    db.info(function(err, info) {
        var query = {};
        if (err) {
            throw new Error(JSON.stringify(err));
            console.log("error on stream reconnect");
            console.log(JSON.stringify(err));
        }
        console.log("db info fetched");
        query = {
                include_docs:true,
                since:info.update_seq
        }
        console.log("Changes stream starting");
        db.changes(query).on('response', function (res) {
            res.on('data', function (change) {
                if(change.deleted == undefined
                    && (change.doc.type == "newsitem"
                            || change.doc.type == "tweet"
                                    || change.doc.type == "xmpp")) {
                    connector.process_pushed(change.doc, pipe);
                } /*else {
                    pipe.emit('syncDeleted', { doc: change.doc });
                }*/
            });
            res.on('end', function () {
                console.log("Changes stream ended, try restarting");
                initializeStream();
            });
        });
    });
};
initializeStream();

process.on('uncaughtException', function (err) {
  console.log('\n##### Caught exception: ######\n');
  console.log(err);
  console.log('\n#############################\n');
});

app.listen(nconf.get('app:port'), function () {
  var addr = app.address();
  console.log(' app listening on http://' + addr.address + ':' + addr.port);
});
<commit_msg>debug output for changes from db added<commit_after>/**
 * Copyright (c) 2012, Martin Borho.
 * Licensed under the Affero General Public License version 3 or later.
 * See LICENSE for details.
 */
var nconf = require('nconf')
    , lib = require('../lib')
    , express = require('express')
    , socket_io = require('socket.io')
    , passport = require('passport')
    , request = require('request')
    , LocalStrategy = require('passport-local').Strategy
    , sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 })
    , parseCookie = require('connect').utils.parseCookie
    , sanitize = require('validator').sanitize
    , _base_path = __dirname+'/..';

nconf.use('file', { file: _base_path+'/config.json' });
nconf.load();

// db connection
var db = lib.storage.getDb(nconf.get('db'))

// libs and services
if(nconf.get('twitter:enabled')) {
    var twit = new lib.twitter.Twitter(nconf.get('twitter'), db);
    twit.userstream(nconf.get('twitter:user'));
}

if(nconf.get('superfeedr:enabled')) {
    lib.superfeedr.listen(db, nconf.get('superfeedr'));
}

if(nconf.get('poller:enabled')) {
    var poller = new lib.Poller(db);
    poller.start();
}

var connector = new lib.connector.Connector(db);

var app = express.createServer();
var io = socket_io.listen(app);
io.set('log level', 2)
var _SOCKET_ENDPOINT = '';

passport.use(new LocalStrategy(
    function(username, password, done) {
        if(username == nconf.get('app:user') && password == nconf.get('app:password')) {
            return done(null, {id: username});
        } else {
            return done(null, false);
        }
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
//   User.findOne(id, function (err, user) {
    done(null,  {id: id});
//   });
});

function checkSession(req, res, next) {
    if(req.user !== undefined) {
        next();
        return;
    }
    res.writeHead(301, {'Location':'/login'});
    res.end();
}

function checkAjaxSession(req, res, next) {
    if(req.user !== undefined) {
        next();
        return;
    }
    console.log('AJAX UNAUTHORIZED');
    res.writeHead(401);
    res.end();
}

// express configuration
app.configure(function() {
    app.use(express.static(_base_path + '/lib/static'));
    app.set('views', _base_path + '/lib/views');
    app.set('view engine', 'ejs');
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({store: sessionStore, secret: 'keyboard cat' }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    //app.use(basic_auth);
});

// routes
app.get('/login', function(req, res){
    res.render('login', {layout: false});
});

app.post('/login',
  passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })
);

app.get('/logout', function(req, res){
  req.logOut();
  res.redirect('/');
});

app.get('/', checkSession,  function(req, res){
    res.render('index', {locals: {
        title: 'Silozippr',
        docs: false,//docs,
        socket_endpoint: _SOCKET_ENDPOINT
    }});
});

app.get('/api/list/docs', checkAjaxSession, function(req, res){
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    var startkey = (req.query["startkey"]) ? sanitize(req.query["startkey"]).xss() : false;
    if(skey && skey !== "") {
        connector.get_source_docs(res, skey, startkey);
    } else {
        connector.get_index_docs(res, startkey);
    }
});

app.get('/api/source/clear', checkAjaxSession, function(req, res) {
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    if(skey) connector.clear_source(res, skey);
});

app.get('/api/toc/get', checkAjaxSession, function(req, res) {
    var skey = (req.query["id"]) ? sanitize(req.query["id"]).xss() : false;
    connector.get_toc(res, skey);
});

app.post('/api/subs/add', checkAjaxSession, function(req, res) {
    connector.add_sub(req, res, nconf.get('superfeedr:enabled'));
});

app.post('/api/subs/remove', checkAjaxSession, function(req, res) {
    connector.remove_sub(req, res, nconf.get('superfeedr:enabled'));
});

app.get('/api/subs/list', checkAjaxSession, function(req, res) {
    connector.get_subs(req, res);
});

app.post('/api/tweet', checkAjaxSession, function(req, res) {
    var text = (req.body.text) ? sanitize(req.body.text).xss() : false;
    if(text && twit !== undefined) {
        twit.tweet(res, text);
    } else {
        return res.json({success:false});
    }
});

app.post('/api/retweet', checkAjaxSession, function(req, res) {
    var doc_id = (req.body.id) ? sanitize(req.body.id).xss() : false;
    if(doc_id && twit !== undefined) {
        db.get(doc_id, function(err, doc) {
            if(err || doc.custom === undefined) return res.json({success:false});
            return twit.retweet(res, doc.custom.id);
        });
    } else {
        return res.json({success:false});
    }
});

app.get('/api/url/short', checkAjaxSession, function(req, res) {
    var longurl = (req.query["url"]) ? sanitize(req.query["url"]).xss() : false;
    var api_url = 'http://is.gd/api.php?longurl='+encodeURIComponent(longurl);
    if(longurl) {
        console.log(longurl);
        var api_req = request(api_url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                res.json({success:true, short: body, long: longurl});
            } else {
                res.json({success:false});
            }
        });
    }
});

io.set('authorization', function (data, accept) {
    var cookies = parseCookie(data.headers.cookie),
        sessionId = cookies['connect.sid'];
    if(!sessionId) {
        console.log('no session id');
        return accept('No session id transmitted.', false);
    } else {
        sessionStore.get(sessionId, function(err, session) {
            if(err) {
                return accept(err, false);
            } else if(session) {
                data.sessionId = sessionId;
                data.user = session.passport.user;
                return accept(null, true);
            }
            return accept('No cookie transmitted.', false);
        });
    }
});

var pipe = io.sockets.on('connection', function (socket) {
    socket.on('removeDoc', function (doc) {
//         console.log(socket.handshake.sessionId+' :: '+socket.handshake.user);
        connector.remove_doc(socket, doc);
    });
    socket.on('removeDocs', function (data) {
        connector.remove_docs(socket, data);
    });
    socket.on('getFeedDocs', function (data) {
        if(data) {
            connector.get_feed_docs(socket, data);
        } else {
            connector.get_index_docs(socket);
        }
    });
});

var initializeStream = function() {
    db.info(function(err, info) {
        var query = {};
        if (err) {
            throw new Error(JSON.stringify(err));
            console.log("error on stream reconnect");
            console.log(JSON.stringify(err));
        }
        console.log("db info fetched");
        query = {
                include_docs:true,
                since:info.update_seq
        }
        console.log("Changes stream starting");
        db.changes(query).on('response', function (res) {
            res.on('data', function (change) {
                console.log("doc received from couchdb");
                if(change.deleted == undefined
                    && (change.doc.type == "newsitem"
                            || change.doc.type == "tweet"
                                    || change.doc.type == "xmpp")) {
                    connector.process_pushed(change.doc, pipe);
                } /*else {
                    pipe.emit('syncDeleted', { doc: change.doc });
                }*/
            });
            res.on('end', function () {
                console.log("Changes stream ended, try restarting");
                initializeStream();
            });
        });
    });
};
initializeStream();

process.on('uncaughtException', function (err) {
  console.log('\n##### Caught exception: ######\n');
  console.log(err);
  console.log('\n#############################\n');
});

app.listen(nconf.get('app:port'), function () {
  var addr = app.address();
  console.log(' app listening on http://' + addr.address + ':' + addr.port);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const onml = require('onml');
const json5 = require('json5');
const argv = require('yargs').argv;

const styles = {};

const marker1 = ['marker',
    {
        id: 'arrowhead',
        style: 'fill:#0041c4',
        markerHeight: 7,
        markerWidth: 10,
        markerUnits: 'strokeWidth',
        viewBox: '0 -4 11 8',
        refX: 15,
        refY: 0,
        orient: 'auto'
    },
    ['path', {'d':'M0 -4 11 0 0 4z'}]
];

const marker2 = ['marker',
    {
        id: 'arrowtail',
        style: 'fill:#0041c4',
        markerHeight: 7,
        markerWidth: 10,
        markerUnits: 'strokeWidth',
        viewBox: '-11 -4 11 8',
        refX: -15,
        refY: 0,
        orient: 'auto'
    },
    ['path', {'d':'M0 -4 -11 0 0 4z'}]
];

const defs = ['defs'];

const style = ['style', {type: 'text/css'}];

const getDefStyle = () => `
  text{
    font-size: 11pt;
    font-style: normal;
    font-variant: normal;
    font-weight: normal;
    font-stretch: normal;
    text-align: center;
    fill-opacity: 1;
    font-family: Helvetica
  }
  .h1 { font-size: 33pt; font-weight: bold }
  .h2 { font-size: 27pt; font-weight: bold }
  .h3 { font-size: 20pt; font-weight: bold }
  .h4 { font-size: 14pt; font-weight: bold }
  .h5 { font-size: 11pt; font-weight: bold }
  .h6 { font-size: 8pt;  font-weight: bold }
`.replace(/\s+/g, '');

const res = ['svg',
    {
        id: 'svg',
        xmlns: 'http://www.w3.org/2000/svg',
        'xmlns:xlink': 'http://www.w3.org/1999/xlink',
        height: '0'
    },
    style,
    defs,
    ['g', {id: 'waves'}, ['g', {id: 'lanes'}], ['g', {id: 'groups'}]]
];

function getFill (fillClasses, node) {
    const m = node.attr.style.match(/fill:(#[0-9a-fA-F]+);/);
    if (m) {
        const fill = m[1];
        const texts = node.full[2][2].split(':');
        const attr = texts[0];
        const klass = texts[1];
        if (attr === 'fill') {
            fillClasses[klass] = fill;
            console.error(attr, klass, fill);
        }
    }
}

function f2o (name, cb) {
    var full, ml;
    full = path.resolve(process.cwd(), name);
    fs.readFile(full, { encoding: 'utf8'}, function (err, dat) {
        if (err) { throw err; }
        ml = onml.parse(dat);
        const fillClasses = {
            '.muted': '#aaa',
            '.warning': '#f6b900',
            '.error': '#f60000',
            '.info': '#0041c4',
            '.success': '#00ab00'
        };
        onml.traverse(ml, {
            leave: function (node) {
                switch(node.name) {
                case 'g':
                    delete node.attr.transform;
                    defs.push(node.full);
                    break;
                case 'rect':
                    delete node.attr.id;
                    break;
                case 'text':
                    getFill(fillClasses, node);
                    break;
                case 'path':
                    delete node.attr.id;
                    if (styles[node.attr.style] === undefined) {
                        styles[node.attr.style] = 's' + (Object.keys(styles).length + 1);
                    }
                    node.attr['class'] = styles[node.attr.style];
                    delete node.attr.style;
                    delete node.attr['sodipodi:nodetypes'];
                    delete node.attr['inkscape:connector-curvature'];
                    break;
                }
            }
        });
        defs.push(marker1);
        defs.push(marker2);

        const fills = Object.keys(fillClasses).map(key =>
            key + '{fill:' + fillClasses[key] + '}');

        const extra = Object.keys(styles).map(key =>
            '.' + styles[key] + '{' + key + '}');

        style.push(getDefStyle() + fills.join('') + extra.join(''));
        // cb('module.exports = ' + jsof.stringify(res) + ';');
        cb(
            'var WaveSkin=WaveSkin||{};WaveSkin.' +
            path.basename(name, '.svg') + '=' +
            json5.stringify(res) +
            ';\ntry { module.exports = WaveSkin; } catch(err) {}\n'
        );
    });
}

if (typeof argv.i === 'string') {
    f2o(argv.i, console.log);
}

/* eslint no-console: 0 */
<commit_msg>var -> const<commit_after>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const onml = require('onml');
const json5 = require('json5');
const argv = require('yargs').argv;

const styles = {};

const marker1 = ['marker',
    {
        id: 'arrowhead',
        style: 'fill:#0041c4',
        markerHeight: 7,
        markerWidth: 10,
        markerUnits: 'strokeWidth',
        viewBox: '0 -4 11 8',
        refX: 15,
        refY: 0,
        orient: 'auto'
    },
    ['path', {'d':'M0 -4 11 0 0 4z'}]
];

const marker2 = ['marker',
    {
        id: 'arrowtail',
        style: 'fill:#0041c4',
        markerHeight: 7,
        markerWidth: 10,
        markerUnits: 'strokeWidth',
        viewBox: '-11 -4 11 8',
        refX: -15,
        refY: 0,
        orient: 'auto'
    },
    ['path', {'d':'M0 -4 -11 0 0 4z'}]
];

const defs = ['defs'];

const style = ['style', {type: 'text/css'}];

const getDefStyle = () => `
  text{
    font-size: 11pt;
    font-style: normal;
    font-variant: normal;
    font-weight: normal;
    font-stretch: normal;
    text-align: center;
    fill-opacity: 1;
    font-family: Helvetica
  }
  .h1 { font-size: 33pt; font-weight: bold }
  .h2 { font-size: 27pt; font-weight: bold }
  .h3 { font-size: 20pt; font-weight: bold }
  .h4 { font-size: 14pt; font-weight: bold }
  .h5 { font-size: 11pt; font-weight: bold }
  .h6 { font-size: 8pt;  font-weight: bold }
`.replace(/\s+/g, '');

const res = ['svg',
    {
        id: 'svg',
        xmlns: 'http://www.w3.org/2000/svg',
        'xmlns:xlink': 'http://www.w3.org/1999/xlink',
        height: '0'
    },
    style,
    defs,
    ['g', {id: 'waves'}, ['g', {id: 'lanes'}], ['g', {id: 'groups'}]]
];

function getFill (fillClasses, node) {
    const m = node.attr.style.match(/fill:(#[0-9a-fA-F]+);/);
    if (m) {
        const fill = m[1];
        const texts = node.full[2][2].split(':');
        const attr = texts[0];
        const klass = texts[1];
        if (attr === 'fill') {
            fillClasses[klass] = fill;
            console.error(attr, klass, fill);
        }
    }
}

function f2o (name, cb) {
    const full = path.resolve(process.cwd(), name);
    fs.readFile(full, { encoding: 'utf8'}, function (err, dat) {
        if (err) { throw err; }
        const ml = onml.parse(dat);
        const fillClasses = {
            '.muted': '#aaa',
            '.warning': '#f6b900',
            '.error': '#f60000',
            '.info': '#0041c4',
            '.success': '#00ab00'
        };
        onml.traverse(ml, {
            leave: function (node) {
                switch(node.name) {
                case 'g':
                    delete node.attr.transform;
                    defs.push(node.full);
                    break;
                case 'rect':
                    delete node.attr.id;
                    break;
                case 'text':
                    getFill(fillClasses, node);
                    break;
                case 'path':
                    delete node.attr.id;
                    if (styles[node.attr.style] === undefined) {
                        styles[node.attr.style] = 's' + (Object.keys(styles).length + 1);
                    }
                    node.attr['class'] = styles[node.attr.style];
                    delete node.attr.style;
                    delete node.attr['sodipodi:nodetypes'];
                    delete node.attr['inkscape:connector-curvature'];
                    break;
                }
            }
        });
        defs.push(marker1);
        defs.push(marker2);

        const fills = Object.keys(fillClasses).map(key =>
            key + '{fill:' + fillClasses[key] + '}');

        const extra = Object.keys(styles).map(key =>
            '.' + styles[key] + '{' + key + '}');

        style.push(getDefStyle() + fills.join('') + extra.join(''));
        // cb('module.exports = ' + jsof.stringify(res) + ';');
        cb(
            'var WaveSkin=WaveSkin||{};WaveSkin.' +
            path.basename(name, '.svg') + '=' +
            json5.stringify(res) +
            ';\ntry { module.exports = WaveSkin; } catch(err) {}\n'
        );
    });
}

if (typeof argv.i === 'string') {
    f2o(argv.i, console.log);
}

/* eslint no-console: 0 */
<|endoftext|>


<commit_before>/**
 * tarita (たりた)
 * https://github.com/paazmaya/tarita
 *
 * Convert Require.js define to ES7 imports
 *
 * Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (http://www.paazmaya.fi)
 * Licensed under the MIT license
 */
'use strict';

const fs = require('fs'),
  path = require('path');

const tarita = require('../index');

/**
 * Read the given file and return a string
 *
 * @param {string} filepath
 * @returns {string} Contents of the file
 */
const readFile = (filepath) => fs.readFileSync(filepath, 'utf8');

/**
 * Write the string contents to a file
 *
 * @param {string} filepath
 * @param {string} content
 */
const writeFile = (filepath, content) => fs.writeFileSync(filepath, content, 'utf8');
<commit_msg>Option configuration<commit_after>#!/usr/bin/env node

/**
 * tarita (たりた)
 * https://github.com/paazmaya/tarita
 *
 * Convert Require.js define to ES7 imports
 *
 * Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (http://www.paazmaya.fi)
 * Licensed under the MIT license
 */
'use strict';

const fs = require('fs'),
  path = require('path');

const optionator = require('optionator');

const tarita = require('../index');

/**
 * Read the given file and return a string
 *
 * @param {string} filepath
 * @returns {string} Contents of the file
 */
const readFile = (filepath) => fs.readFileSync(filepath, 'utf8');

/**
 * Write the string contents to a file
 *
 * @param {string} filepath
 * @param {string} content
 */
const writeFile = (filepath, content) => fs.writeFileSync(filepath, content, 'utf8');

let pkg;

try {
  const packageJson = fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8');
  pkg = JSON.parse(packageJson);
}
catch (error) {
  console.error('Could not read/parse "package.json", quite strange...');
  console.error(error);
  process.exit(1);
}

const optsParser = optionator({
  prepend: `${pkg.name} [options] <file|directory>`,
  append: `Version ${pkg.version}`,
  options: [
    {
      option: 'help',
      alias: 'h',
      type: 'Boolean',
      default: false,
      description: 'Help and usage instructions'
    },
    {
      option: 'version',
      alias: 'V',
      type: 'Boolean',
      default: false,
      description: 'Version number'
    },
    {
      option: 'verbose',
      alias: 'v',
      type: 'Boolean',
      default: false,
      description: 'Verbose output, will print which file is currently being processed'
    },
    {
      option: 'match',
      alias: 'M',
      type: 'String',
      default: '\\.js$',
      description: 'Regular expression for matching and filtering files'
    },
    {
      option: 'recursive',
      alias: 'r',
      type: 'Boolean',
      default: false,
      description: 'Recursively search matching files'
    }
  ]
});

let opts;

try {
  opts = optsParser.parse(process.argv);
}
catch (error) {
  console.error(error.message);
  process.exit(1);
}

if (opts.version) {
  console.log((opts.verbose ? pkg.name + ' v' : '') + pkg.version);
  process.exit();
}

if (opts.help || opts._.length === 0) {
  console.log(optsParser.generateHelp());
  process.exit();
}

// List of files that will be processed
const fileList = [];

// Expression to match file paths against
const matcher = new RegExp(opts.match);

/**
 * Determine if the given existing filepath is a file or directory
 * and continue with filtering and recursive when needed.
 *
 * @param {string} filepath Resolved filepath that exists
 * @param {bool} recurse Should a directory be entered
 * @returns {void}
 */
const handleFilepath = (filepath, recurse) => {
  const stat = fs.statSync(filepath);
  if (stat.isDirectory() && recurse) {
    const list = fs.readdirSync(filepath);

    list.forEach((item) => {
      handleFilepath(path.join(filepath, item), opts.recursive);
    });
  }
  else if (filepath.match(matcher) && stat.isFile()) {
    fileList.push(filepath);
  }
};

opts._.forEach((item) => {
  console.log(item);
  const filepath = path.resolve(item);
  if (!fs.existsSync(filepath)) {
    console.error(`File (${filepath}) not found`);
  }
  else {
    // It is ok to enter the directory on the first level
    handleFilepath(filepath, true);
  }
});

console.log(`Going to process total of ${fileList.length} files`);

// Process then...
<|endoftext|>


<commit_before>var _ = require('lodash');
var assert = require('assert');

var vumigo = require('../lib');
var structs = vumigo.structs;
var Model = structs.Model;

describe("models", function() {
    describe("Model", function() {
        describe(".clear", function() {
            it("should clear all of the model's attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: 'qux'
                });

                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'qux'
                });

                model.clear();

                assert.deepEqual(model, {});
            });
        });

        describe(".reset", function() {
            it("should validate the model", function() {
                var model = new Model();

                var validated = false;
                model.cls.validate = function() {
                    validated = true;
                };

                model.reset();
                assert(validated);
            });

            it("should reset the model's attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: 'qux'
                });

                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'qux'
                });

                model.reset({
                    foo: 'lorem',
                    lerp: 'larp'
                });

                assert.deepEqual(model, {
                    foo: 'lorem',
                    lerp: 'larp'
                });
            });

            it("should apply the model's default attributes", function() {
                var model = new Model();

                model.cls.defaults = {
                    'foo': 'lerp',
                    'baz': 'larp'
                };

                model.reset({foo: 'bar'});
                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'larp'
                });
            });
        });

        describe(".serialize", function() {
            it("should validate the model", function() {
                var model = new Model();

                var validated = false;
                model.cls.validate = function() {
                    validated = true;
                };

                model.serialize();
                assert(validated);
            });

            it("should return a deep copy of its attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: 'qux'
                });

                var data = model.serialize();
                assert.deepEqual(data, {
                    foo: 'bar',
                    baz: 'qux'
                });

                data.foo = 'spam';
                assert.equal(model.foo, 'bar');
            });
        });

        it("should allow only model attributes to be enumerable", function() {
            var model = new Model({foo: 'bar'});
            model.cls.spam = 'ham';
            assert.deepEqual(_.keys(model), ['foo']);
        });

        it("should allow model class properties to be directly accessible",
        function() {
            var model = new Model();
            model.cls.spam = 'ham';
            assert.equal(model.spam, 'ham');
        });

        describe(".extend", function() {
            it("should set up the child's prototype chain", function() {
                var Parent = Model.extend(function() {});
                var Child = Parent.extend(function() {});

                var p = new Parent();
                var c = new Child();

                assert(p instanceof Model);
                assert(p instanceof Parent);

                assert(c instanceof Model);
                assert(c instanceof Parent);
                assert(c instanceof Child);
            });

            it("should set the parent's static methods on the child",
            function() {
                var Parent = Model.extend(function() {});
                assert.equal(Parent.extend, Model.extend);
                Parent.foo = 'bar';

                var Child = Parent.extend(function() {});
                assert.equal(Child.extend, Parent.extend);
                assert.equal(Child.foo, Parent.foo);
            });

            describe("the constructor's context", function() {
                it("should be the first arg of the constructor", function() {
                    var Thing = Model.extend(function(self) {
                        assert.strictEqual(self, this);
                    });

                    new Thing();
                });
            });
        });
    });
});
<commit_msg>Better deep copy test for Model.serialize()<commit_after>var _ = require('lodash');
var assert = require('assert');

var vumigo = require('../lib');
var structs = vumigo.structs;
var Model = structs.Model;

describe("models", function() {
    describe("Model", function() {
        describe(".clear", function() {
            it("should clear all of the model's attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: 'qux'
                });

                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'qux'
                });

                model.clear();

                assert.deepEqual(model, {});
            });
        });

        describe(".reset", function() {
            it("should validate the model", function() {
                var model = new Model();

                var validated = false;
                model.cls.validate = function() {
                    validated = true;
                };

                model.reset();
                assert(validated);
            });

            it("should reset the model's attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: 'qux'
                });

                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'qux'
                });

                model.reset({
                    foo: 'lorem',
                    lerp: 'larp'
                });

                assert.deepEqual(model, {
                    foo: 'lorem',
                    lerp: 'larp'
                });
            });

            it("should apply the model's default attributes", function() {
                var model = new Model();

                model.cls.defaults = {
                    'foo': 'lerp',
                    'baz': 'larp'
                };

                model.reset({foo: 'bar'});
                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: 'larp'
                });
            });
        });

        describe(".serialize", function() {
            it("should validate the model", function() {
                var model = new Model();

                var validated = false;
                model.cls.validate = function() {
                    validated = true;
                };

                model.serialize();
                assert(validated);
            });

            it("should return a deep copy of its attributes", function() {
                var model = new Model({
                    foo: 'bar',
                    baz: {qux: 'corge'}
                });

                var data = model.serialize();
                assert.deepEqual(data, {
                    foo: 'bar',
                    baz: {qux: 'corge'}
                });

                data.foo = 'spam';
                data.baz.qux = 'ham';

                assert.deepEqual(model, {
                    foo: 'bar',
                    baz: {qux: 'corge'}
                });
            });
        });

        it("should allow only model attributes to be enumerable", function() {
            var model = new Model({foo: 'bar'});
            model.cls.spam = 'ham';
            assert.deepEqual(_.keys(model), ['foo']);
        });

        it("should allow model class properties to be directly accessible",
        function() {
            var model = new Model();
            model.cls.spam = 'ham';
            assert.equal(model.spam, 'ham');
        });

        describe(".extend", function() {
            it("should set up the child's prototype chain", function() {
                var Parent = Model.extend(function() {});
                var Child = Parent.extend(function() {});

                var p = new Parent();
                var c = new Child();

                assert(p instanceof Model);
                assert(p instanceof Parent);

                assert(c instanceof Model);
                assert(c instanceof Parent);
                assert(c instanceof Child);
            });

            it("should set the parent's static methods on the child",
            function() {
                var Parent = Model.extend(function() {});
                assert.equal(Parent.extend, Model.extend);
                Parent.foo = 'bar';

                var Child = Parent.extend(function() {});
                assert.equal(Child.extend, Parent.extend);
                assert.equal(Child.foo, Parent.foo);
            });

            describe("the constructor's context", function() {
                it("should be the first arg of the constructor", function() {
                    var Thing = Model.extend(function(self) {
                        assert.strictEqual(self, this);
                    });

                    new Thing();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>// EVENT TESTS
// ===========
//
// TODO: add moar tests

(function () {

	var fixture, createEvent, testDiv, compareHTML;

	module( 'Events' );

	fixture = document.getElementById( 'qunit-fixture' );

	try {
		new Event( 'click' );

		createEvent = function ( eventType, params ) {
			return new Event( eventType, params );
		};
	}

	catch ( err ) {
		createEvent = function ( eventType, params ) {
			var event, args;

			event = document.createEvent( 'Event' );

			args = [
				eventType
			]

			event.initEvent( eventType );

			return event;
		};
	}

	testDiv = document.createElement( 'div' );

	// necessary because IE is a goddamned nuisance
	compareHTML = function ( actual, expected ) {
		testDiv.innerHTML = actual;
		actual = testDiv.innerHTML;

		testDiv.innerHTML = expected;
		expected = testDiv.innerHTML;

		return actual === expected;
	};

	test( 'on-click="someEvent" fires an event when user clicks the element', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me'
		});

		ractive.on( 'someEvent', function ( event ) {
			t.ok( true );
			t.equal( event.original.type, 'click' );
		});

		simulant.fire( ractive.nodes.test, 'click' );
	});

	test( 'Standard events have correct properties: node, original, keypath, context, index', function ( t ) {
		var ractive, fakeEvent;

		expect( 5 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me'
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.node, ractive.nodes.test );
			t.equal( event.original, fakeEvent );
			t.equal( event.keypath, '' );
			t.equal( event.context, ractive.data );
			t.equal( event.index, undefined );
		});

		fakeEvent = simulant( 'click' );

		simulant.fire( ractive.nodes.test, fakeEvent );
	});

	test( 'event.keypath is set to the innermost context', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#foo}}click me{{/foo}}',
			data: {
				foo: { bar: 'test' }
			}
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.keypath, 'foo' );
			t.equal( event.context.bar, 'test' );
		});

		simulant.fire( ractive.nodes.test, 'click' );
	});

	test( 'event.index stores current indices against their references', function ( t ) {
		var ractive;

		expect( 4 );

		ractive = new Ractive({
			el: fixture,
			template: '
{{#array:i}}
{{i}}: {{.}}
{{/array}}
',
			data: {
				array: [ 'a', 'b', 'c', 'd', 'e' ]
			}
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.node.innerHTML, '2: c' );
			t.equal( event.keypath, 'array.2' );
			t.equal( event.context, 'c' );
			t.deepEqual( event.index, { i: 2 })
		});

		simulant.fire( ractive.nodes.item_2, 'click' );
	});

	test( 'event.index reports nested indices correctly', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#foo:x}}{{#bar:y}}{{#baz:z}}{{x}}{{y}}{{z}}{{/baz}}{{/bar}}{{/foo}}',
			data: {
				foo: [
					{
						bar: [
							{
								baz: [ 1, 2, 3 ]
							}
						]
					}
				]
			}
		});

		t.equal( ractive.nodes.test_001.innerHTML, '001' );

		ractive.on( 'someEvent', function ( event ) {
			t.deepEqual( event.index, { x: 0, y: 0, z: 1 })
		});

		simulant.fire( ractive.nodes.test_001, 'click' );
	});

	test( 'proxy events can have dynamic names', function ( t ) {
		var ractive, last;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me',
			data: { something: 'foo' }
		});

		ractive.on({
			do_foo: function ( event ) {
				last = 'foo';
			},
			do_bar: function ( event ) {
				last = 'bar';
			}
		});

		simulant.fire( ractive.nodes.test, 'click' );
		t.equal( last, 'foo' );

		ractive.set( 'something', 'bar' );

		simulant.fire( ractive.nodes.test, 'click' );
		t.equal( last, 'bar' );
	});

	test( 'proxy event parameters are correctly parsed as JSON, or treated as a string', function ( t ) {
		var ractive, last;

		expect( 3 );

		ractive = new Ractive({
			el: fixture,
			template: 'click meclick meclick me'
		});

		ractive.on({
			log: function ( event, params ) {
				last = params;
			}
		});

		simulant.fire( ractive.nodes.foo, 'click' );
		t.equal( last, 'one' );

		simulant.fire( ractive.nodes.bar, 'click' );
		t.deepEqual( last, { bar: true } );

		simulant.fire( ractive.nodes.baz, 'click' );
		t.deepEqual( last, [ 1, 2, 3 ] );
	});

	test( 'Splicing arrays correctly modifies proxy events', function ( t ) {
		var ractive;

		expect( 4 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#buttons:i}}<button id="button_{{i}}" on-click="remove:{{i}}">click me</button>{{/buttons}}',
			data: { buttons: new Array(5) }
		});

		ractive.on( 'remove', function ( event, num ) {
			this.get( 'buttons' ).splice( num, 1 );
		});

		t.equal( ractive.findAll( 'button' ).length, 5 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 4 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 3 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 2 );
	});

	test( 'Splicing arrays correctly modifies two-way bindings', function ( t ) {
		var ractive, items;

		expect( 25 );

		items = [
			{ description: 'one' },
			{ description: 'two', done: true },
			{ description: 'three' }
		];

		ractive = new Ractive({
			el: fixture,
			template: '
{{#items:i}}
<input id="input_{{i}}" type="checkbox" checked="{{.done}}"> {{description}}
{{/items}}
',
			data: { items: items }
		});

		// 1-3
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, true );
		t.equal( ractive.nodes.input_2.checked, false );

		// 4-6
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), true );
		t.equal( !!ractive.get( 'items.2.done' ), false );

		simulant.fire( ractive.nodes.input_0, 'click' );

		// 7-9
		t.equal( ractive.nodes.input_0.checked, true );
		t.equal( ractive.nodes.input_1.checked, true );
		t.equal( ractive.nodes.input_2.checked, false );

		// 10-12
		t.equal( !!ractive.get( 'items.0.done' ), true );
		t.equal( !!ractive.get( 'items.1.done' ), true );
		t.equal( !!ractive.get( 'items.2.done' ), false );

		items.shift();

		// 13-14
		t.equal( ractive.nodes.input_0.checked, true );
		t.equal( ractive.nodes.input_1.checked, false );

		// 15-16
		t.equal( !!ractive.get( 'items.0.done' ), true );
		t.equal( !!ractive.get( 'items.1.done' ), false );

		simulant.fire( ractive.nodes.input_0, 'click' );

		// 17-18
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, false );

		// 19-20
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), false );

		simulant.fire( ractive.nodes.input_1, 'click' );

		// 21-22
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, true );

		// 23-24
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), true );

		// 25
		t.equal( ractive.findAll( 'input' ).length, 2 );
	});

}());<commit_msg>added test for #158, plus general tap event test<commit_after>// EVENT TESTS
// ===========
//
// TODO: add moar tests

(function () {

	var fixture, createEvent, testDiv, compareHTML;

	module( 'Events' );

	fixture = document.getElementById( 'qunit-fixture' );

	try {
		new Event( 'click' );

		createEvent = function ( eventType, params ) {
			return new Event( eventType, params );
		};
	}

	catch ( err ) {
		createEvent = function ( eventType, params ) {
			var event, args;

			event = document.createEvent( 'Event' );

			args = [
				eventType
			]

			event.initEvent( eventType );

			return event;
		};
	}

	testDiv = document.createElement( 'div' );

	// necessary because IE is a goddamned nuisance
	compareHTML = function ( actual, expected ) {
		testDiv.innerHTML = actual;
		actual = testDiv.innerHTML;

		testDiv.innerHTML = expected;
		expected = testDiv.innerHTML;

		return actual === expected;
	};

	test( 'on-click="someEvent" fires an event when user clicks the element', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me'
		});

		ractive.on( 'someEvent', function ( event ) {
			t.ok( true );
			t.equal( event.original.type, 'click' );
		});

		simulant.fire( ractive.nodes.test, 'click' );
	});

	test( 'Standard events have correct properties: node, original, keypath, context, index', function ( t ) {
		var ractive, fakeEvent;

		expect( 5 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me'
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.node, ractive.nodes.test );
			t.equal( event.original, fakeEvent );
			t.equal( event.keypath, '' );
			t.equal( event.context, ractive.data );
			t.equal( event.index, undefined );
		});

		fakeEvent = simulant( 'click' );

		simulant.fire( ractive.nodes.test, fakeEvent );
	});

	test( 'event.keypath is set to the innermost context', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#foo}}click me{{/foo}}',
			data: {
				foo: { bar: 'test' }
			}
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.keypath, 'foo' );
			t.equal( event.context.bar, 'test' );
		});

		simulant.fire( ractive.nodes.test, 'click' );
	});

	test( 'event.index stores current indices against their references', function ( t ) {
		var ractive;

		expect( 4 );

		ractive = new Ractive({
			el: fixture,
			template: '
{{#array:i}}
{{i}}: {{.}}
{{/array}}
',
			data: {
				array: [ 'a', 'b', 'c', 'd', 'e' ]
			}
		});

		ractive.on( 'someEvent', function ( event ) {
			t.equal( event.node.innerHTML, '2: c' );
			t.equal( event.keypath, 'array.2' );
			t.equal( event.context, 'c' );
			t.deepEqual( event.index, { i: 2 })
		});

		simulant.fire( ractive.nodes.item_2, 'click' );
	});

	test( 'event.index reports nested indices correctly', function ( t ) {
		var ractive;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#foo:x}}{{#bar:y}}{{#baz:z}}{{x}}{{y}}{{z}}{{/baz}}{{/bar}}{{/foo}}',
			data: {
				foo: [
					{
						bar: [
							{
								baz: [ 1, 2, 3 ]
							}
						]
					}
				]
			}
		});

		t.equal( ractive.nodes.test_001.innerHTML, '001' );

		ractive.on( 'someEvent', function ( event ) {
			t.deepEqual( event.index, { x: 0, y: 0, z: 1 })
		});

		simulant.fire( ractive.nodes.test_001, 'click' );
	});

	test( 'proxy events can have dynamic names', function ( t ) {
		var ractive, last;

		expect( 2 );

		ractive = new Ractive({
			el: fixture,
			template: 'click me',
			data: { something: 'foo' }
		});

		ractive.on({
			do_foo: function ( event ) {
				last = 'foo';
			},
			do_bar: function ( event ) {
				last = 'bar';
			}
		});

		simulant.fire( ractive.nodes.test, 'click' );
		t.equal( last, 'foo' );

		ractive.set( 'something', 'bar' );

		simulant.fire( ractive.nodes.test, 'click' );
		t.equal( last, 'bar' );
	});

	test( 'proxy event parameters are correctly parsed as JSON, or treated as a string', function ( t ) {
		var ractive, last;

		expect( 3 );

		ractive = new Ractive({
			el: fixture,
			template: 'click meclick meclick me'
		});

		ractive.on({
			log: function ( event, params ) {
				last = params;
			}
		});

		simulant.fire( ractive.nodes.foo, 'click' );
		t.equal( last, 'one' );

		simulant.fire( ractive.nodes.bar, 'click' );
		t.deepEqual( last, { bar: true } );

		simulant.fire( ractive.nodes.baz, 'click' );
		t.deepEqual( last, [ 1, 2, 3 ] );
	});

	test( 'Splicing arrays correctly modifies proxy events', function ( t ) {
		var ractive;

		expect( 4 );

		ractive = new Ractive({
			el: fixture,
			template: '{{#buttons:i}}<button id="button_{{i}}" on-click="remove:{{i}}">click me</button>{{/buttons}}',
			data: { buttons: new Array(5) }
		});

		ractive.on( 'remove', function ( event, num ) {
			this.get( 'buttons' ).splice( num, 1 );
		});

		t.equal( ractive.findAll( 'button' ).length, 5 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 4 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 3 );

		simulant.fire( ractive.nodes.button_2, 'click' );
		t.equal( ractive.findAll( 'button' ).length, 2 );
	});

	test( 'Splicing arrays correctly modifies two-way bindings', function ( t ) {
		var ractive, items;

		expect( 25 );

		items = [
			{ description: 'one' },
			{ description: 'two', done: true },
			{ description: 'three' }
		];

		ractive = new Ractive({
			el: fixture,
			template: '
{{#items:i}}
<input id="input_{{i}}" type="checkbox" checked="{{.done}}"> {{description}}
{{/items}}
',
			data: { items: items }
		});

		// 1-3
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, true );
		t.equal( ractive.nodes.input_2.checked, false );

		// 4-6
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), true );
		t.equal( !!ractive.get( 'items.2.done' ), false );

		simulant.fire( ractive.nodes.input_0, 'click' );

		// 7-9
		t.equal( ractive.nodes.input_0.checked, true );
		t.equal( ractive.nodes.input_1.checked, true );
		t.equal( ractive.nodes.input_2.checked, false );

		// 10-12
		t.equal( !!ractive.get( 'items.0.done' ), true );
		t.equal( !!ractive.get( 'items.1.done' ), true );
		t.equal( !!ractive.get( 'items.2.done' ), false );

		items.shift();

		// 13-14
		t.equal( ractive.nodes.input_0.checked, true );
		t.equal( ractive.nodes.input_1.checked, false );

		// 15-16
		t.equal( !!ractive.get( 'items.0.done' ), true );
		t.equal( !!ractive.get( 'items.1.done' ), false );

		simulant.fire( ractive.nodes.input_0, 'click' );

		// 17-18
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, false );

		// 19-20
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), false );

		simulant.fire( ractive.nodes.input_1, 'click' );

		// 21-22
		t.equal( ractive.nodes.input_0.checked, false );
		t.equal( ractive.nodes.input_1.checked, true );

		// 23-24
		t.equal( !!ractive.get( 'items.0.done' ), false );
		t.equal( !!ractive.get( 'items.1.done' ), true );

		// 25
		t.equal( ractive.findAll( 'input' ).length, 2 );
	});

	test( 'Mousedown followed by click results in a tap event', function ( t ) {
		var ractive, tapped;

		ractive = new Ractive({
			el: fixture,
			template: 'tap me'
		});

		ractive.on( 'tap', function () {
			tapped = true;
		});

		t.equal( tapped, undefined );
		simulant.fire( ractive.nodes.test, 'mousedown' );
		simulant.fire( ractive.nodes.test, 'click' );
		t.equal( tapped, true );
	});

	test( 'Pressing spacebar on a focused button results in a tap event', function ( t ) {
		var ractive, node, tapped;

		ractive = new Ractive({
			el: fixture,
			template: '<button id="test" on-tap="tap">tap me</button>'
		});

		node = ractive.nodes.test;

		ractive.on( 'tap', function ( event ) {
			console.log( event );
			tapped = true;
		});

		t.equal( tapped, undefined );

		simulant.fire( node, 'keydown', { which: 32 });
		t.equal( tapped, undefined );

		node.focus();
		t.equal( document.activeElement, node );
		simulant.fire( node, 'keydown', { which: 32 });
		t.equal( tapped, true );
	});

}());<|endoftext|>


<commit_before>'use strict';

describe('$FB service', function () {

  it('should be true', function () {
    expect(true).toBeTruthy();
  });

});<commit_msg>$FB test spec in progress<commit_after>'use strict';

describe('$FB', function () {

  var APP_ID = 'some fb app id';

  var loadSDKSpy, initSpy;

  beforeEach(function () {
    loadSDKSpy = jasmine.createSpy('load sdk');
    initSpy = jasmine.createSpy('init');

    // module('ezfb', function ($FBProvider) {
    //   // $FBProvider.setLoadSDKFunction(loadSDKFunc);
    //   // $FBProvider.setInitFunction(initFunc);
    //   // $FBProvider.setLocale(LOCALE);

    // });

    // inject(function (_$rootScope_, _$timeout_) {
    //   $rootScope = _$rootScope_;
    //   $timeout = _$timeout_;
    // });
  });

  it('should try to load FB JS SDK once', function () {
    module('ezfb', function ($FBProvider) {
      $FBProvider.setLoadSDKFunction(loadSDKSpy);
      $FBProvider.setInitParams({
        appId: APP_ID
      });
    });
    inject(function ($FB) {

      expect(loadSDKSpy).toHaveBeenCalled();
    });

  });

  it('should load FB JS SDK with correct locale', function () {
    var LOCALE = 'zhTW';

    module('ezfb', function ($FBProvider) {
      $FBProvider.setLoadSDKFunction(['$fbLocale', function ($fbLocale) {
        loadSDKSpy($fbLocale);
      }]);
      $FBProvider.setLocale(LOCALE);
      $FBProvider.setInitParams({
        appId: APP_ID
      });
    });
    inject(function ($FB) {

      expect(loadSDKSpy.mostRecentCall.args[0]).toEqual(LOCALE);
    });

  });

  it('should call init function with correct appId', function () {
    module('ezfb', function ($FBProvider) {
      $FBProvider.setLoadSDKFunction(['$fbAsyncInit', function ($fbAsyncInit) {
        // Can't rely on default load SDK function here
        $fbAsyncInit();
      }]);
      $FBProvider.setInitFunction(['$fbInitParams', function ($fbInitParams) {
        initSpy($fbInitParams);
      }]);
      $FBProvider.setInitParams({
        appId: APP_ID
      });
    });
    inject(function ($FB, $rootScope) {
      $rootScope.$apply();
      expect(initSpy).toHaveBeenCalled();
      expect(initSpy.mostRecentCall.args[0]).toEqual({
        appId      : APP_ID,
        status     : true,
        cookie     : true,
        xfbml      : true
      });
    });
  });

  it('should call init function even sdk is loaded asynchronously', function () {
    module('ezfb', function ($FBProvider) {
      $FBProvider.setLoadSDKFunction([
               '$fbAsyncInit', '$timeout',
      function ($fbAsyncInit,   $timeout) {
        // Delay a bit
        $timeout(function () {
          $fbAsyncInit();
        }, 999999999999999);
      }]);
      $FBProvider.setInitFunction(initSpy);
      $FBProvider.setInitParams({
        appId: APP_ID
      });
    });
    inject(function ($FB, $rootScope, $timeout) {
      $rootScope.$apply();
      $timeout.flush();
      expect(initSpy).toHaveBeenCalled();
    });
  });

});
<|endoftext|>


<commit_before>
settings.primaryColor = "#eecccc";
settings.primaryLight = "#eee2e2";
settings.autocomplete = true;
settings.lemgramSelect = true;
settings.wordpicture = true;

settings.corpora = {};
settings.corporafolders = {};
settings.corpora.lb = {
	id : "lb",
	title : "Litteraturbanken",
	description : 'Samtliga etexter och sökbara faksimiler från Litteraturbanken.se.',
	within : settings.defaultWithin,
	context : settings.defaultContext,
	attributes : {
		pos : attrs.pos,
		msd : attrs.msd,
		lemma : attrs.baseform,
		lex : attrs.lemgram,
		saldo : attrs.saldo,
		dephead : attrs.dephead,
		deprel : attrs.deprel,
		ref : attrs.ref,
		prefix : attrs.prefix,
		suffix : attrs.suffix
	},
	struct_attributes : {
		"text_title" : {label : "title"},
		"text_author" : {label : "author"},
		"text_url" : {label : "verk", type : "url"},
		"text_source" : {label : "source"},
		"text_date" : {label : "imprintyear"},
		"page_n" : {label : "page"},
		"page_url" : {label : "page", type : "url"}
	}
};

settings.corpusListing = new CorpusListing(settings.corpora);
<commit_msg><commit_after>
settings.primaryColor = "#eecccc";
settings.primaryLight = "#eee2e2";
settings.autocomplete = true;
settings.lemgramSelect = true;
settings.wordpicture = true;

settings.corpora = {};
settings.corporafolders = {};
settings.corpora.lb = {
	id : "lb",
	title : "Litteraturbanken",
	description : 'Samtliga etexter och sökbara faksimiler från Litteraturbanken.se.',
	within : settings.defaultWithin,
	context : settings.defaultContext,
	attributes : {
		pos : attrs.pos,
		msd : attrs.msd,
		lemma : attrs.baseform,
		lex : attrs.lemgram,
		saldo : attrs.saldo,
		dephead : attrs.dephead,
		deprel : attrs.deprel,
		ref : attrs.ref,
		prefix : attrs.prefix,
		suffix : attrs.suffix
	},
	struct_attributes : {
		"text_title" : {label : "title"},
		"text_author" : {label : "author"},
		"text_url" : {label : "verk", type : "url"},
		"text_source" : {label : "source"},
		"text_date" : {label : "imprintyear"},
		"page_n" : {label : "page"},
		"page_url" : {label : "pagelink", type : "url"}
	}
};

settings.corpusListing = new CorpusListing(settings.corpora);
<|endoftext|>


<commit_before>describe('The CamlTag should build a valid XML String', function() {
	var CamlTag;
	beforeEach(module('ngSharepoint'));
	beforeEach(inject(function(_CamlTag_) {
		CamlTag = _CamlTag_;
	}));
	it('builds a valid XML Tag', function() {
		expect(new CamlTag('Test').build()).toEqual('<Test/>');
	});
	it('builds a valid XML Tag with Attributes', function() {
		expect(new CamlTag('Test', {Type: "Test"}).build()).toEqual('<Test Type="Test"/>');
	});
	it('builds a valid XML Hierarchy', function() {
		var tag = new CamlTag('Test');
		tag.push('Child');
		expect(tag.build()).toEqual('<Test><Child/></Test>');
	});
});<commit_msg>Test tag with value<commit_after>describe('The CamlTag should build a valid XML String', function() {
	var CamlTag;
	beforeEach(module('ngSharepoint'));
	beforeEach(inject(function(_CamlTag_) {
		CamlTag = _CamlTag_;
	}));
	it('builds a valid XML Tag', function() {
		expect(new CamlTag('Test').build()).toEqual('<Test/>');
	});
	it('builds a valid XML Tag with Attributes', function() {
		expect(new CamlTag('Test', {Type: "Test"}).build()).toEqual('<Test Type="Test"/>');
	});
	it('builds a valid XML Hierarchy', function() {
		var tag = new CamlTag('Test');
		tag.push('Child');
		expect(tag.build()).toEqual('<Test><Child/></Test>');
	});
	it('builds a valid XML Tag with a value', function() {
		expect(new CamlTag('Test', {}, 'Value').build()).toEqual('<Test>Value</Test>');
	});
});<|endoftext|>


<commit_before>'use strict';

var JSIGSnippet = require('../lib/jsig-snippet.js');

JSIGSnippet.test('can export a string', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        foo : String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('can export an object', {
    snippet: function m() {/*
        var foo = { a: '' };

        module.exports = foo;
    */},
    header: function h() {/*
        foo : { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

JSIGSnippet.test('can export an anonymous string', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        export default String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('catches mis-export error', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.sub-type.type-class-mismatch');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, 'String');
    assert.equal(err.line, 3);

    assert.end();
});

JSIGSnippet.test('can export an anonymous string literal', {
    snippet: function m() {/*
        module.exports = '';
    */},
    header: function h() {/*
        export default String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('catches mis-export error for literal', {
    snippet: function m() {/*
        module.exports = '';
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.sub-type.type-class-mismatch');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, 'String');
    assert.equal(err.line, 1);

    assert.end();
});

JSIGSnippet.test('Export must exist', {
    snippet: function m() {/*
        var foo = 4;
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.verify.missing-exports');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, '<MissingType>');
    assert.equal(err.fileName, 'snippet.js');

    assert.end();
});

JSIGSnippet.test('can export an anonymous object', {
    snippet: function m() {/*
        module.exports = { a: '' };
    */},
    header: function h() {/*
        export default { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

JSIGSnippet.test('can use exports.foo', {
    snippet: function m() {/*
        exports.a = '';
    */},
    header: function h() {/*
        export default { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

// TODO: assiging exports.foo where exports : Number
// TODO: not assiging exports.foo at all
// TODO: assigning a subset of exports fields
<commit_msg>another test for exporting<commit_after>'use strict';

var JSIGSnippet = require('../lib/jsig-snippet.js');

JSIGSnippet.test('can export a string', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        foo : String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('can export an object', {
    snippet: function m() {/*
        var foo = { a: '' };

        module.exports = foo;
    */},
    header: function h() {/*
        foo : { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

JSIGSnippet.test('can export an anonymous string', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        export default String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('catches mis-export error', {
    snippet: function m() {/*
        var foo = '';

        module.exports = foo;
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.sub-type.type-class-mismatch');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, 'String');
    assert.equal(err.line, 3);

    assert.end();
});

JSIGSnippet.test('can export an anonymous string literal', {
    snippet: function m() {/*
        module.exports = '';
    */},
    header: function h() {/*
        export default String
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'String');

    assert.end();
});

JSIGSnippet.test('catches mis-export error for literal', {
    snippet: function m() {/*
        module.exports = '';
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.sub-type.type-class-mismatch');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, 'String');
    assert.equal(err.line, 1);

    assert.end();
});

JSIGSnippet.test('Export must exist', {
    snippet: function m() {/*
        var foo = 4;
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 1, 'expected one error');

    var err = meta.errors[0];
    assert.equal(err.type, 'jsig.verify.missing-exports');
    assert.equal(err.expected, 'Number');
    assert.equal(err.actual, '<MissingType>');
    assert.equal(err.fileName, 'snippet.js');

    assert.end();
});

JSIGSnippet.test('can export an anonymous object', {
    snippet: function m() {/*
        module.exports = { a: '' };
    */},
    header: function h() {/*
        export default { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

JSIGSnippet.test('can use exports.foo', {
    snippet: function m() {/*
        exports.a = '';
    */},
    header: function h() {/*
        export default { a: String }
    */}
}, function t(snippet, assert) {
    var meta = snippet.compileAndCheck(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, '{ a: String }');

    assert.end();
});

JSIGSnippet.test('assigning exports field to non-object', {
    snippet: function m() {/*
        exports.a = '';
    */},
    header: function h() {/*
        export default Number
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile(assert);
    var exported = meta.serializeType(meta.moduleExportsType);

    assert.equal(exported, 'Number');
    assert.equal(meta.errors.length, 2, 'found two errors');

    var err1 = meta.errors[0];
    assert.equal(err1.type, 'jsig.verify.accessing-field-on-non-object');
    assert.equal(err1.fieldName, 'a');
    assert.equal(err1.nonObjectType, 'Number');
    assert.equal(err1.line, 1);

    var err2 = meta.errors[1];
    assert.equal(err2.type, 'jsig.verify.missing-exports');
    assert.equal(err2.expected, 'Number');
    assert.equal(err2.actual, '<MissingType>');

    assert.end();
});

// TODO: not assiging exports.foo at all
// TODO: adding the wrong field to exports
// TODO: assigning a subset of exports fields
<|endoftext|>


<commit_before>exports.singleSprite = {
  sprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 10, height: 20
  }],
  spritesheet: {
    width: 10, height: 20, image: 'nested/dir/spritesheet.png'
  }
};

exports.multipleSprites = {
  sprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 10, height: 20
  }, {
    name: 'sprite_snake_case', x: 10, y: 20, width: 20, height: 30
  }, {
    name: 'spriteCamelCase', x: 30, y: 50, width: 50, height: 50
  }],
  spritesheet: {
    width: 80, height: 100, image: 'nested/dir/spritesheet.png'
  }
};
<commit_msg>Added new config for retina<commit_after>exports.singleSprite = {
  sprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 10, height: 20
  }],
  spritesheet: {
    width: 10, height: 20, image: 'nested/dir/spritesheet.png'
  }
};

exports.multipleSprites = {
  sprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 10, height: 20
  }, {
    name: 'sprite_snake_case', x: 10, y: 20, width: 20, height: 30
  }, {
    name: 'spriteCamelCase', x: 30, y: 50, width: 50, height: 50
  }],
  spritesheet: {
    width: 80, height: 100, image: 'nested/dir/spritesheet.png'
  }
};

exports.retinaMultipleSprites = {
  sprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 10, height: 20
  }, {
    name: 'sprite_snake_case', x: 10, y: 20, width: 20, height: 30
  }, {
    name: 'spriteCamelCase', x: 30, y: 50, width: 50, height: 50
  }],
  spritesheet: {
    width: 80, height: 100, image: 'nested/dir/spritesheet.png'
  },
  retinaSprites: [{
    name: 'sprite-dash-case', x: 0, y: 0, width: 20, height: 40
  }, {
    name: 'sprite_snake_case', x: 20, y: 40, width: 40, height: 60
  }, {
    name: 'spriteCamelCase', x: 60, y: 100, width: 100, height: 100
  }],
  retinaSpritesheet: {
    width: 160, height: 200, image: 'nested/dir/spritesheet.png'
  }
};
<|endoftext|>