<commit_before>const HTTP = require("./http");
const create = Object.create;
const define = Object.defineProperties;
const GitHub$internal = new WeakMap();

/**
 * Create GitHub API object.
 * @param {string} repo
 * @param {Credentials} creds
 * @returns {GitHub}
 */
function github(repo, creds) {
    var github = create(GitHub);

    GitHub$internal.set(github, {
        repo: repo,
        creds: creds
    });
}

/**
 * Return HTTP headers to send with GitHub API requests.
 * @param {GitHub} github
 * @returns {object}
 */
function headers(github) {
    var creds = GitHub$internal.get(github).creds,
        auth = HTTP.auth(creds.ident, creds.secret),
        ua = HTTP.ua(creds.ident);

    return assign(ua, auth);
}

/**
 * Read response body.
 * @param {object} res
 * @returns {object}
 */
function readbody(res) {
    if (res.status === 200) return res.body;
    if (res.status === 404) return null;
    throw new Error(`unexpected ${res.status} status`);
}

const GitHub = {
    /**
     * Return full URI for GitHub resource URI.
     * @param {string} uri
     * @returns {string}
     */
    url: function(uri) {
        return /^https?:/.test(uri) ? uri : `${this.endpoint}/${uri}`;
    },

    /**
     * Lookup branch info.
     * @param {string} branch
     * @returns {Promise}
     */
    branch: function(branch) {
        var url = this.url(`branches/${branch}`);
        return HTTP.get(url, headers(this)).then(readbody);
    },

    /**
     * Compare references.
     * @param {string} refa
     * @param {string} refb
     */
    compare: function(refa, refb) {
        var url = this.url(`compare/${refa}...${refb}`);
        return HTTP.get(url, headers(this)).then(readbody);
    }
};

define(GitHub, {
    /**
     * GitHub owner/repo.
     * @name GitHub#repo
     * @type {string}
     * @readonly
     */
    repo: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).repo;}
    },

    /**
     * GitHub credentials.
     * @name GitHub#creds
     * @type {Credentials}
     * @readonly
     */
    creds: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).creds;}
    },

    /**
     * Base branch at which to start builds.
     * @name GitHub#base
     * @type {string}
     * @readonly
     */
    base: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).base;}
    },

    /**
     * Build branch which will be set to latest build.
     * @name GitHub#build
     * @type {string}
     * @readonly
     */
    build: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).build;}
    },

    /**
     * GitHub API endpoint for repo.
     * @name GitHub#endpoint
     * @type {string}
     * @readonly
     */
    endpoint: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).endpoint;}
    }
});

module.exports = github;
module.exports.GitHub = GitHub;
<commit_msg>fix missing return value from github<commit_after>const HTTP = require("./http");
const create = Object.create;
const define = Object.defineProperties;
const GitHub$internal = new WeakMap();

/**
 * Create GitHub API object.
 * @param {string} repo
 * @param {Credentials} creds
 * @returns {GitHub}
 */
function github(repo, creds) {
    var github = create(GitHub);

    GitHub$internal.set(github, {
        repo: repo,
        creds: creds
    });

    return github;
}

/**
 * Return HTTP headers to send with GitHub API requests.
 * @param {GitHub} github
 * @returns {object}
 */
function headers(github) {
    var creds = GitHub$internal.get(github).creds,
        auth = HTTP.auth(creds.ident, creds.secret),
        ua = HTTP.ua(creds.ident);

    return assign(ua, auth);
}

/**
 * Read response body.
 * @param {object} res
 * @returns {object}
 */
function readbody(res) {
    if (res.status === 200) return res.body;
    if (res.status === 404) return null;
    throw new Error(`unexpected ${res.status} status`);
}

const GitHub = {
    /**
     * Return full URI for GitHub resource URI.
     * @param {string} uri
     * @returns {string}
     */
    url: function(uri) {
        return /^https?:/.test(uri) ? uri : `${this.endpoint}/${uri}`;
    },

    /**
     * Lookup branch info.
     * @param {string} branch
     * @returns {Promise}
     */
    branch: function(branch) {
        var url = this.url(`branches/${branch}`);
        return HTTP.get(url, headers(this)).then(readbody);
    },

    /**
     * Compare references.
     * @param {string} refa
     * @param {string} refb
     */
    compare: function(refa, refb) {
        var url = this.url(`compare/${refa}...${refb}`);
        return HTTP.get(url, headers(this)).then(readbody);
    }
};

define(GitHub, {
    /**
     * GitHub owner/repo.
     * @name GitHub#repo
     * @type {string}
     * @readonly
     */
    repo: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).repo;}
    },

    /**
     * GitHub credentials.
     * @name GitHub#creds
     * @type {Credentials}
     * @readonly
     */
    creds: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).creds;}
    },

    /**
     * Base branch at which to start builds.
     * @name GitHub#base
     * @type {string}
     * @readonly
     */
    base: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).base;}
    },

    /**
     * Build branch which will be set to latest build.
     * @name GitHub#build
     * @type {string}
     * @readonly
     */
    build: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).build;}
    },

    /**
     * GitHub API endpoint for repo.
     * @name GitHub#endpoint
     * @type {string}
     * @readonly
     */
    endpoint: {
        configurable: true,
        enumerable: true,
        get: function() {return GitHub$internal.get(this).endpoint;}
    }
});

module.exports = github;
module.exports.GitHub = GitHub;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var _ = require('underscore');
var WebsocketServer = require('./lib/websocket-server');
var SceneDOM = require('scene-dom');
var IndexScene = require('./lib/index-scene');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var express = require('express');
var http = require('http');
var cors = require('cors');
var Env = require('./lib/env');

function Server (folder, port) {
  this.folder = path.join(process.cwd(), folder);
  this.port = parseInt(port, 10);
}

/**
 * Start the express server and the websocket server
 */
Server.prototype.start = function () {
  var self = this;

  console.log('[server] Serving scenes in \'' + this.folder + '\' on port ' + this.port + '...');

  this.webServer = express();
  this.webServer.use(cors());
  this.webServer.use(express.static(this.folder));

  this.webServer.get('/', function (req, res) {
    res.redirect('http://client.scenevr.com/?connect=' + req.get('host'));
  });

  var httpServer = http.createServer(this.webServer);
  httpServer.listen(this.port);

  this.websocketServer = new WebsocketServer(httpServer);
  this.websocketServer.listen();

  if (Env.supportsAutoReload()) {
    this.restart = _.throttle(this.restartServer.bind(this), 1000, {trailing: false});
  }

  this.loadAllScenes();

  if (Env.isDevelopment()) {
    require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
      var url = err ? 'localhost:' + self.port : addr + ':' + self.port;
      console.log('\n\thttp://' + url + '/\n');
    });
  }
};

/**
 * Load all the scenes to host from disk and into the websocket server
 */
Server.prototype.loadAllScenes = function () {
  var self = this;

  glob(this.folder + '/*.xml', {}, function (err, files) {
    if (err || (files.length === 0)) {
      console.log('[server] Error. No scene files found in ' + self.folder);
      if (Env.isDevelopment()) {
        process.exit(-1);
      }
    }

    var indexXml = new IndexScene(files).toXml();
    var document = SceneDOM.createDocument().loadXML(indexXml);

    self.websocketServer.addDocument(document, '/index.xml');

    files.forEach(function (filename) {
      try {
        fs.readFile(filename, 'utf8', function (err, xml) {
          if (err) throw new Error(err);

          var document = SceneDOM.createDocument().loadXML(xml);
          self.websocketServer.addDocument(document, '/' + path.basename(filename));
          console.log('[server]  * Loaded \'' + filename + '\'');

          if (Env.supportsAutoReload()) {
            fs.watch(filename, self.restart);
          }
        });
      } catch(e) {
        console.log('[server] Could not load filename: ' + e);
      }
    });
  });
};

/**
 * Restart all documents in the server
 */
Server.prototype.restartServer = function () {
  var self = this;

  console.log('[server] Restarting server on file change.');

  this.websocketServer.getDocumentURLs().forEach(function (url) {
    self.websocketServer.removeDocument(url);
  });

  setTimeout(function () {
    self.loadAllScenes();
  }, 250);
};

var scenePath = process.argv[2];

if (!scenePath) {
  console.log('Usage: scenevr [scenedirectory]');
  process.exit(-1);
}

var server = new Server(scenePath, Env.getPort());
server.start();
<commit_msg>Completely resolve filename, set originalFilename on document.<commit_after>#!/usr/bin/env node

var _ = require('underscore');
var WebsocketServer = require('./lib/websocket-server');
var SceneDOM = require('scene-dom');
var IndexScene = require('./lib/index-scene');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var express = require('express');
var http = require('http');
var cors = require('cors');
var Env = require('./lib/env');

function Server (folder, port) {
  this.folder = path.join(process.cwd(), folder);
  this.port = parseInt(port, 10);
}

/**
 * Start the express server and the websocket server
 */
Server.prototype.start = function () {
  var self = this;

  console.log('[server] Serving scenes in \'' + this.folder + '\' on port ' + this.port + '...');

  this.webServer = express();
  this.webServer.use(cors());
  this.webServer.use(express.static(this.folder));

  this.webServer.get('/', function (req, res) {
    res.redirect('http://client.scenevr.com/?connect=' + req.get('host'));
  });

  var httpServer = http.createServer(this.webServer);
  httpServer.listen(this.port);

  this.websocketServer = new WebsocketServer(httpServer);
  this.websocketServer.listen();

  if (Env.supportsAutoReload()) {
    this.restart = _.throttle(this.restartServer.bind(this), 1000, {trailing: false});
  }

  this.loadAllScenes();

  if (Env.isDevelopment()) {
    require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
      var url = err ? 'localhost:' + self.port : addr + ':' + self.port;
      console.log('\n\thttp://' + url + '/\n');
    });
  }
};

/**
 * Load all the scenes to host from disk and into the websocket server
 */
Server.prototype.loadAllScenes = function () {
  var self = this;

  glob(this.folder + '/*.xml', {}, function (err, files) {
    if (err || (files.length === 0)) {
      console.log('[server] Error. No scene files found in ' + self.folder);
      if (Env.isDevelopment()) {
        process.exit(-1);
      }
    }

    var indexXml = new IndexScene(files).toXml();
    var document = SceneDOM.createDocument().loadXML(indexXml);

    self.websocketServer.addDocument(document, '/index.xml');

    files.forEach(function (match) {
      var filename = path.resolve(__dirname, match);

      try {
        fs.readFile(filename, 'utf8', function (err, xml) {
          if (err) throw new Error(err);

          var document = SceneDOM.createDocument().loadXML(xml);
          document.originalFilename = filename;
          self.websocketServer.addDocument(document, '/' + path.basename(filename));
          console.log('[server]  * Loaded \'' + filename + '\'');

          if (Env.supportsAutoReload()) {
            fs.watch(filename, self.restart);
          }
        });
      } catch(e) {
        console.log('[server] Could not load filename: ' + e);
      }
    });
  });
};

/**
 * Restart all documents in the server
 */
Server.prototype.restartServer = function () {
  var self = this;

  console.log('[server] Restarting server on file change.');

  this.websocketServer.getDocumentURLs().forEach(function (url) {
    self.websocketServer.removeDocument(url);
  });

  setTimeout(function () {
    self.loadAllScenes();
  }, 250);
};

var scenePath = process.argv[2];

if (!scenePath) {
  console.log('Usage: scenevr [scenedirectory]');
  process.exit(-1);
}

var server = new Server(scenePath, Env.getPort());
server.start();
<|endoftext|>


<commit_before>(function() {
	var multiplex = Reveal.getConfig().multiplex;
	var socketId = multiplex.id;
	var socket = io.connect(multiplex.url);

	socket.on(multiplex.id, function(data) {
		// ignore data from sockets that aren't ours
		if (data.socketId !== socketId) { return; }
		if( window.location.host === 'localhost:1947' ) return;

        if (data.type && data.type === 'slidechanged') {
    		Reveal.slide(data.indexh, data.indexv, data.indexf, 'remote');
        }
        else if (data.type && data.type === 'codechanged') {
            var event = document.createEvent( "HTMLEvents", 1, 2 );
    	    event.initEvent( 'keypress', true, true );
            event.target = document.getElementById(data.id);
            event.target.innerHTML = data.html;
            document.querySelector('.reveal').dispatchEvent(event);
        }
	});
}());
<commit_msg>Do not modify event target -- dispatch event directly from target instead.<commit_after>(function() {
	var multiplex = Reveal.getConfig().multiplex;
	var socketId = multiplex.id;
	var socket = io.connect(multiplex.url);

	socket.on(multiplex.id, function(data) {
		// ignore data from sockets that aren't ours
		if (data.socketId !== socketId) { return; }
		if( window.location.host === 'localhost:1947' ) return;

        if (data.type && data.type === 'slidechanged') {
    		Reveal.slide(data.indexh, data.indexv, data.indexf, 'remote');
        }
        else if (data.type && data.type === 'codechanged') {
            var event = document.createEvent( "HTMLEvents", 1, 2 ),
                target = document.getElementById(data.id);

    	    event.initEvent( 'keypress', true, true );

            target.innerHTML = data.html;
            target.dispatchEvent(event);
        }
	});
}());
<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2010 by anekos <anekos@snca.net>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.

/** @scope modules */

const Abbreviation = Class("Abbreviation", {
    init: function (modes, lhs, rhs) {
        this.modes = modes;
        this.lhs = lhs;
        this.rhs = rhs;
    },

    equals: function (other) {
        return this.lhs == other.lhs && this.rhs == other.rhs;
    },

    modesEqual: function (modes) {
        return (modes.lengh === this.modes.lengh) &&
               (this.modes.every(function (m1) modes.some(function (m2) m1 === m2)));
    },

    get text() (this.rhs instanceof Function ? this.rhs() : this.rhs).toString(),

    inMode: function (mode) {
        return this.modes.some(function (_mode) _mode == mode);
    },

    inModes: function (modes) {
        let self = this;
        return modes.some(function (mode) self.inMode(mode));
    },

    removeMode: function (mode) {
        this.modes = this.modes.filter(function (m) m != mode);
    },

    get modeChar() Abbreviation.modeChar(this.modes)
}, {
    modeChar: function (_modes) {
        let result = "";
        for ([, mode] in Iterator(_modes))
            result += modes.getMode(mode).char;
        if (/^(ic|ci)$/(result))
            result = "!";
        return result;
    }
});

const Abbreviations = Module("abbreviations", {
    requires: ["config", "modes"],

    init: function () {
        this.abbrevs = {};

        // (summarized from Vim's ":help abbreviations")
        //
        // There are three types of abbreviations.
        //
        // full-id: Consists entirely of keyword characters.
        //          ("foo", "g3", "-1")
        //
        // end-id: Ends in a keyword character, but all other
        //         are not keyword characters.
        //         ("#i", "..f", "$/7")
        //
        // non-id: Ends in a non-keyword character, but the
        //         others can be of any type other than space
        //         and tab.
        //         ("def#", "4/7$")
        //
        // Example strings that cannot be abbreviations:
        //         "a.b", "#def", "a b", "_$r"
        //
        // For now, a keyword character is anything except for \s, ", or '
        // (i.e., whitespace and quotes). In Vim, a keyword character is
        // specified by the 'iskeyword' setting and is a much less inclusive
        // list.
        //
        // TODO: Make keyword definition closer to Vim's default keyword
        //       definition (which differs across platforms).

        let nonkw = "\\s\"'";
        let keyword = "[^" + nonkw + "]";
        let nonkeyword = "[" + nonkw + "]";

        let fullId = keyword + "+";
        let endId = nonkeyword + "+" + keyword;
        let nonId = "\\S*" + nonkeyword;

        // Used in add and expand
        this._match = fullId + "|" + endId + "|" + nonId;
    },

    /**
     * Adds a new abbreviation.
     *
     * @param {Abbreviation}
     */
    add: function (abbr) {
        if (!(abbr instanceof Abbreviation))
            abbr = Abbreviation.apply(null, arguments);

        for (let [, mode] in Iterator(abbr.modes)) {
            if (!this.abbrevs[mode])
                this.abbrevs[mode] = {};
            this.abbrevs[mode][abbr.lhs] = abbr;
        }
    },

    /**
     * Returns matched abbreviation.
     *
     * @param {mode}
     * @param {string}
     */
    get: function (mode, lhs) {
        let abbrevs = this.abbrevs[mode];
        return abbrevs && abbrevs[lhs];
    },

    /**
     * The list of the abbreviations merged from each modes.
     */
    get merged() {
        let result = [];
        let lhses = [];
        let modes = [mode for (mode in this.abbrevs)];

        for (let [, mabbrevs] in Iterator(this.abbrevs))
            lhses = lhses.concat([key for (key in mabbrevs)]);
        lhses.sort();
        lhses = util.Array.uniq(lhses);

        for (let [, lhs] in Iterator(lhses)) {
            let exists = {};
            for (let [, mabbrevs] in Iterator(this.abbrevs)) {
                let abbr = mabbrevs[lhs];
                if (abbr && !exists[abbr.rhs]) {
                    exists[abbr.rhs] = 1;
                    result.push(abbr);
                }
            }
        }

        return result;
    },

    /**
     * Lists all abbreviations matching modes and lhs.
     *
     * @param {Array} list of mode.
     * @param {string} lhs The LHS of the abbreviation.
     */
    list: function (modes, lhs) {
        let list = this.merged.filter(function (abbr) (abbr.inModes(modes) && abbr.lhs.indexOf(lhs) == 0));

        if (!list.length)
            liberator.echomsg("No abbreviations found");
        else if (list.length == 1) {
            let head = list[0];
            liberator.echo(head.modeChar + "  " + head.lhs + "   " + head.rhs, commandline.FORCE_SINGLELINE); // 2 spaces, 3 spaces
        }
        else {
            list = list.map(function (abbr) [abbr.modeChar, abbr.lhs, abbr.rhs]);
            list = template.tabular(["", "LHS", "RHS"], [], list);
            commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
        }
    },

    /**
     * Remove the specified abbreviations.
     *
     * @param {Array} list of mode.
     * @param {string} lhs of abbreviation.
     * @returns {boolean} did the deleted abbreviation exist?
     */
    remove: function (modes, lhs) {
        let result = false;
        for (let [, mode] in Iterator(modes)) {
            if ((mode in this.abbrevs) && (lhs in this.abbrevs[mode])) {
                result = true;
                this.abbrevs[mode][lhs].removeMode(mode);
                delete this.abbrevs[mode][lhs];
            }
        }
        return result;
    },

    /**
     * Removes all abbreviations specified modes.
     *
     * @param {Array} list of mode.
     */
    removeAll: function (modes) {
        for (let [, mode] in modes) {
            if (!(mode in this.abbrevs))
                return;
            for (let [, abbr] in this.abbrevs[mode])
                abbr.removeMode(mode);
            delete this.abbrevs[mode];
        }
    }
}, {
}, {
    completion: function () {
        // TODO: shouldn't all of these have a standard signature (context, args, ...)? --djk
        completion.abbreviation = function abbreviation(context, args, modes) {
            if (args.completeArg == 0) {
                let abbrevs = abbreviations.merged.filter(function (abbr) abbr.inModes(modes));
                context.completions = [[abbr.lhs, abbr.rhs] for ([, abbr] in Iterator(abbrevs))];
            }
        };
    },

    commands: function () {
        function addAbbreviationCommands(modes, ch, modeDescription) {
            modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";

            commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"],
                "Abbreviate a key sequence" + modeDescription,
                function (args) {
                    let matches = args.literalArg.match(RegExp("^\\s*($|" + abbreviations._match + ")(?:\\s*$|\\s+(.*))"));
                    liberator.assert(matches, "E474: Invalid argument");

                    let [, lhs, rhs] = matches;
                    if (rhs) {
                        if (args["-javascript"]) {
                            let expr = rhs;
                            rhs = (function () eval(expr));
                            rhs.toString = function () expr;
                        }
                        abbreviations.add(modes, lhs, rhs);
                    }
                    else {
                        abbreviations.list(modes, lhs || "");
                    }
                }, {
                    options: [[["-javascript", "-j"], commands.OPTION_NOARG, null]],
                    completer: function (context, args) completion.abbreviation(context, args, modes),
                    literal: 0,
                    serial: function () [ {
                            command: this.name,
                            arguments: [abbr.lhs],
                            literalArg: abbr.rhs,
                            options: abbr.rhs instanceof Function ? {"-javascript": null} : {}
                        }
                        for ([, abbr] in Iterator(abbreviations.merged))
                        if (abbr.modesEqual(modes))
                    ]
                });

            commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"],
                "Remove an abbreviation" + modeDescription,
                function (args) {
                    let lhs = args.literalArg;
                    if (!lhs)
                        return liberator.echoerr("E474: Invalid argument");
                    if (!abbreviations.remove(modes, lhs))
                        return liberator.echoerr("E24: No such abbreviation");
                }, {
                    argCount: "1",
                    completer: function (context, args) completion.abbreviation(context, args, modes),
                    literal: 0
                });

            commands.add([ch + "abc[lear]"],
                "Remove all abbreviations" + modeDescription,
                function () { abbreviations.removeAll(modes); },
                { argCount: "0" });
        }

        addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", "");
        addAbbreviationCommands([modes.INSERT], "i", "insert");
        addAbbreviationCommands([modes.COMMAND_LINE], "c", "command line");
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Add "abbr -javascript" completer<commit_after>// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2010 by anekos <anekos@snca.net>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.

/** @scope modules */

const Abbreviation = Class("Abbreviation", {
    init: function (modes, lhs, rhs) {
        this.modes = modes;
        this.lhs = lhs;
        this.rhs = rhs;
    },

    equals: function (other) {
        return this.lhs == other.lhs && this.rhs == other.rhs;
    },

    modesEqual: function (modes) {
        return (modes.lengh === this.modes.lengh) &&
               (this.modes.every(function (m1) modes.some(function (m2) m1 === m2)));
    },

    get text() (this.rhs instanceof Function ? this.rhs() : this.rhs).toString(),

    inMode: function (mode) {
        return this.modes.some(function (_mode) _mode == mode);
    },

    inModes: function (modes) {
        let self = this;
        return modes.some(function (mode) self.inMode(mode));
    },

    removeMode: function (mode) {
        this.modes = this.modes.filter(function (m) m != mode);
    },

    get modeChar() Abbreviation.modeChar(this.modes)
}, {
    modeChar: function (_modes) {
        let result = "";
        for ([, mode] in Iterator(_modes))
            result += modes.getMode(mode).char;
        if (/^(ic|ci)$/(result))
            result = "!";
        return result;
    }
});

const Abbreviations = Module("abbreviations", {
    requires: ["config", "modes"],

    init: function () {
        this.abbrevs = {};

        // (summarized from Vim's ":help abbreviations")
        //
        // There are three types of abbreviations.
        //
        // full-id: Consists entirely of keyword characters.
        //          ("foo", "g3", "-1")
        //
        // end-id: Ends in a keyword character, but all other
        //         are not keyword characters.
        //         ("#i", "..f", "$/7")
        //
        // non-id: Ends in a non-keyword character, but the
        //         others can be of any type other than space
        //         and tab.
        //         ("def#", "4/7$")
        //
        // Example strings that cannot be abbreviations:
        //         "a.b", "#def", "a b", "_$r"
        //
        // For now, a keyword character is anything except for \s, ", or '
        // (i.e., whitespace and quotes). In Vim, a keyword character is
        // specified by the 'iskeyword' setting and is a much less inclusive
        // list.
        //
        // TODO: Make keyword definition closer to Vim's default keyword
        //       definition (which differs across platforms).

        let nonkw = "\\s\"'";
        let keyword = "[^" + nonkw + "]";
        let nonkeyword = "[" + nonkw + "]";

        let fullId = keyword + "+";
        let endId = nonkeyword + "+" + keyword;
        let nonId = "\\S*" + nonkeyword;

        // Used in add and expand
        this._match = fullId + "|" + endId + "|" + nonId;
    },

    /**
     * Adds a new abbreviation.
     *
     * @param {Abbreviation}
     */
    add: function (abbr) {
        if (!(abbr instanceof Abbreviation))
            abbr = Abbreviation.apply(null, arguments);

        for (let [, mode] in Iterator(abbr.modes)) {
            if (!this.abbrevs[mode])
                this.abbrevs[mode] = {};
            this.abbrevs[mode][abbr.lhs] = abbr;
        }
    },

    /**
     * Returns matched abbreviation.
     *
     * @param {mode}
     * @param {string}
     */
    get: function (mode, lhs) {
        let abbrevs = this.abbrevs[mode];
        return abbrevs && abbrevs[lhs];
    },

    /**
     * The list of the abbreviations merged from each modes.
     */
    get merged() {
        let result = [];
        let lhses = [];
        let modes = [mode for (mode in this.abbrevs)];

        for (let [, mabbrevs] in Iterator(this.abbrevs))
            lhses = lhses.concat([key for (key in mabbrevs)]);
        lhses.sort();
        lhses = util.Array.uniq(lhses);

        for (let [, lhs] in Iterator(lhses)) {
            let exists = {};
            for (let [, mabbrevs] in Iterator(this.abbrevs)) {
                let abbr = mabbrevs[lhs];
                if (abbr && !exists[abbr.rhs]) {
                    exists[abbr.rhs] = 1;
                    result.push(abbr);
                }
            }
        }

        return result;
    },

    /**
     * Lists all abbreviations matching modes and lhs.
     *
     * @param {Array} list of mode.
     * @param {string} lhs The LHS of the abbreviation.
     */
    list: function (modes, lhs) {
        let list = this.merged.filter(function (abbr) (abbr.inModes(modes) && abbr.lhs.indexOf(lhs) == 0));

        if (!list.length)
            liberator.echomsg("No abbreviations found");
        else if (list.length == 1) {
            let head = list[0];
            liberator.echo(head.modeChar + "  " + head.lhs + "   " + head.rhs, commandline.FORCE_SINGLELINE); // 2 spaces, 3 spaces
        }
        else {
            list = list.map(function (abbr) [abbr.modeChar, abbr.lhs, abbr.rhs]);
            list = template.tabular(["", "LHS", "RHS"], [], list);
            commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
        }
    },

    /**
     * Remove the specified abbreviations.
     *
     * @param {Array} list of mode.
     * @param {string} lhs of abbreviation.
     * @returns {boolean} did the deleted abbreviation exist?
     */
    remove: function (modes, lhs) {
        let result = false;
        for (let [, mode] in Iterator(modes)) {
            if ((mode in this.abbrevs) && (lhs in this.abbrevs[mode])) {
                result = true;
                this.abbrevs[mode][lhs].removeMode(mode);
                delete this.abbrevs[mode][lhs];
            }
        }
        return result;
    },

    /**
     * Removes all abbreviations specified modes.
     *
     * @param {Array} list of mode.
     */
    removeAll: function (modes) {
        for (let [, mode] in modes) {
            if (!(mode in this.abbrevs))
                return;
            for (let [, abbr] in this.abbrevs[mode])
                abbr.removeMode(mode);
            delete this.abbrevs[mode];
        }
    }
}, {
}, {
    completion: function () {
        // TODO: shouldn't all of these have a standard signature (context, args, ...)? --djk
        completion.abbreviation = function abbreviation(context, args, modes) {
            if (args.completeArg == 0) {
                let abbrevs = abbreviations.merged.filter(function (abbr) abbr.inModes(modes));
                context.completions = [[abbr.lhs, abbr.rhs] for ([, abbr] in Iterator(abbrevs))];
            }
        };
    },

    commands: function () {
        function addAbbreviationCommands(modes, ch, modeDescription) {
            function splitArg (arg) {
                return arg.match(RegExp("^\\s*($|" + abbreviations._match + ")(?:\\s*$|\\s+(.*))"));
            }

            modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";

            commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"],
                "Abbreviate a key sequence" + modeDescription,
                function (args) {
                    let matches = splitArg(args.literalArg);

                    liberator.assert(matches, "E474: Invalid argument");

                    let [, lhs, rhs] = matches;
                    if (rhs) {
                        if (args["-javascript"]) {
                            let expr = rhs;
                            rhs = (function () eval(expr));
                            rhs.toString = function () expr;
                        }
                        abbreviations.add(modes, lhs, rhs);
                    }
                    else {
                        abbreviations.list(modes, lhs || "");
                    }
                }, {
                    options: [[["-javascript", "-j"], commands.OPTION_NOARG, null]],
                    completer: function (context, args) {
                        let [, lhs, rhs] = splitArg(args.literalArg);
                        if (rhs && args["-javascript"])
                            return completion.javascript(context);
                        completion.abbreviation(context, args, modes)
                    },
                    literal: 0,
                    serial: function () [ {
                            command: this.name,
                            arguments: [abbr.lhs],
                            literalArg: abbr.rhs,
                            options: abbr.rhs instanceof Function ? {"-javascript": null} : {}
                        }
                        for ([, abbr] in Iterator(abbreviations.merged))
                        if (abbr.modesEqual(modes))
                    ]
                });

            commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"],
                "Remove an abbreviation" + modeDescription,
                function (args) {
                    let lhs = args.literalArg;
                    if (!lhs)
                        return liberator.echoerr("E474: Invalid argument");
                    if (!abbreviations.remove(modes, lhs))
                        return liberator.echoerr("E24: No such abbreviation");
                }, {
                    argCount: "1",
                    completer: function (context, args) completion.abbreviation(context, args, modes),
                    literal: 0
                });

            commands.add([ch + "abc[lear]"],
                "Remove all abbreviations" + modeDescription,
                function () { abbreviations.removeAll(modes); },
                { argCount: "0" });
        }

        addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", "");
        addAbbreviationCommands([modes.INSERT], "i", "insert");
        addAbbreviationCommands([modes.COMMAND_LINE], "c", "command line");
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>var express = require('express');
var Jimp = require('jimp');
var concat = require('concat-stream');
var app = express();
var mode = process.env.IMAGE_MODE;

app.get('/', function(req, res) {
    res.send('Hello world!');
});

app.post('/', function(req, res, next) {
    var chunks = [];

    req.on('data', function (data) {
        chunks.push(data);
    });

    req.on('end', function () {
        var buffer = Buffer.concat(chunks);
        Jimp.read(buffer).then(function (image) {
            console.log('Manipulating an image!');

            switch(mode) {
                case "1":
                    image.sepia().getBuffer(Jimp.MIME_PNG, function(err, editedBuffer) {
                        res.end(editedBuffer);
                    });
                    break;
                default:
                    image.greyscale().getBuffer(Jimp.MIME_PNG, function(err, editedBuffer) {
                        res.end(editedBuffer);
                    });
            }
        }).catch(function (err) {
            console.error('Error: ' + err);
        });
    });
});

var server = app.listen(9001, function() {
    console.log('Server running on mode ' + mode + ' listening on port 9001...');
});
<commit_msg>Refactoring to get buffer after effects switch<commit_after>var express = require('express');
var Jimp = require('jimp');
var concat = require('concat-stream');
var app = express();
var mode = process.env.IMAGE_MODE || "3";

app.get('/', function(req, res) {
    res.send('Hello world!');
});

app.post('/', function(req, res, next) {
    var chunks = [];

    req.on('data', function (data) {
        chunks.push(data);
    });

    req.on('end', function () {
        var buffer = Buffer.concat(chunks);
        Jimp.read(buffer).then(function (image) {
            console.log('Manipulating an image!');

            switch(mode) {
                case "1":
                    image.sepia();
                    break;
                case "2":
                    image.autocrop();
                    break;
                case "3":
                    image.invert();
                    break;
                default:
                    image.greyscale();
            }

            image.getBuffer(Jimp.MIME_PNG, function(err, editedBuffer) {
                res.end(editedBuffer);
            });
        }).catch(function (err) {
            console.error('Error: ' + err);
        });
    });
});

var server = app.listen(9001, function() {
    console.log('Server running on mode ' + mode + ' listening on port 9001...');
});
<|endoftext|>


<commit_before>module.exports = (RateLimiter, google, googleAuth, Promise, redisClient, json2csv, fs) => {
    let limiter = new RateLimiter(1, 100);

    let auth = new googleAuth();
    let oauth2Client = new auth.OAuth2();

    let SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file'];
    let key = require('../googleAuth.json');

    let drive = google.drive('v3');
    let client = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        SCOPES
    );

    let setFolders = (year, week) => {

        return authorize()
            .then(setCredentials)
            .then(findRootFolder)
            .then(findPlayByPlayFolder)
            .then((result) => {
                return new Promise((resolve) => {
                    resolve({
                        year: year,
                        result: result
                    });
                });
            })
            .then(findYearFolder)
            .then(findYearSubFolders)
            .then((result) => {
                return new Promise((resolve) => {
                    resolve({
                        week: week,
                        result: result
                    });
                });
            })
            .then(findJSONWeekFolder)
            .then(findJSONWeekSubFolders)
            .then(storeFolderIds)
            .then(() => {
                return redisClient.getFolderId("CSV");
            })
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        year: year,
                        week: week,
                        id: id
                    });
                });
            })
            .then(createCSVFile)
            .then((result) => {
                return redisClient.setFileId('CSV', result.id);
            });
    }

    let removeTokens = () => {
        return Promise.fromCallback((cb) => limiter.removeTokens(1, cb));
    }

    let authorize = () => {
        return Promise.fromCallback((cb) => client.authorize(cb));
    }

    let setCredentials = (tokens, err) => {
        if (err) {
            console.log(err);
            return;
        }

        oauth2Client.setCredentials({
            access_token: tokens.access_token
        });

        return new Promise((resolve) => resolve({}));
    }

    let findRootFolder = () => {
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: "mimeType='application/vnd.google-apps.folder' and name='CFB'"
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findPlayByPlayFolder = (result) => {
        let rootId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='Play By Play' and '${rootId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findYearFolder = (result) => {
        let pbpId = result.result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='${result.year}' and '${pbpId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findYearSubFolders = (result) => {
        let yearId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and '${yearId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findJSONWeekFolder = (result) => {
        let jsonFolderId = result.result.files.find(f => f.name == "JSON").id;
        let csvFolderId = result.result.files.find(f => f.name == "CSV").id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='Week ${result.week}' and '${jsonFolderId}' in parents`
            }, cb));
        };

        redisClient.setFolderId("JSON", jsonFolderId);
        redisClient.setFolderId("CSV", csvFolderId);

        return removeTokens().then(action);
    }

    let findJSONWeekSubFolders = (result) => {
        let jsonWeekId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and '${jsonWeekId}' in parents`
            }, cb));
        };

        redisClient.setFolderId("JSONWeek", jsonWeekId);

        return removeTokens().then(action);
    }

    let storeFolderIds = (result) => {
        let jsonFullId = result.files.find(f => f.name == "full").id;
        let jsonFlattenedId = result.files.find(f => f.name == "flattened").id;

        return redisClient.setFolderId("JSONFull", jsonFullId)
            .then(() => {
                return redisClient.setFolderId("JSONFlat", jsonFlattenedId);
            });
    }

    let createCSVFile = (result) => {
        let driveResult;
        let Readable = require('stream').Readable;
        let stream = new Readable();
        stream.push(null);

        let action = () => {
            return Promise.fromCallback((cb) => drive.files.create({
                auth: oauth2Client,
                resource: {
                    'name': `PBP - ${result.year} - Week ${result.week}.csv`,
                    parents: [result.id]
                },
                media: {
                    mimeType: 'text/csv',
                    body: stream
                },
                fields: 'id'
            }, cb));
        };

        return removeTokens()
            .then(action)
            .then((result) => {
                driveResult = result;
                let header = '"gameId","year","week","homeId","homeTeam","homeAbbr","awayId","awayTeam","awayAbbr","driveIndex","playIndex","offenseId","offenseTeam","offenseAbbr","defenseId","defenseTeam","defenseAbbr","homeScore","awayScore","isScoringPlay","quarter","clock","type","down","distance","yardLine","yardsGained","endYardLine","description"';
                return Promise.fromCallback((cb) => fs.writeFile(`${process.env.CSV_PATH}${result.id}.csv`, header, cb));
            })
            .then(() => {
                return new Promise((resolve) => {
                    resolve(driveResult);
                })
            });
    }

    let getReadableStream = (result) => {
        let Readable = require('stream').Readable;
        let stream = new Readable();
        stream.push(JSON.stringify(result.json, null, '\t'));
        stream.push(null);
        result.stream = stream

        return new Promise((resolve) => {
            resolve(result);
        });
    }

    let writeJSONFile = (result) => {
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.create({
                auth: oauth2Client,
                resource: {
                    'name': result.filename,
                    parents: [result.id]
                },
                media: {
                    mimeType: 'application/json',
                    body: result.stream
                },
                fields: 'id'
            }, cb));
        };

        return removeTokens().then(action);
    }

    let updateCSV = (result) => {
        let csv = '\r\n' + json2csv({
            hasCSVColumnTitle: false,
            data: result.json
        });

        return Promise.fromCallback((cb) => fs.appendFile(`${process.env.CSV_PATH}${result.id}.csv`, csv, cb));
    };

    let writeJSON = (filename, full, flattened) => {
        return authorize()
            .then(setCredentials)
            .then(() => redisClient.getFolderId('JSONFull'))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        filename: filename,
                        id: id,
                        json: full
                    });
                });
            })
            .then(getReadableStream)
            .then(writeJSONFile)
            .then(() => redisClient.getFolderId('JSONFlat'))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        filename: filename,
                        id: id,
                        json: flattened
                    });
                });
            })
            .then(getReadableStream)
            .then(writeJSONFile)
            .then(() => redisClient.getFileId("CSV"))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        json: flattened,
                        id: id
                    });
                });
            })
            .then(updateCSV);
    }

    let uploadCSV = (count) => {
        if (count && count > 0) {
            let id;

            return redisClient.getFileId('CSV')
                .then((result) => {
                    id = result;
                    return new Promise(resolve => resolve({}));
                })
                .then(() => {
                    return Promise.fromCallback((cb) => fs.readFile(`${process.env.CSV_PATH}${id}.csv`, 'utf8', cb));
                })
                .then((content) => {
                    let Readable = require('stream').Readable;
                    let stream = new Readable();
                    stream.push(content);
                    stream.push(null);

                    return new Promise(resolve => resolve(stream));
                })
                .then((stream) => {
                    return Promise.fromCallback((cb) => drive.files.update({
                        auth: oauth2Client,
                        fileId: id,
                        media: {
                            body: stream
                        }
                    }, cb));
                });
        }
    }

    return {
        setFolders: setFolders,
        writeJSON: writeJSON,
        uploadCSV: uploadCSV
    }
}<commit_msg>updates to key storage<commit_after>module.exports = (RateLimiter, google, googleAuth, Promise, redisClient, json2csv, fs) => {
    let limiter = new RateLimiter(1, 100);

    let auth = new googleAuth();
    let oauth2Client = new auth.OAuth2();

    let SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file'];

    let drive = google.drive('v3');
    let client = new google.auth.JWT(
        process.env.CLIENT_EMAIL,
        null,
        process.env.PRIVATE_KEY,
        SCOPES
    );

    let setFolders = (year, week) => {

        return authorize()
            .then(setCredentials)
            .then(findRootFolder)
            .then(findPlayByPlayFolder)
            .then((result) => {
                return new Promise((resolve) => {
                    resolve({
                        year: year,
                        result: result
                    });
                });
            })
            .then(findYearFolder)
            .then(findYearSubFolders)
            .then((result) => {
                return new Promise((resolve) => {
                    resolve({
                        week: week,
                        result: result
                    });
                });
            })
            .then(findJSONWeekFolder)
            .then(findJSONWeekSubFolders)
            .then(storeFolderIds)
            .then(() => {
                return redisClient.getFolderId("CSV");
            })
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        year: year,
                        week: week,
                        id: id
                    });
                });
            })
            .then(createCSVFile)
            .then((result) => {
                return redisClient.setFileId('CSV', result.id);
            });
    }

    let removeTokens = () => {
        return Promise.fromCallback((cb) => limiter.removeTokens(1, cb));
    }

    let authorize = () => {
        return Promise.fromCallback((cb) => client.authorize(cb));
    }

    let setCredentials = (tokens, err) => {
        if (err) {
            console.log(err);
            return;
        }

        oauth2Client.setCredentials({
            access_token: tokens.access_token
        });

        return new Promise((resolve) => resolve({}));
    }

    let findRootFolder = () => {
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: "mimeType='application/vnd.google-apps.folder' and name='CFB'"
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findPlayByPlayFolder = (result) => {
        let rootId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='Play By Play' and '${rootId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findYearFolder = (result) => {
        let pbpId = result.result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='${result.year}' and '${pbpId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findYearSubFolders = (result) => {
        let yearId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and '${yearId}' in parents`
            }, cb));
        };

        return removeTokens().then(action);
    }

    let findJSONWeekFolder = (result) => {
        let jsonFolderId = result.result.files.find(f => f.name == "JSON").id;
        let csvFolderId = result.result.files.find(f => f.name == "CSV").id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and name='Week ${result.week}' and '${jsonFolderId}' in parents`
            }, cb));
        };

        redisClient.setFolderId("JSON", jsonFolderId);
        redisClient.setFolderId("CSV", csvFolderId);

        return removeTokens().then(action);
    }

    let findJSONWeekSubFolders = (result) => {
        let jsonWeekId = result.files[0].id;
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.list({
                auth: oauth2Client,
                q: `mimeType='application/vnd.google-apps.folder' and '${jsonWeekId}' in parents`
            }, cb));
        };

        redisClient.setFolderId("JSONWeek", jsonWeekId);

        return removeTokens().then(action);
    }

    let storeFolderIds = (result) => {
        let jsonFullId = result.files.find(f => f.name == "full").id;
        let jsonFlattenedId = result.files.find(f => f.name == "flattened").id;

        return redisClient.setFolderId("JSONFull", jsonFullId)
            .then(() => {
                return redisClient.setFolderId("JSONFlat", jsonFlattenedId);
            });
    }

    let createCSVFile = (result) => {
        let driveResult;
        let Readable = require('stream').Readable;
        let stream = new Readable();
        stream.push(null);

        let action = () => {
            return Promise.fromCallback((cb) => drive.files.create({
                auth: oauth2Client,
                resource: {
                    'name': `PBP - ${result.year} - Week ${result.week}.csv`,
                    parents: [result.id]
                },
                media: {
                    mimeType: 'text/csv',
                    body: stream
                },
                fields: 'id'
            }, cb));
        };

        return removeTokens()
            .then(action)
            .then((result) => {
                driveResult = result;
                let header = '"gameId","year","week","homeId","homeTeam","homeAbbr","awayId","awayTeam","awayAbbr","driveIndex","playIndex","offenseId","offenseTeam","offenseAbbr","defenseId","defenseTeam","defenseAbbr","homeScore","awayScore","isScoringPlay","quarter","clock","type","down","distance","yardLine","yardsGained","endYardLine","description"';
                return Promise.fromCallback((cb) => fs.writeFile(`${process.env.CSV_PATH}${result.id}.csv`, header, cb));
            })
            .then(() => {
                return new Promise((resolve) => {
                    resolve(driveResult);
                })
            });
    }

    let getReadableStream = (result) => {
        let Readable = require('stream').Readable;
        let stream = new Readable();
        stream.push(JSON.stringify(result.json, null, '\t'));
        stream.push(null);
        result.stream = stream

        return new Promise((resolve) => {
            resolve(result);
        });
    }

    let writeJSONFile = (result) => {
        let action = () => {
            return Promise.fromCallback((cb) => drive.files.create({
                auth: oauth2Client,
                resource: {
                    'name': result.filename,
                    parents: [result.id]
                },
                media: {
                    mimeType: 'application/json',
                    body: result.stream
                },
                fields: 'id'
            }, cb));
        };

        return removeTokens().then(action);
    }

    let updateCSV = (result) => {
        let csv = '\r\n' + json2csv({
            hasCSVColumnTitle: false,
            data: result.json
        });

        return Promise.fromCallback((cb) => fs.appendFile(`${process.env.CSV_PATH}${result.id}.csv`, csv, cb));
    };

    let writeJSON = (filename, full, flattened) => {
        return authorize()
            .then(setCredentials)
            .then(() => redisClient.getFolderId('JSONFull'))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        filename: filename,
                        id: id,
                        json: full
                    });
                });
            })
            .then(getReadableStream)
            .then(writeJSONFile)
            .then(() => redisClient.getFolderId('JSONFlat'))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        filename: filename,
                        id: id,
                        json: flattened
                    });
                });
            })
            .then(getReadableStream)
            .then(writeJSONFile)
            .then(() => redisClient.getFileId("CSV"))
            .then((id) => {
                return new Promise((resolve) => {
                    resolve({
                        json: flattened,
                        id: id
                    });
                });
            })
            .then(updateCSV);
    }

    let uploadCSV = (count) => {
        if (count && count > 0) {
            let id;

            return redisClient.getFileId('CSV')
                .then((result) => {
                    id = result;
                    return new Promise(resolve => resolve({}));
                })
                .then(() => {
                    return Promise.fromCallback((cb) => fs.readFile(`${process.env.CSV_PATH}${id}.csv`, 'utf8', cb));
                })
                .then((content) => {
                    let Readable = require('stream').Readable;
                    let stream = new Readable();
                    stream.push(content);
                    stream.push(null);

                    return new Promise(resolve => resolve(stream));
                })
                .then((stream) => {
                    return Promise.fromCallback((cb) => drive.files.update({
                        auth: oauth2Client,
                        fileId: id,
                        media: {
                            body: stream
                        }
                    }, cb));
                });
        }
    }

    return {
        setFolders: setFolders,
        writeJSON: writeJSON,
        uploadCSV: uploadCSV
    }
}<|endoftext|>


<commit_before>require('dotenv').load();

if (!process.env.MONZO_CLIENT_ID || !process.env.MONZO_CLIENT_SECRET || !process.env.MONZO_REDIRECT_URI) {
  return console.error('❗ Failed to load in the environment variables. Are they missing from the `.env` file?');
}

if (!process.env.GOOGLE_MAPS_API_KEY) {
  return console.error('✋ Warning: No `GOOGLE_MAPS_API_KEY` environment variable found in the `.env` file. Google Maps will not work across the application.');
}

const express = require('express');
const morgan = require('morgan');
const request = require('request');
const path = require('path');

const inDevelopment = process.env.NODE_ENV !== 'production';

let app = express();

if (inDevelopment) {
  const webpack = require('webpack');
  const devMiddleware = require('webpack-dev-middleware');
  const hotMiddleware = require('webpack-hot-middleware');
  const config = require('./webpack.config');

  const compiler = webpack(config);

  app.use(devMiddleware(compiler, {
    publicPath: config.output.publicPath,
    historyApiFallback: true
  }));

  app.use(hotMiddleware(compiler));
} else {
  // Static files
  app.use(express.static(path.resolve(path.resolve('.'), 'dist')));
}

// Logging
app.use(morgan('combined'));

// Route to get our token
app.get('/token', (req, res) => {
  if (!req.query.code && !req.query.grant_type) {
    return res.status(401).json({
      message: 'No authorisation code provided'
    });
  }

  request.post({
    url: 'https://api.getmondo.co.uk/oauth2/token',
    form: {
      grant_type: req.query.grant_type || 'authorization_code',
      client_id: process.env.MONZO_CLIENT_ID,
      client_secret: process.env.MONZO_CLIENT_SECRET,
      redirect_uri: process.env.MONZO_REDIRECT_URI,
      [req.query.grant_type === 'refresh_token' ? 'refresh_token' : 'code']:
        req.query.grant_type === 'refresh_token' ? req.query.refresh_token : req.query.code
    }
  }, (err, response, body) => {
    if (!err && response.statusCode === 200) {
      res.status(200).json(JSON.parse(body));
    } else {
      res.status(response.statusCode).json({
        message: body
      });
    }
  });
});

// Send everything else to react-router
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, inDevelopment ? 'src' : 'dist', 'index.html'));
});

app.listen(process.env.PORT || 8000, (err) => {
  if (err) {
    return console.error(err);
  }

  console.log(`🌐 Listening at http://localhost:${process.env.PORT || 8000}/`);
  console.log(`${inDevelopment ? '🛠 Development' : '🚀 Production'} mode`);
});
<commit_msg>Don't stop server when GOOGLE_MAPS_API is missing<commit_after>require('dotenv').load();

if (!process.env.MONZO_CLIENT_ID || !process.env.MONZO_CLIENT_SECRET || !process.env.MONZO_REDIRECT_URI) {
  return console.error('❗ Failed to load in the environment variables. Are they missing from the `.env` file?');
}

if (!process.env.GOOGLE_MAPS_API_KEY) {
  console.error('✋ Warning: No `GOOGLE_MAPS_API_KEY` environment variable found in the `.env` file. Google Maps will not work across the application.');
}

const express = require('express');
const morgan = require('morgan');
const request = require('request');
const path = require('path');

const inDevelopment = process.env.NODE_ENV !== 'production';

let app = express();

if (inDevelopment) {
  const webpack = require('webpack');
  const devMiddleware = require('webpack-dev-middleware');
  const hotMiddleware = require('webpack-hot-middleware');
  const config = require('./webpack.config');

  const compiler = webpack(config);

  app.use(devMiddleware(compiler, {
    publicPath: config.output.publicPath,
    historyApiFallback: true
  }));

  app.use(hotMiddleware(compiler));
} else {
  // Static files
  app.use(express.static(path.resolve(path.resolve('.'), 'dist')));
}

// Logging
app.use(morgan('combined'));

// Route to get our token
app.get('/token', (req, res) => {
  if (!req.query.code && !req.query.grant_type) {
    return res.status(401).json({
      message: 'No authorisation code provided'
    });
  }

  request.post({
    url: 'https://api.getmondo.co.uk/oauth2/token',
    form: {
      grant_type: req.query.grant_type || 'authorization_code',
      client_id: process.env.MONZO_CLIENT_ID,
      client_secret: process.env.MONZO_CLIENT_SECRET,
      redirect_uri: process.env.MONZO_REDIRECT_URI,
      [req.query.grant_type === 'refresh_token' ? 'refresh_token' : 'code']:
        req.query.grant_type === 'refresh_token' ? req.query.refresh_token : req.query.code
    }
  }, (err, response, body) => {
    if (!err && response.statusCode === 200) {
      res.status(200).json(JSON.parse(body));
    } else {
      res.status(response.statusCode).json({
        message: body
      });
    }
  });
});

// Send everything else to react-router
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, inDevelopment ? 'src' : 'dist', 'index.html'));
});

app.listen(process.env.PORT || 8000, (err) => {
  if (err) {
    return console.error(err);
  }

  console.log(`🌐 Listening at http://localhost:${process.env.PORT || 8000}/`);
  console.log(`${inDevelopment ? '🛠 Development' : '🚀 Production'} mode`);
});
<|endoftext|>


<commit_before>/*!
 * guzzle
 * Copyright(c) 2014 Lauren Smith <isfinite@gmail.com>
 * MIT Licensed
 */

'use strict';

/**
* Module dependencies.
*/

var inquirer = require('inquirer'),
	fs = require('fs'),
	exec = require('child_process').exec,
	spawn = require('child_process').spawn,
	prompts = require('./prompt'),
	Bower = require('./bower'),
	NPM = require('./npm');

/**
* Expose `Guzzle`.
*/

exports = module.exports = Guzzle;

/**
* Setup guzzle.
* @api public
*/

function Guzzle() {

}

Guzzle.prototype.deleteFiles = function(files, callback) {
	var totalDeleted = 0,
		totalToDelete = files.length;
	files.forEach(function(file) {
		unlink(file, function() {
			totalDeleted++;
			if (totalDeleted === totalToDelete) callback && callback();
		});
	});
}

Guzzle.prototype.writeScaffold = function(filename, ext, callback) {
	var stream, data;

	if (ext !== 'js') {
		fs.readFile(__dirname + '/scaffolds/' + filename, { encoding: 'utf8' }, function(err, data) {
			if (data.indexOf('module.exports') !== -1) data = JSON.stringify( require(__dirname + '/scaffolds/' + filename)(this.data), null, 4 );
			fs.writeFile((ext) ? filename + '.' + ext : '.' + filename, data, callback);
		}.bind(this));
	} else {
		fs.createReadStream(__dirname + '/scaffolds/' + filename)
			.pipe(fs.createWriteStream(process.cwd() + '/' + filename + '.' + ext))
			.on('finish', callback || function() {});
	}
}

Guzzle.prototype.cmd = function(msg, cmd, args, verbose, callback) {
	var ls = spawn(cmd, args), timer;

	console.log(msg);

	if (!verbose) {
		timer = setInterval(function() {
			process.stdout.write('=');
		}, 100);
	}

	ls.stdout.on('data', function() {
		clearInterval(timer);
		console.log();
		callback && callback();
	});

	ls.stderr.setEncoding('utf8');
	ls.stderr.on('data', function(data) {
		process.stdout.write(data);
	})
}

Guzzle.prototype.run = function() {

	var prompt = function(data) {
		var	npm = new NPM(),
			bower = new Bower(data.bower_install);

		this.data = data;

		fs.mkdir('lib', function() {
			fs.mkdir('lib/js');
			fs.mkdir('lib/css');
		});

		var writeScaffolds = function() {
			var files = [
				{ name: 'server', ext: 'js' },
				{ name: 'gulpfile', ext: 'js' },
				{ name: 'package', ext: 'json', callback: function() {
					npm.run();
				}},
				{ name: 'npmignore', ext: false },
				{ name: 'gitignore', ext: false }
			];

			do {
				var file = files.shift();
				this.writeScaffold(file.name, file.ext, (file.callback) ? file.callback : null);
			} while(files.length);
		}.bind(this);

		if (data.use_testing) {
			npm.dependencies.dev.push('mocha');
			npm.dependencies.dev.push('should');
			npm.dependencies.dev.push('gulp-mocha');
			fs.mkdir('test', function() {
				fs.writeFile(process.cwd() + '/test/mocha.opts', '--reporter min\n--require should');
			});
		}

		if (data.use_browserify) {
			npm.dependencies.dev.push('vinyl-source-stream');
			npm.dependencies.dev.push('browserify');
		}

		if (data.use_bower) {
			npm.dependencies.dev.push('gulp-bower-files');

			this.writeScaffold('bowerrc', false);
			this.writeScaffold('bower', 'json', function() {
				bower = new Bower();
				bower.packages = data.bower_install;
				bower.directory = data.bower_dir;

				bower.run(writeScaffolds);
			});
		} else {
			writeScaffolds();
		}
	}.bind(this);

	exec('ls . | wc -l', function(err, total) {
		if (total <= 0) {
			prompts.shift();
			inquirer.prompt(prompts, prompt);
		} else {
			inquirer.prompt([prompts.shift()], function(data) {
				if (data.pre_install === 'Continue') {
					inquirer.prompt(prompts, prompt);
				} else if (data.pre_install === 'Exit') {
					process.exit(1);
				} else if (data.pre_install === 'Empty directory and continue') {

				}
			});
		}

		/*
		if (data.pre_install && !data.pre_install === 'Continue') {
			switch(data.pre_install) {
				case 'Exit':
					process.exit(1);
					break;
				case 'Empty directory and continue':

					break;
			}
		}
		*/
	});
}<commit_msg>cleanup<commit_after>/*!
 * guzzle
 * Copyright(c) 2014 Lauren Smith <isfinite@gmail.com>
 * MIT Licensed
 */

'use strict';

/**
* Module dependencies.
*/

var inquirer = require('inquirer'),
	fs = require('fs'),
	exec = require('child_process').exec,
	spawn = require('child_process').spawn,
	prompts = require('./prompt'),
	Bower = require('./bower'),
	NPM = require('./npm');

/**
* Expose `Guzzle`.
*/

exports = module.exports = Guzzle;

/**
* Setup guzzle.
* @api public
*/

function Guzzle() {

}

Guzzle.prototype.deleteFiles = function(files, callback) {
	var totalDeleted = 0,
		totalToDelete = files.length;
	files.forEach(function(file) {
		unlink(file, function() {
			totalDeleted++;
			if (totalDeleted === totalToDelete) callback && callback();
		});
	});
}

Guzzle.prototype.writeScaffold = function(filename, ext, callback) {
	var stream, data;

	if (ext !== 'js') {
		fs.readFile(__dirname + '/scaffolds/' + filename, { encoding: 'utf8' }, function(err, data) {
			if (data.indexOf('module.exports') !== -1) data = JSON.stringify( require(__dirname + '/scaffolds/' + filename)(this.data), null, 4 );
			fs.writeFile((ext) ? filename + '.' + ext : '.' + filename, data, callback);
		}.bind(this));
	} else {
		fs.createReadStream(__dirname + '/scaffolds/' + filename)
			.pipe(fs.createWriteStream(process.cwd() + '/' + filename + '.' + ext))
			.on('finish', callback || function() {});
	}
}

Guzzle.prototype.cmd = function(msg, cmd, args, verbose, callback) {
	var ls = spawn(cmd, args), timer;

	console.log(msg);

	if (!verbose) {
		timer = setInterval(function() {
			process.stdout.write('=');
		}, 100);
	}

	ls.stdout.on('data', function() {
		clearInterval(timer);
		console.log();
		callback && callback();
	});

	ls.stderr.setEncoding('utf8');
	ls.stderr.on('data', function(data) {
		process.stdout.write(data);
	})
}

Guzzle.prototype.run = function() {

	var prompt = function(data) {
		var	npm = new NPM(),
			bower = new Bower(data.bower_install);

		this.data = data;

		fs.mkdir('lib', function() {
			fs.mkdir('lib/js');
			fs.mkdir('lib/css');
		});

		var writeScaffolds = function() {
			var files = [
				{ name: 'server', ext: 'js' },
				{ name: 'gulpfile', ext: 'js' },
				{ name: 'package', ext: 'json', callback: function() {
					npm.run();
				}},
				{ name: 'npmignore', ext: false },
				{ name: 'gitignore', ext: false }
			];

			do {
				var file = files.shift();
				this.writeScaffold(file.name, file.ext, (file.callback) ? file.callback : null);
			} while(files.length);
		}.bind(this);

		if (data.use_testing) {
			npm.dependencies.dev.push('mocha');
			npm.dependencies.dev.push('should');
			npm.dependencies.dev.push('gulp-mocha');
			fs.mkdir('test', function() {
				fs.writeFile(process.cwd() + '/test/mocha.opts', '--reporter min\n--require should');
			});
		}

		if (data.use_browserify) {
			npm.dependencies.dev.push('vinyl-source-stream');
			npm.dependencies.dev.push('browserify');
		}

		if (data.use_bower) {
			npm.dependencies.dev.push('gulp-bower-files');

			this.writeScaffold('bowerrc', false);
			this.writeScaffold('bower', 'json', function() {
				bower = new Bower();
				bower.packages = data.bower_install;
				bower.directory = data.bower_dir;

				bower.run(writeScaffolds);
			});
		} else {
			writeScaffolds();
		}
	}.bind(this);

	exec('ls . | wc -l', function(err, total) {
		if (total <= 0) {
			prompts.shift();
			inquirer.prompt(prompts, prompt);
		} else {
			inquirer.prompt([prompts.shift()], function(data) {
				if (data.pre_install === 'Continue') {
					inquirer.prompt(prompts, prompt);
				} else if (data.pre_install === 'Exit') {
					process.exit(1);
				} else if (data.pre_install === 'Empty directory and continue') {

				}
			});
		}
	});
}<|endoftext|>


<commit_before>require('cleansocket/listen')

const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')
const mime = require('mime')
const humanize = require('humanize')
const JunkDrawer = require('./')
const Handlebars = require('handlebars')
const Ecstatic = require('ecstatic')

const drawerPath = process.env.JUNKPATH
const drawerRoot = path.resolve(__dirname, drawerPath)

const staticDir = path.join(__dirname, 'static')
const staticPath = '/static/'

const junkDrawer = JunkDrawer({ root: drawerRoot })
const ecstatic = Ecstatic({
  baseDir: staticPath,
  root: staticDir,
})

Handlebars.registerHelper('human', function(num) {
  return humanize.filesize(num)
})

const methodEndpoints = {
  'HEAD': function (req, res) {
    const file = getFilePath(req)

    var size = 0

    const type = mime.lookup(file)
    res.setHeader('content-type', type)

    junkDrawer.createReadStream(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      })
      .on('data', function (data) { size += data.length })
      .on('end', function () {
        res.writeHead(200, {
          'x-human-size': humanize.filesize(size)
        })
        res.end()
      })
  },

  'GET': function (req, res) {
    if (isIndex(req))
      return showIndex(res)

    if (isStatic(req))
      return ecstatic(req, res)

    const file = getFilePath(req)
    const type = mime.lookup(file)

    res.setHeader('content-type', type)
    junkDrawer.createReadStream(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      }).pipe(res)
  },

  'DELETE': function (req, res) {
    const file = getFilePath(req)

    junkDrawer.deleteFile(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      })
      .on('done', function () {
        res.writeHead(200, {'content-type': 'text/plain'})
        res.write('yeah, fuck that file anyway')
        res.end()
      })
  },

  'POST': function (req, res) {
    const file = getFilePath(req)

    req.on('error', function (error) {
      console.dir(error)
      return forbidden(res)
    })

    req.pipe(junkDrawer.createWriteStream(file))
      .on('error', function (error) {
        console.dir(error)
        return forbidden(res)
      })
      .on('finish', function () {
        res.writeHead(200, {'content-type': 'text/plain'})
        res.write('got it')
        res.end()
      })
  }
}

http.createServer(function (req, res) {
  const method = req.method

  if (!acceptableMethod(method)) {
    res.writeHead(406)
    res.write('Method Not Allowed')
    return res.end()
  }

  return methodEndpoints[method](req, res)

}).listen(process.env.SOCKET || process.env.PORT || '/tmp/junk.sock')

function isIndex(req) {
  const parts = url.parse(req.url)
  return parts.pathname.trim() === '/'
}

function isStatic(req) {
  const parts = url.parse(req.url)
  const fullpath = parts.pathname
  return fullpath.indexOf(path.join(staticPath, '/')) === 0
}

function showIndex(res) {
  const templateFile = path.join(__dirname, 'index.html')
  fs.readFile(templateFile, function (error, contents) {
    if (error) {
      console.dir(error)
      return fileNotFound(res)
    }

    const tmpl = Handlebars.compile(contents.toString('utf8'))
    junkDrawer.getFileList(function (error, files) {
      if (error) {
        console.dir(error)
        return fileNotFound(res)
      }

      res.writeHead(200, {'content-type': 'text/html'})
      res.write(tmpl({ files: files }))
      res.end()
    })
  })
}

function getFilePath(req) {
  const parts = url.parse(req.url)
  return unescape(parts.pathname).slice(1)
}

function acceptableMethod(method) {
  var METHODS = ['GET', 'POST', 'DELETE', 'HEAD']
  return METHODS.indexOf(method) !== -1
}

function forbidden(res) {
  res.writeHead(403, {'content-type': 'text/plain'})
  res.write('fuck all that')
  res.end()
}

function fileNotFound(res) {
  res.writeHead(404, {'content-type': 'text/plain'})
  res.write('can\'t find shit')
  res.end()
}
<commit_msg>Allow cors<commit_after>require('cleansocket/listen')

const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')
const mime = require('mime')
const humanize = require('humanize')
const JunkDrawer = require('./')
const Handlebars = require('handlebars')
const Ecstatic = require('ecstatic')

const drawerPath = process.env.JUNKPATH
const drawerRoot = path.resolve(__dirname, drawerPath)

const staticDir = path.join(__dirname, 'static')
const staticPath = '/static/'

const junkDrawer = JunkDrawer({ root: drawerRoot })
const ecstatic = Ecstatic({
  baseDir: staticPath,
  root: staticDir,
})

Handlebars.registerHelper('human', function(num) {
  return humanize.filesize(num)
})

const methodEndpoints = {
  'HEAD': function (req, res) {
    const file = getFilePath(req)

    var size = 0

    const type = mime.lookup(file)
    res.setHeader('content-type', type)

    junkDrawer.createReadStream(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      })
      .on('data', function (data) { size += data.length })
      .on('end', function () {
        res.writeHead(200, {
          'x-human-size': humanize.filesize(size)
        })
        res.end()
      })
  },

  'GET': function (req, res) {
    if (isIndex(req))
      return showIndex(res)

    if (isStatic(req))
      return ecstatic(req, res)

    const file = getFilePath(req)
    const type = mime.lookup(file)

    res.setHeader('content-type', type)
    res.setHeader('access-control-allow-origin', '*')
    junkDrawer.createReadStream(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      }).pipe(res)
  },

  'DELETE': function (req, res) {
    const file = getFilePath(req)

    junkDrawer.deleteFile(file)
      .on('error', function (error) {
        console.dir(error)
        return fileNotFound(res)
      })
      .on('done', function () {
        res.writeHead(200, {'content-type': 'text/plain'})
        res.write('yeah, fuck that file anyway')
        res.end()
      })
  },

  'POST': function (req, res) {
    const file = getFilePath(req)

    req.on('error', function (error) {
      console.dir(error)
      return forbidden(res)
    })

    req.pipe(junkDrawer.createWriteStream(file))
      .on('error', function (error) {
        console.dir(error)
        return forbidden(res)
      })
      .on('finish', function () {
        res.writeHead(200, {'content-type': 'text/plain'})
        res.write('got it')
        res.end()
      })
  }
}

http.createServer(function (req, res) {
  const method = req.method

  if (!acceptableMethod(method)) {
    res.writeHead(406)
    res.write('Method Not Allowed')
    return res.end()
  }

  return methodEndpoints[method](req, res)

}).listen(process.env.SOCKET || process.env.PORT || '/tmp/junk.sock')

function isIndex(req) {
  const parts = url.parse(req.url)
  return parts.pathname.trim() === '/'
}

function isStatic(req) {
  const parts = url.parse(req.url)
  const fullpath = parts.pathname
  return fullpath.indexOf(path.join(staticPath, '/')) === 0
}

function showIndex(res) {
  const templateFile = path.join(__dirname, 'index.html')
  fs.readFile(templateFile, function (error, contents) {
    if (error) {
      console.dir(error)
      return fileNotFound(res)
    }

    const tmpl = Handlebars.compile(contents.toString('utf8'))
    junkDrawer.getFileList(function (error, files) {
      if (error) {
        console.dir(error)
        return fileNotFound(res)
      }

      res.writeHead(200, {'content-type': 'text/html'})
      res.write(tmpl({ files: files }))
      res.end()
    })
  })
}

function getFilePath(req) {
  const parts = url.parse(req.url)
  return unescape(parts.pathname).slice(1)
}

function acceptableMethod(method) {
  var METHODS = ['GET', 'POST', 'DELETE', 'HEAD']
  return METHODS.indexOf(method) !== -1
}

function forbidden(res) {
  res.writeHead(403, {'content-type': 'text/plain'})
  res.write('fuck all that')
  res.end()
}

function fileNotFound(res) {
  res.writeHead(404, {'content-type': 'text/plain'})
  res.write('can\'t find shit')
  res.end()
}
<|endoftext|>


<commit_before>const express = require('express');
const i18n = require('i18n-abide');

const app = express();

app.use(i18n.abide({
  supported_languages: ['en-US', 'it-CH'],
  default_lang: 'en-US',
  debug_lang: 'it-CH',
  translation_directory: 'i18n'
}));

app.get('/.well-known/browserid', function (req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send('{"disable": true}');
});

app.get('/provision', function (req, res) {
  res.send(req.gettext('TODO: Add provisioning page'));
});

app.get('/authenticate', function (req, res) {
  res.send(req.gettext('TODO: Add authentication page'));
});

app.listen(3000);
<commit_msg>Add simple heartbeat<commit_after>const express = require('express');
const i18n = require('i18n-abide');

const app = express();

app.use(i18n.abide({
  supported_languages: ['en-US', 'it-CH'],
  default_lang: 'en-US',
  debug_lang: 'it-CH',
  translation_directory: 'i18n'
}));

app.get('/__heartbeat__', function (req, res) {
  res.send('ok');
});

app.get('/.well-known/browserid', function (req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send('{"disable": true}');
});

app.get('/provision', function (req, res) {
  res.send(req.gettext('TODO: Add provisioning page'));
});

app.get('/authenticate', function (req, res) {
  res.send(req.gettext('TODO: Add authentication page'));
});

app.listen(3000);
<|endoftext|>