<commit_before>/**
 * Created by Benson.Liao on 15/12/9.
 * --always-compact: always full gc().
 * --expose-gc: manual gc().
 */
var debug = require('debug')('LiveCluster');
var fxNetSocket = require('./fxNetSocket');
var FxConnection = fxNetSocket.netConnection;
var outputStream = fxNetSocket.stdoutStream;
var parser = fxNetSocket.parser;
var utilities = fxNetSocket.utilities;
var logger = fxNetSocket.logger;
var fs  = require('fs');
var net  = require('net');
var evt = require('events');
var cfg = require('./config.js');
var proc = require('child_process');
/** 所有視訊stream物件 **/
var liveStreams = {};
/** 多執行緒 **/
var cluster = require('cluster');
var isWorker = ('NODE_CDID' in process.env);
var isMaster = (isWorker === false);
var server;
/** cluster start **/
process.on('message', function(data , handle) {

    if (data == 0) {
        isMaster = false;

        debug('[Runnable] Create cluster id:',data );

        var self = this;

        var srv = new FxConnection(handle);
        setupCluster(srv);
        server = srv;
    }
    else if ((typeof data.handle != 'undefined') && data.handle === 'socketSend'){
        socketSend(data.evt,data.spawnName);
    } else{
        var json = data;
        //debug(json.namespace);
        var spawnName = json.namespace;
        var clients = server.getClients();
        var keys = Object.keys(clients);
        if (keys.length == 0) return;
        for (var i = 0 ; i < keys.length; i++) {
            var socket = clients[keys[i]];
            if (socket.isConnect == true) {
                if (socket.namespace == spawnName)
                {
                    var str = JSON.stringify({"NetStreamEvent":"NetStreamData",'data':json.data});
                    //debug('INFO::::%s bytes', Buffer.byteLength(str));
                    //!!!! cpu very busy !!!
                    socket.write(str)
                }

            }
        }
        keys = null;
    }

});

if (isMaster) initizatialSrv();

/** cluster ended **/

function initizatialSrv() {
    /** createLiveStreams **/
    createLiveStreams(cfg.appConfig.fileName);
    setInterval(observerTotoalUseMem, 60000); // testing code 1.0 min

    utilities.autoReleaseGC(); //** 手動 1 sec gc

    var srv = new FxConnection(cfg.appConfig.port,{'cluster':4});
    setupCluster(srv);
    server = srv;
}

function setupCluster(srv) {

    srv.on('Listening', function (app) {
        debug('Listening...');
        var option = {'cluster':1};
        if (typeof option === 'undefined') {
            option = {'cluster':0};
        }
        /** cluster start **/
        if (isMaster && option.cluster != 0) { // isMaster
            for (var i = 0; i < option.cluster; i++) {

                // file , fork.settings, args
                var env = process.env;
                env.NODE_CDID = i;
                var cluster = proc.fork('./FxLiveStreamSrvCluster.js',{silent:false}, {env:env});
                cluster.id = i;
                cluster.send(0, app._handle);

                cluster.on('message', function (msg) {
                    debug("serv", msg);
                });
                srv.clusters.push(cluster);

            };
            app.close();
        };
        /** cluster ended **/

    });

    srv.on('connection', function (socket) {
        debug('clients:',socket.name);

        return;
        // 檢查 Stream List 建立
        if (typeof liveStreams != 'undefined' && liveStreams != null ) {
            var swpan = liveStreams[socket.namespace];

            if (typeof swpan == 'undefined' && swpan == null ) {
                // return;

                var confirm = verificationString(socket.namespace);
                // 特殊需求這邊本來應該return;如果連線指定伺服器啟動」
                debug("rtmp://" + cfg.videoDomainName + socket.namespace , confirm);
                if (confirm) {
                    createLiveStreams(["rtmp://" + cfg.videoDomainName + socket.namespace]);
                }else
                {
                    srv.clientDestroy(socket);
                }
            }else
                rebootStream(swpan);

        }else {
            //todo 為建立狀態流程處理
            console.error("[ERROR]Stream not Create.");
        }
    });
    /** socket data event **/
    srv.on('message', function (data) {
        debug('message :',data);
    });
    /** client socket destroy **/
    srv.on('disconnect', function (socket) {
        debug('disconnect_fxconnect_client.');
        //socket.removeListener('connection', callback);
    });
    /** verification **/
    function verificationString(str) {
        var regexp = /(video\/[a-zA-Z]*\/video[0-9a-zA-Z]*)/i;
        var val = str.match(regexp);
        if (val !== null && typeof val !== 'undefined' && val[0] !== null) {
            return true;
        }else
            return false;
    }

    /**
     * client socket connection is http connect()
     * @param req: request
     * @param client: client socket
     * @param head: req header
     * **/
    srv.on('httpUpgrade', function (req, client, head) {

        debug('## upgrade ##');

        var _get = head[0].split(" ");

        var socket = client.socket;

        if (_get[1] === "/") {

            fs.readFile('public/views/broadwayPlayer.html', function (err, data) {
                successfulHeader(200, socket, "html");
                socket.write(data);

                client.close();
            });
        }
        else if (_get[1] === "/favicon.ico") {
            failureHeader(404, socket, "ico");
            client.close();
        }
        else
        {
            successfulHeader(200, socket, "js");
            var fsstream = fs.createReadStream("public" + _get[1], {bufferSize: 1024 * 300, end:false});
            var fileLength = 0;
            fsstream.pipe(socket);

            fsstream.on('data', function (chunk) {
                fileLength += chunk.length;
            });
            fsstream.on('end', function () {
                //var file = Buffer.concat(list).toString();
                debug("%s file size : %d kb",_get[1],fileLength/1024);
                //socket.write("content-length:%d\r\n", fileLength);

                //client.close();

            });
            fsstream.on('error', function (err) {
                debug('fsStream error:', err);
            });

        }

    });
    /**
     * @param code: response header Status Code
     * @param socket: client socket
     * @param type: content-type
     * */
    function successfulHeader(code, socket, type) {

        var contentType = type === 'js' ? "application/javascript" : "text/html";

        var headers = parser.headers.responseHeader(code, {
            "Host": srv.app.address().address,
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Connection": "Keep-Alive",
            "Keep-Alive": "timeout=3, max=10",
            "Access-Control-Allow-Origin": "*",
            "Content-Type": contentType
        });

        //socket.write("Content-Security-Policy: default-src 'self'; img-src *;object-src 'self' http://127.0.0.1; script-src 'self' http://127.0.0.1;\n");
        socket.write(headers);
    };
    /**
     * @param code: response header Status Code
     * @param socket: client socket
     * */
    function failureHeader(code, socket) {

        var headers = parser.headers.responseHeader(code, {
            "Connection": "close" });
        socket.write(headers);

    }

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
// STREAM //
function createLiveStreams(fileName) {
    var sn = fileName;
    var spawned,_name;
    var max = sn.length-1;
    var i = 0;
    //for (var i = 0; i < sn.length; i++) {
    //
    //};

    var si = setInterval(function () {
        // schema 2, domain 3, port 5, path 6,last path 7, file 8, querystring 9, hash 12
        _name = sn[i].toString().match(/^((rtmp[s]?):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/i);
        if (typeof  _name[6] != 'undefined' && typeof _name[8] != 'undefined') {
            var pathname = _name[6] + _name[8];
            spawned = liveStreams[pathname] = new outputStream(sn[i]);
            spawned.name = pathname;
            spawned.on('streamData', swpanedUpdate);
            spawned.on('close', swpanedClosed);
            spawned = null;
        }else {
            throw "create Live Stream path error." + sn[i];
        }
        i++;
        if (i == max) si = clearInterval(si);
    }, 100);
};
/** 重啟stream **/
function rebootStream(spawned,skip) {
    if ((spawned.running == false && spawned.STATUS >= 2) || skip == true) {
        debug('>>rebootStream:', spawned.name);
        var spawn = liveStreams[spawned.name] = new outputStream( "rtmp://" + cfg.videoDomainName + spawned.name);
        spawn.idx = spawned.idx;
        spawn.name = spawned.name;
        spawn.on('streamData', swpanedUpdate);
        spawn.on('close', swpanedClosed);
        spawned.removeListener('streamData', swpanedUpdate);
        spawned.removeListener('close', swpanedClosed);
        spawned = null;
        server.eventDispatch(3);
    }
}
/** ffmpeg stream pull the data of a base64 **/

function swpanedUpdate(base64) {
    var spawnName = this.name;
    if (server.clusters[0]){
        server.clusters[0].send({'namespace':spawnName,'data':base64});
    }
};

function socketSend(evt, spawnName) {

    if (isMaster) {
        for (var i = 0; i < server.clusters.length; i++) {
            if (server.clusters[i])
            {
                server.clusters[i].send({'handle':'socketSend','evt':evt,'spawnName':spawnName});
            }

        }

    }else
    {
        var clients = server.getClients();
        var keys = Object.keys(clients);
        if (keys.length == 0) return;

        for (var i = 0 ; i < keys.length; i++) {
            var socket = clients[keys[i]];
            if (socket.isConnect == true) {
                if (socket.namespace === spawnName)
                    socket.write(JSON.stringify(evt));
            }

        }

        keys = null;
    };

}

/* ------- start testing logger ------- */
/** ffmpeg stream close **/
function swpanedClosed(code){

    socketSend({'NetStatusEvent': 'NetConnect.Failed'}, this.name);

    //** 監聽到自動關閉,重新啟動 code == 0 **/
    if (1) {
        debug("listen swpaned Closed - ",this.name, " < REBOOTING >");
        rebootStream(this,true);
    }

    logger.reachabilityWithHostName(cfg.videoDomainName);

};
/** 觀察記憶體使用狀況 **/
function observerTotoalUseMem() {

    var keys = Object.keys(liveStreams);
    var pids = [];
    keys.asyncEach(function(element, resume) {
        resume();
        pids.push(liveStreams[element].ffmpeg.pid);
    }, function() {
        logger.logTotalMemoryUsage(pids);
    });

}
/* ------- ended testing logger ------- */

process.on('uncaughtException', function (err) {
    console.error(err.stack);
});<commit_msg>remove multi cluster<commit_after>/**
 * Created by Benson.Liao on 15/12/9.
 * --always-compact: always full gc().
 * --expose-gc: manual gc().
 */
var debug = require('debug')('LiveCluster');
var fxNetSocket = require('./fxNetSocket');
var FxConnection = fxNetSocket.netConnection;
var outputStream = fxNetSocket.stdoutStream;
var parser = fxNetSocket.parser;
var utilities = fxNetSocket.utilities;
var logger = fxNetSocket.logger;
var fs  = require('fs');
var net  = require('net');
var evt = require('events');
var cfg = require('./config.js');
var proc = require('child_process');
/** 所有視訊stream物件 **/
var liveStreams = {};
/** 多執行緒 **/
var cluster = require('cluster');
var isWorker = ('NODE_CDID' in process.env);
var isMaster = (isWorker === false);
var server;
/** cluster start **/
process.on('message', function(data , handle) {

    if (data == 0) {
        isMaster = false;

        debug('[Runnable] Create cluster id:',data );

        var self = this;

        var srv = new FxConnection(handle);
        setupCluster(srv);
        server = srv;
    }
    else if ((typeof data.handle != 'undefined') && data.handle === 'socketSend'){
        socketSend(data.evt,data.spawnName);
    } else{
        var json = data;
        //debug(json.namespace);
        var spawnName = json.namespace;
        var clients = server.getClients();
        var keys = Object.keys(clients);
        if (keys.length == 0) return;
        for (var i = 0 ; i < keys.length; i++) {
            var socket = clients[keys[i]];
            if (socket.isConnect == true) {
                if (socket.namespace == spawnName)
                {
                    var str = JSON.stringify({"NetStreamEvent":"NetStreamData",'data':json.data});
                    //debug('INFO::::%s bytes', Buffer.byteLength(str));
                    //!!!! cpu very busy !!!
                    socket.write(str)
                }

            }
        }
        keys = null;
    }

});

if (isMaster) initizatialSrv();

/** cluster ended **/

function initizatialSrv() {
    /** createLiveStreams **/
    createLiveStreams(cfg.appConfig.fileName);
    setInterval(observerTotoalUseMem, 60000); // testing code 1.0 min

    utilities.autoReleaseGC(); //** 手動 1 sec gc

    var srv = new FxConnection(cfg.appConfig.port);
    setupCluster(srv);
    server = srv;
}

function setupCluster(srv) {

    srv.on('Listening', function (app) {
        debug('Listening...');
        var option = {'cluster':1};
        if (typeof option === 'undefined') {
            option = {'cluster':0};
        }
        /** cluster start **/
        if (isMaster && option.cluster != 0) { // isMaster
            for (var i = 0; i < option.cluster; i++) {

                // file , fork.settings, args
                var env = process.env;
                env.NODE_CDID = i;
                var cluster = proc.fork('./FxLiveStreamSrvCluster.js',{silent:false}, {env:env});
                cluster.id = i;
                cluster.send(0, app._handle);

                cluster.on('message', function (msg) {
                    debug("serv", msg);
                });
                srv.clusters.push(cluster);

            };
            app.close();
        };
        /** cluster ended **/

    });

    srv.on('connection', function (socket) {
        debug('clients:',socket.name);

        return;
        // 檢查 Stream List 建立
        if (typeof liveStreams != 'undefined' && liveStreams != null ) {
            var swpan = liveStreams[socket.namespace];

            if (typeof swpan == 'undefined' && swpan == null ) {
                // return;

                var confirm = verificationString(socket.namespace);
                // 特殊需求這邊本來應該return;如果連線指定伺服器啟動」
                debug("rtmp://" + cfg.videoDomainName + socket.namespace , confirm);
                if (confirm) {
                    createLiveStreams(["rtmp://" + cfg.videoDomainName + socket.namespace]);
                }else
                {
                    srv.clientDestroy(socket);
                }
            }else
                rebootStream(swpan);

        }else {
            //todo 為建立狀態流程處理
            console.error("[ERROR]Stream not Create.");
        }
    });
    /** socket data event **/
    srv.on('message', function (data) {
        debug('message :',data);
    });
    /** client socket destroy **/
    srv.on('disconnect', function (socket) {
        debug('disconnect_fxconnect_client.');
        //socket.removeListener('connection', callback);
    });
    /** verification **/
    function verificationString(str) {
        var regexp = /(video\/[a-zA-Z]*\/video[0-9a-zA-Z]*)/i;
        var val = str.match(regexp);
        if (val !== null && typeof val !== 'undefined' && val[0] !== null) {
            return true;
        }else
            return false;
    }

    /**
     * client socket connection is http connect()
     * @param req: request
     * @param client: client socket
     * @param head: req header
     * **/
    srv.on('httpUpgrade', function (req, client, head) {

        debug('## upgrade ##');

        var _get = head[0].split(" ");

        var socket = client.socket;

        if (_get[1] === "/") {

            fs.readFile('public/views/broadwayPlayer.html', function (err, data) {
                successfulHeader(200, socket, "html");
                socket.write(data);

                client.close();
            });
        }
        else if (_get[1] === "/favicon.ico") {
            failureHeader(404, socket, "ico");
            client.close();
        }
        else
        {
            successfulHeader(200, socket, "js");
            var fsstream = fs.createReadStream("public" + _get[1], {bufferSize: 1024 * 300, end:false});
            var fileLength = 0;
            fsstream.pipe(socket);

            fsstream.on('data', function (chunk) {
                fileLength += chunk.length;
            });
            fsstream.on('end', function () {
                //var file = Buffer.concat(list).toString();
                debug("%s file size : %d kb",_get[1],fileLength/1024);
                //socket.write("content-length:%d\r\n", fileLength);

                //client.close();

            });
            fsstream.on('error', function (err) {
                debug('fsStream error:', err);
            });

        }

    });
    /**
     * @param code: response header Status Code
     * @param socket: client socket
     * @param type: content-type
     * */
    function successfulHeader(code, socket, type) {

        var contentType = type === 'js' ? "application/javascript" : "text/html";

        var headers = parser.headers.responseHeader(code, {
            "Host": srv.app.address().address,
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Connection": "Keep-Alive",
            "Keep-Alive": "timeout=3, max=10",
            "Access-Control-Allow-Origin": "*",
            "Content-Type": contentType
        });

        //socket.write("Content-Security-Policy: default-src 'self'; img-src *;object-src 'self' http://127.0.0.1; script-src 'self' http://127.0.0.1;\n");
        socket.write(headers);
    };
    /**
     * @param code: response header Status Code
     * @param socket: client socket
     * */
    function failureHeader(code, socket) {

        var headers = parser.headers.responseHeader(code, {
            "Connection": "close" });
        socket.write(headers);

    }

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
// STREAM //
function createLiveStreams(fileName) {
    var sn = fileName;
    var spawned,_name;
    var max = sn.length-1;
    var i = 0;
    //for (var i = 0; i < sn.length; i++) {
    //
    //};

    var si = setInterval(function () {
        // schema 2, domain 3, port 5, path 6,last path 7, file 8, querystring 9, hash 12
        _name = sn[i].toString().match(/^((rtmp[s]?):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/i);
        if (typeof  _name[6] != 'undefined' && typeof _name[8] != 'undefined') {
            var pathname = _name[6] + _name[8];
            spawned = liveStreams[pathname] = new outputStream(sn[i]);
            spawned.name = pathname;
            spawned.on('streamData', swpanedUpdate);
            spawned.on('close', swpanedClosed);
            spawned = null;
        }else {
            throw "create Live Stream path error." + sn[i];
        }
        i++;
        if (i == max) si = clearInterval(si);
    }, 100);
};
/** 重啟stream **/
function rebootStream(spawned,skip) {
    if ((spawned.running == false && spawned.STATUS >= 2) || skip == true) {
        debug('>>rebootStream:', spawned.name);
        var spawn = liveStreams[spawned.name] = new outputStream( "rtmp://" + cfg.videoDomainName + spawned.name);
        spawn.idx = spawned.idx;
        spawn.name = spawned.name;
        spawn.on('streamData', swpanedUpdate);
        spawn.on('close', swpanedClosed);
        spawned.removeListener('streamData', swpanedUpdate);
        spawned.removeListener('close', swpanedClosed);
        spawned = null;
        server.eventDispatch(3);
    }
}
/** ffmpeg stream pull the data of a base64 **/

function swpanedUpdate(base64) {
    var spawnName = this.name;
    if (server.clusters[0]){
        server.clusters[0].send({'namespace':spawnName,'data':base64});
    }
};

function socketSend(evt, spawnName) {

    if (isMaster) {
        for (var i = 0; i < server.clusters.length; i++) {
            if (server.clusters[i])
            {
                server.clusters[i].send({'handle':'socketSend','evt':evt,'spawnName':spawnName});
            }

        }

    }else
    {
        var clients = server.getClients();
        var keys = Object.keys(clients);
        if (keys.length == 0) return;

        for (var i = 0 ; i < keys.length; i++) {
            var socket = clients[keys[i]];
            if (socket.isConnect == true) {
                if (socket.namespace === spawnName)
                    socket.write(JSON.stringify(evt));
            }

        }

        keys = null;
    };

}

/* ------- start testing logger ------- */
/** ffmpeg stream close **/
function swpanedClosed(code){

    socketSend({'NetStatusEvent': 'NetConnect.Failed'}, this.name);

    //** 監聽到自動關閉,重新啟動 code == 0 **/
    if (1) {
        debug("listen swpaned Closed - ",this.name, " < REBOOTING >");
        rebootStream(this,true);
    }

    logger.reachabilityWithHostName(cfg.videoDomainName);

};
/** 觀察記憶體使用狀況 **/
function observerTotoalUseMem() {

    var keys = Object.keys(liveStreams);
    var pids = [];
    keys.asyncEach(function(element, resume) {
        resume();
        pids.push(liveStreams[element].ffmpeg.pid);
    }, function() {
        logger.logTotalMemoryUsage(pids);
    });

}
/* ------- ended testing logger ------- */

process.on('uncaughtException', function (err) {
    console.error(err.stack);
});<|endoftext|>


<commit_before>/* Activities */
Mailpile.activities.compose = function(address) {
  var compose_data = {};
  if (address) {
    compose_data = {to: address};
  }
	Mailpile.API.message_compose_post(compose_data, function(response) {
    if (response.status === 'success') {
      window.location.href = Mailpile.urls.message_draft + response.result.created[0] + '/';
    } else {
      Mailpile.notification(response);
    }
  });
};

Mailpile.activities.render_typeahead = function() {

  var baseMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      // an array that will be populated with substring matches
      matches = [];
      // regex used to determine if a string contains the substring `q`
      substrRegex = new RegExp(q, 'i');
      // iterate through the pool of strings and for any string that
      // contains the substring `q`, add it to the `matches` array
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.term)) {
          // the typeahead jQuery plugin expects suggestions to a
          // JavaScript object, refer to typeahead docs for more info
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  var tagMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.name)) {
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  var peopleMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.fn) || substrRegex.test(str.address)) {
          str.term =  'from:';
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  // List of basic suggestions for search helpers
  var helpers = [
    { value: 'dates:', helper: '2011-12..2012-04-15' },
    { value: 'date:', helper: 'date:2013-8-3 +date:2013-9-10' },
    { value: 'year:', helper: '2013' },
    { value: 'month:', helper: '8' },
    { value: 'subject:', helper: 'any normal words' },
    { value: 'att:', helper: 'jpg' },
    { value: 'has:', helper: 'attachment' },
    { value: 'contacts: ', helper: 'name@email.com' },
    { value: 'to:', helper: 'name@email.com' },
    { value: 'keys:', helper: 'name@email.com / keyid' }
  ];

  // Create Typeahead
  $('#form-search .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 0
  },{
    name: 'search',
    displayKey: 'value',
    source: baseMatcher(helpers),
    templates: {
      suggestion: function(data) {
        var template = _.template('

 <%= value %> <%= helper %>

');
        return template(data);
      }
    }
  },{
    name: 'tags',
    displayKey: function(value) {
      return 'in:' + value.slug
    },
    source: tagMatcher(Mailpile.instance.tags),
    templates: {
      empty: '

 No tags match your search

',
      suggestion: function(data) {
        if (data.display !== 'invisible') {
          var template = _.template('

<span class="color-<%= label_color %> <%= icon %>"> <%= name %>

');
          return template(data);
        }
      }
    }
  },{
    name: 'people',
    displayKey: function(value) {
      return value.term + value.address;
    },
    source: peopleMatcher(Mailpile.instance.addresses),
    templates: {
      header: '',
      empty: '

 No people match your search

',
      suggestion: function(data) {
        if (data.photo === undefined) { data.photo = '/static/img/avatar-default.png'; }
        var template = _.template('

<img class="avatar" src="<%= photo %>"> <%= term %> <%= fn %>

');
        return template(data);
      }
    }
  });

};<commit_msg>Fixed undefined var name in Typehead search helpers<commit_after>/* Activities */
Mailpile.activities.compose = function(address) {
  var compose_data = {};
  if (address) {
    compose_data = {to: address};
  }
	Mailpile.API.message_compose_post(compose_data, function(response) {
    if (response.status === 'success') {
      window.location.href = Mailpile.urls.message_draft + response.result.created[0] + '/';
    } else {
      Mailpile.notification(response);
    }
  });
};

Mailpile.activities.render_typeahead = function() {

  var baseMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.term)) {
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  var tagMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.name)) {
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  var peopleMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substrRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.fn) || substrRegex.test(str.address)) {
          str.term =  'from:';
          matches.push(str);
        }
      });
      cb(matches);
    };
  };

  // List of basic suggestions for search helpers
  var helpers = [
    { term: 'dates:', helper: '2011-12..2012-04-15' },
    { term: 'date:', helper: 'date:2013-8-3 +date:2013-9-10' },
    { term: 'year:', helper: '2013' },
    { term: 'month:', helper: '8' },
    { term: 'subject:', helper: 'any normal words' },
    { term: 'att:', helper: 'jpg' },
    { term: 'has:', helper: 'attachment' },
    { term: 'contacts: ', helper: 'name@email.com' },
    { term: 'to:', helper: 'name@email.com' },
    { term: 'keys:', helper: 'name@email.com / keyid' }
  ];

  // Create Typeahead
  $('#form-search .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 0
  },{
    name: 'search',
    displayKey: 'term',
    source: baseMatcher(helpers),
    templates: {
      suggestion: function(data) {
        var template = _.template('

 <%= term %> <%= helper %>

');
        return template(data);
      }
    }
  },{
    name: 'tags',
    displayKey: function(value) {
      return 'in:' + value.slug
    },
    source: tagMatcher(Mailpile.instance.tags),
    templates: {
      empty: '

 No tags match your search

',
      suggestion: function(data) {
        if (data.display !== 'invisible') {
          var template = _.template('

<span class="color-<%= label_color %> <%= icon %>"> <%= name %>

');
          return template(data);
        }
      }
    }
  },{
    name: 'people',
    displayKey: function(value) {
      return value.term + value.address;
    },
    source: peopleMatcher(Mailpile.instance.addresses),
    templates: {
      header: '',
      empty: '

 No people match your search

',
      suggestion: function(data) {
        if (data.photo === undefined) { data.photo = '/static/img/avatar-default.png'; }
        var template = _.template('

<img class="avatar" src="<%= photo %>"> <%= term %> <%= fn %>

');
        return template(data);
      }
    }
  });

};<|endoftext|>


<commit_before>import {LitElement, css, html, nothing} from 'lit';
import SHARED_STYLES from '../css/shared.css';
import {STATE_NAMES} from './chromedash-approvals-dialog.js';

class ChromedashFeatureTable extends LitElement {
  static get properties() {
    return {
      query: {type: String},
      features: {type: Array},
      loading: {type: Boolean},
      rows: {type: Number},
      columns: {type: String},
      signedIn: {type: Boolean},
      canEdit: {type: Boolean},
      canApprove: {type: Boolean},
      starredFeatures: {type: Object},
      noResultsMessage: {type: String},
      approvals: {type: Object},
      comments: {type: Object},
      configs: {type: Object},
    };
  }

  constructor() {
    super();
    this.loading = true;
    this.starredFeatures = new Set();
    this.features = [];
    this.noResultsMessage = 'No results';
    this.canEdit = false;
    this.canApprove = false;
    this.approvals = {};
    this.comments = {};
    this.configs = {};
  }

  connectedCallback() {
    super.connectedCallback();
    window.csClient.searchFeatures(this.query).then((features) => {
      this.features = features;
      this.loading = false;
      if (this.columns == 'approvals') {
        this.loadApprovalData();
      }
    });
  }

  loadApprovalData() {
    for (const feature of this.features) {
      window.csClient.getApprovals(feature.id).then(res => {
        const newApprovals = {...this.approvals};
        newApprovals[feature.id] = res.approvals;
        this.approvals = newApprovals;
      });
      window.csClient.getComments(feature.id).then(res => {
        const newComments = {...this.comments};
        newComments[feature.id] = res.comments;
        this.comments = newComments;
      });
      window.csClient.getApprovalConfigs(feature.id).then(res => {
        const newConfigs = {...this.configs};
        newConfigs[feature.id] = res.configs;
        this.configs = newConfigs;
      });
    }
  }

  static get styles() {
    return [
      SHARED_STYLES,
      css`
      table {
        width: var(--max-content-width);
      }
      tr {
        background: var(--table-row-background);
      }
      td {
        padding: var(--content-padding-half);
        border-bottom: var(--table-divider);
      }
      td.name_col {
        width: 100%;
      }
      td.icon_col {
        white-space: nowrap;
        vertical-align: top;
      }
      .quick_actions {
        white-space: nowrap;
        float: right;
      }
      .highlights {
        padding-left: var(--content-padding);
      }
      .highlights div {
        color: var(--unimportant-text-color);
        padding: var(--content-padding-quarter);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      iron-icon {
        --iron-icon-height: 18px;
        --iron-icon-width: 18px;
        color: var(--link-color);
      }
      iron-icon:hover {
        color: var(--link-hover-color);
      }
      button {
        border: var(--default-border);
        padding: 0 6px;
        font-size: var(--button-small-font-size);
      }
    `];
  }

  _fireEvent(eventName, detail) {
    const event = new CustomEvent(eventName, {
      bubbles: true,
      composed: true,
      detail,
    });
    this.dispatchEvent(event);
  }

  toggleStar(e) {
    console.log('toggleStar');
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target;
    const featureId = Number(iconEl.dataset.featureId);
    const newStarred = !this.starredFeatures.has(featureId);

    // handled in chromedash-myfeatures.js
    this._fireEvent('star-toggle-event', {
      featureId: featureId,
      doStar: newStarred,
    });
  }

  renderMessages() {
    if (this.loading) {
      return html`

Loading...

      `;
    }
    if (this.features.length == 0) {
      return html`

${this.noResultsMessage}

      `;
    }
    return nothing;
  }

  openApprovalsDialog(featureId) {
    // handled in chromedash-myfeatures.js
    this._fireEvent('open-approvals-event', {
      featureId: featureId,
    });
  }

  doLGTM(featureId) {
    // TODO(jrobbins): Make it pre-select Approved and add comment.
    this.openApprovalsDialog(featureId);
  }

  doSnooze(featureId) {
    // TODO(jrobbins): Make it pre-set a new next-review-date value.
    this.openApprovalsDialog(featureId);
  }

  renderApprovalsIcon(feature) {
    return html`
       this.openApprovalsDialog(feature.id)}"
        title="Review approvals">
        <iron-icon icon="chromestatus:approval"></iron-icon>

    `;
  }

  renderEditIcon(feature) {
    return html`

        <iron-icon icon="chromestatus:create"></iron-icon>

    `;
  }

  renderStarIcon(feature) {
    return html`

        <iron-icon
          icon="${this.starredFeatures.has(Number(feature.id)) ?
          'chromestatus:star' :
          'chromestatus:star-border'}"
          class="pushicon"
          data-feature-id="${feature.id}"
          @click="${this.toggleStar}">
        </iron-icon>

    `;
  }

  renderSignedOutStarIcon() {
    return html`

          <iron-icon icon="chromestatus:star-border"
            class="pushicon">
          </iron-icon>

    `;
  }

  renderIcons(feature) {
    if (this.signedIn) {
      return html`
        ${this.canApprove ? this.renderApprovalsIcon(feature) : nothing}
        ${this.canEdit ? this.renderEditIcon(feature) : nothing}
        ${this.renderStarIcon(feature)}
      `;
    } else {
      return html`
        ${this.renderSignedOutStarIcon()}
      `;
    }
  }

  renderQuickActions(feature) {
    if (this.columns == 'approvals') {
      // TODO(jrobbins): Show only thread link for active intent.
      // Blocked on merge of PR that adds fetching that info.
      // Work around unused function parameter lint error.
      const threadLinks = feature ? [] : [];

      // TODO(jrobbins): Show these buttons when they work.
      // let lgtmButton = html`
      //  <button data-feature-id="${feature.id}"
      //          @click="${() => this.doLGTM(feature.id)}">
      //    Add LGTM
      //  </button>
      // `;
      // let snoozeButton = html`
      //  <button data-feature-id="${feature.id}"
      //          @click="${() => this.doSnooze(feature.id)}">
      //    Snooze
      //  </button>
      // `;

      return html`

          ${threadLinks}

      `;
    }
    return nothing;
  }

  getEarliestReviewDate(feature) {
    const configs = this.configs[feature.id];
    const allDates = configs.map(c => c.next_action).filter(d => d);
    if (allDates.length > 0) {
      allDates.sort();
      return allDates[0];
    }
    return null;
  }

  getActiveOwners(feature) {
    const featureConfigs = this.configs[feature.id];
    const allOwners = featureConfigs.map(c => c.owners).flat();
    // TODO(jrobbins): Limit to only owners of active intents
    let activeOwners = allOwners;
    activeOwners = [...new Set(activeOwners)]; // de-dup.
    activeOwners.sort();
    return activeOwners;
  }

  getActiveApprovals(feature) {
    const featureApprovals = this.approvals[feature.id];
    // TODO(jrobbins): Limit to only owners of active intents
    const activeApprovals = featureApprovals;
    return activeApprovals;
  }

  getRecentComment(feature) {
    // TODO(jrobbins): implement this.
    return feature ? null : null;
  }

  renderApprovalsSoFar(approvals) {
    const result = [];
    for (const stateItem of STATE_NAMES) {
      const state = stateItem[0];
      const stateName = stateItem[1];
      const approvalsWithThatState = approvals.filter(a => a.state == state);
      const setters = approvalsWithThatState.map(a => a.set_by.split('@')[0]);
      if (setters.length > 0) {
        result.push(html`<span>${stateName}: ${setters.join(', ')}. </span>`);
      }
    }
    return result;
  }

  renderHighlights(feature) {
    if (this.columns == 'approvals') {
      const nextReviewDate = this.getEarliestReviewDate(feature);
      const owners = this.getActiveOwners(feature);
      const activeApprovals = this.getActiveApprovals(feature);
      const recentComment = this.getRecentComment(feature);
      // TODO(jrobbins): show additional_review.

      return html`

          ${nextReviewDate ? html`

              Next review date: ${nextReviewDate}

            ` : nothing}
          ${owners.length == 1 ? html`

              Owner: ${owners[0]}

            ` : nothing}
          ${owners.length > 1 ? html`

              Owners: ${owners.join(', ')}

            ` : nothing}
          ${activeApprovals.length > 0 ? html`

              ${this.renderApprovalsSoFar(activeApprovals)}

            ` : nothing}
          ${recentComment ? html`

              Comment: ${recentComment.content}

            ` : nothing}

      `;
    }
    return nothing;
  }

  renderFeature(feature) {
    return html`

          ${this.renderQuickActions(feature)}
          ${feature.name}
          ${this.renderHighlights(feature)}

          ${this.renderIcons(feature)}

    `;
  }

  render() {
    return html`

        ${this.features.map(this.renderFeature.bind(this))}
        ${this.renderMessages()}

    `;
  }
}

customElements.define('chromedash-feature-table', ChromedashFeatureTable);
<commit_msg>Avoid a JS error for pending approvals without a config. (#1788)<commit_after>import {LitElement, css, html, nothing} from 'lit';
import SHARED_STYLES from '../css/shared.css';
import {STATE_NAMES} from './chromedash-approvals-dialog.js';

class ChromedashFeatureTable extends LitElement {
  static get properties() {
    return {
      query: {type: String},
      features: {type: Array},
      loading: {type: Boolean},
      rows: {type: Number},
      columns: {type: String},
      signedIn: {type: Boolean},
      canEdit: {type: Boolean},
      canApprove: {type: Boolean},
      starredFeatures: {type: Object},
      noResultsMessage: {type: String},
      approvals: {type: Object},
      comments: {type: Object},
      configs: {type: Object},
    };
  }

  constructor() {
    super();
    this.loading = true;
    this.starredFeatures = new Set();
    this.features = [];
    this.noResultsMessage = 'No results';
    this.canEdit = false;
    this.canApprove = false;
    this.approvals = {};
    this.comments = {};
    this.configs = {};
  }

  connectedCallback() {
    super.connectedCallback();
    window.csClient.searchFeatures(this.query).then((features) => {
      this.features = features;
      this.loading = false;
      if (this.columns == 'approvals') {
        this.loadApprovalData();
      }
    });
  }

  loadApprovalData() {
    for (const feature of this.features) {
      window.csClient.getApprovals(feature.id).then(res => {
        const newApprovals = {...this.approvals};
        newApprovals[feature.id] = res.approvals;
        this.approvals = newApprovals;
      });
      window.csClient.getComments(feature.id).then(res => {
        const newComments = {...this.comments};
        newComments[feature.id] = res.comments;
        this.comments = newComments;
      });
      window.csClient.getApprovalConfigs(feature.id).then(res => {
        const newConfigs = {...this.configs};
        newConfigs[feature.id] = res.configs;
        this.configs = newConfigs;
      });
    }
  }

  static get styles() {
    return [
      SHARED_STYLES,
      css`
      table {
        width: var(--max-content-width);
      }
      tr {
        background: var(--table-row-background);
      }
      td {
        padding: var(--content-padding-half);
        border-bottom: var(--table-divider);
      }
      td.name_col {
        width: 100%;
      }
      td.icon_col {
        white-space: nowrap;
        vertical-align: top;
      }
      .quick_actions {
        white-space: nowrap;
        float: right;
      }
      .highlights {
        padding-left: var(--content-padding);
      }
      .highlights div {
        color: var(--unimportant-text-color);
        padding: var(--content-padding-quarter);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      iron-icon {
        --iron-icon-height: 18px;
        --iron-icon-width: 18px;
        color: var(--link-color);
      }
      iron-icon:hover {
        color: var(--link-hover-color);
      }
      button {
        border: var(--default-border);
        padding: 0 6px;
        font-size: var(--button-small-font-size);
      }
    `];
  }

  _fireEvent(eventName, detail) {
    const event = new CustomEvent(eventName, {
      bubbles: true,
      composed: true,
      detail,
    });
    this.dispatchEvent(event);
  }

  toggleStar(e) {
    console.log('toggleStar');
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target;
    const featureId = Number(iconEl.dataset.featureId);
    const newStarred = !this.starredFeatures.has(featureId);

    // handled in chromedash-myfeatures.js
    this._fireEvent('star-toggle-event', {
      featureId: featureId,
      doStar: newStarred,
    });
  }

  renderMessages() {
    if (this.loading) {
      return html`

Loading...

      `;
    }
    if (this.features.length == 0) {
      return html`

${this.noResultsMessage}

      `;
    }
    return nothing;
  }

  openApprovalsDialog(featureId) {
    // handled in chromedash-myfeatures.js
    this._fireEvent('open-approvals-event', {
      featureId: featureId,
    });
  }

  doLGTM(featureId) {
    // TODO(jrobbins): Make it pre-select Approved and add comment.
    this.openApprovalsDialog(featureId);
  }

  doSnooze(featureId) {
    // TODO(jrobbins): Make it pre-set a new next-review-date value.
    this.openApprovalsDialog(featureId);
  }

  renderApprovalsIcon(feature) {
    return html`
       this.openApprovalsDialog(feature.id)}"
        title="Review approvals">
        <iron-icon icon="chromestatus:approval"></iron-icon>

    `;
  }

  renderEditIcon(feature) {
    return html`

        <iron-icon icon="chromestatus:create"></iron-icon>

    `;
  }

  renderStarIcon(feature) {
    return html`

        <iron-icon
          icon="${this.starredFeatures.has(Number(feature.id)) ?
          'chromestatus:star' :
          'chromestatus:star-border'}"
          class="pushicon"
          data-feature-id="${feature.id}"
          @click="${this.toggleStar}">
        </iron-icon>

    `;
  }

  renderSignedOutStarIcon() {
    return html`

          <iron-icon icon="chromestatus:star-border"
            class="pushicon">
          </iron-icon>

    `;
  }

  renderIcons(feature) {
    if (this.signedIn) {
      return html`
        ${this.canApprove ? this.renderApprovalsIcon(feature) : nothing}
        ${this.canEdit ? this.renderEditIcon(feature) : nothing}
        ${this.renderStarIcon(feature)}
      `;
    } else {
      return html`
        ${this.renderSignedOutStarIcon()}
      `;
    }
  }

  renderQuickActions(feature) {
    if (this.columns == 'approvals') {
      // TODO(jrobbins): Show only thread link for active intent.
      // Blocked on merge of PR that adds fetching that info.
      // Work around unused function parameter lint error.
      const threadLinks = feature ? [] : [];

      // TODO(jrobbins): Show these buttons when they work.
      // let lgtmButton = html`
      //  <button data-feature-id="${feature.id}"
      //          @click="${() => this.doLGTM(feature.id)}">
      //    Add LGTM
      //  </button>
      // `;
      // let snoozeButton = html`
      //  <button data-feature-id="${feature.id}"
      //          @click="${() => this.doSnooze(feature.id)}">
      //    Snooze
      //  </button>
      // `;

      return html`

          ${threadLinks}

      `;
    }
    return nothing;
  }

  getEarliestReviewDate(feature) {
    const featureConfigs = this.configs[feature.id] || [];
    const allDates = featureConfigs.map(c => c.next_action).filter(d => d);
    if (allDates.length > 0) {
      allDates.sort();
      return allDates[0];
    }
    return null;
  }

  getActiveOwners(feature) {
    const featureConfigs = this.configs[feature.id] || [];
    const allOwners = featureConfigs.map(c => c.owners).flat();
    // TODO(jrobbins): Limit to only owners of active intents
    let activeOwners = allOwners;
    activeOwners = [...new Set(activeOwners)]; // de-dup.
    activeOwners.sort();
    return activeOwners;
  }

  getActiveApprovals(feature) {
    const featureApprovals = this.approvals[feature.id];
    // TODO(jrobbins): Limit to only owners of active intents
    const activeApprovals = featureApprovals;
    return activeApprovals;
  }

  getRecentComment(feature) {
    // TODO(jrobbins): implement this.
    return feature ? null : null;
  }

  renderApprovalsSoFar(approvals) {
    const result = [];
    for (const stateItem of STATE_NAMES) {
      const state = stateItem[0];
      const stateName = stateItem[1];
      const approvalsWithThatState = approvals.filter(a => a.state == state);
      const setters = approvalsWithThatState.map(a => a.set_by.split('@')[0]);
      if (setters.length > 0) {
        result.push(html`<span>${stateName}: ${setters.join(', ')}. </span>`);
      }
    }
    return result;
  }

  renderHighlights(feature) {
    if (this.columns == 'approvals') {
      const nextReviewDate = this.getEarliestReviewDate(feature);
      const owners = this.getActiveOwners(feature);
      const activeApprovals = this.getActiveApprovals(feature);
      const recentComment = this.getRecentComment(feature);
      // TODO(jrobbins): show additional_review.

      return html`

          ${nextReviewDate ? html`

              Next review date: ${nextReviewDate}

            ` : nothing}
          ${owners.length == 1 ? html`

              Owner: ${owners[0]}

            ` : nothing}
          ${owners.length > 1 ? html`

              Owners: ${owners.join(', ')}

            ` : nothing}
          ${activeApprovals && activeApprovals.length > 0 ? html`

              ${this.renderApprovalsSoFar(activeApprovals)}

            ` : nothing}
          ${recentComment ? html`

              Comment: ${recentComment.content}

            ` : nothing}

      `;
    }
    return nothing;
  }

  renderFeature(feature) {
    return html`

          ${this.renderQuickActions(feature)}
          ${feature.name}
          ${this.renderHighlights(feature)}

          ${this.renderIcons(feature)}

    `;
  }

  render() {
    return html`

        ${this.features.map(this.renderFeature.bind(this))}
        ${this.renderMessages()}

    `;
  }
}

customElements.define('chromedash-feature-table', ChromedashFeatureTable);
<|endoftext|>


<commit_before>$(document).ready(function () {
    var pathname = getPathname();
    var ul = $("nav[role='navigation'] ul").eq(0);

    var allMenu = ul.find("li").find("a");
    allMenu.splice(0, 2);

    var indexOfCurrentMenu = findIndexOf(allMenu, pathname);
    var prevRef = (pathname === "/" || indexOfCurrentMenu === 0) ? null : allMenu.eq(indexOfCurrentMenu - 1);
    var nextRef = (indexOfCurrentMenu === allMenu.length - 1) ? null : allMenu.eq(indexOfCurrentMenu + 1);

    console.log(indexOfCurrentMenu);
    console.log("Previous", prevRef ? prevRef.attr("href") : null);
    console.log("Next", nextRef ? nextRef.attr("href") : null);

    updateNavigationLink($(".navigation-prev"), prevRef);
    updateNavigationLink($(".navigation-next"), nextRef);

});

function getPathname() {
    var currentHref = $(location).attr("href");
    var element = $('<a>', {
        href: currentHref
    });

    var pathname = element.prop('pathname');
    if (currentHref.indexOf("localhost:1313") >= 0) {
        return pathname;
    }
    return pathname.replace("/" + element.prop('pathname').split("/")[1], "")
}

function updateNavigationLink(linkToUpdate, refElem) {
    if (refElem) {
        linkToUpdate.attr("href", refElem.attr("href"));
        linkToUpdate.attr("aria-label", refElem.text());
        linkToUpdate.show();
    } else {
        linkToUpdate.hide();
    }
}

function findIndexOf(list, pathToFind) {
    for (var i = 0; i < list.length; i++) {
        if (list[i].getAttribute("href").indexOf(pathToFind) !== -1) {
            return i;
        }
    }
    return -1;
}<commit_msg>Next nd previous should be at there respective ends on the first and last links<commit_after>$(document).ready(function () {
    var pathname = getPathname();
    var ul = $("nav[role='navigation'] ul").eq(0);

    var allMenu = ul.find("li").find("a");
    allMenu.splice(0, 2);

    var indexOfCurrentMenu = findIndexOf(allMenu, pathname);
    var prevRef = (pathname === "/" || indexOfCurrentMenu === 0) ? null : allMenu.eq(indexOfCurrentMenu - 1);
    var nextRef = (indexOfCurrentMenu === allMenu.length - 1) ? null : allMenu.eq(indexOfCurrentMenu + 1);

    updateNavigationLink($(".navigation-prev"), prevRef);
    updateNavigationLink($(".navigation-next"), nextRef);

});

function getPathname() {
    var currentHref = $(location).attr("href");
    var element = $('<a>', {
        href: currentHref
    });

    var pathname = element.prop('pathname');
    if (currentHref.indexOf("localhost:1313") >= 0) {
        return pathname;
    }
    return pathname.replace("/" + element.prop('pathname').split("/")[1], "")
}

function updateNavigationLink(linkToUpdate, refElem) {
    if (refElem) {
        linkToUpdate.attr("href", refElem.attr("href"));
        linkToUpdate.attr("aria-label", refElem.text());
        linkToUpdate.css('visibility', 'visible');
    } else {
        linkToUpdate.css('visibility', 'hidden');
    }
}

function findIndexOf(list, pathToFind) {
    for (var i = 0; i < list.length; i++) {
        if (list[i].getAttribute("href").indexOf(pathToFind) !== -1) {
            return i;
        }
    }
    return -1;
}<|endoftext|>


<commit_before>import * as assert2 from "../base/assert2.js";
import * as init from '../base/init.js';
import * as config from '../base/config.js';
import * as expb from '../express/express-base.js';
import * as db from '../db/db.js';

import "../post/post-search";
import "../post/post-update";
import "../post/post-new";
import "../post/post-view";
import "../post/post-list";
import "../user/user-base";

process.on('SIGINT', function() {
  db.close(function(err) {
    console.log("SIGINT caught");
    process.exit(err ? 1 : 0);
  });
});

init.add((done) => {
  expb.start();
  done();
});

init.run();

<commit_msg>fix main.js.<commit_after>import * as assert2 from "../base/assert2.js";
import * as init from '../base/init.js';
import * as config from '../base/config.js';
import * as expb from '../express/express-base.js';
import * as db from '../db/db.js';

import "../post/post-search.js";
import "../post/post-update.js";
import "../post/post-new.js";
import "../post/post-view.js";
import "../post/post-list.js";
import "../user/user-base.js";

process.on('SIGINT', function() {
  db.close(function(err) {
    console.log("SIGINT caught");
    process.exit(err ? 1 : 0);
  });
});

init.add((done) => {
  expb.start();
  done();
});

init.run();

<|endoftext|>


<commit_before>const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    devtool: 'source-map',
    entry: {
        'main': './main.ts'
    },
    module: {
        loaders: [
            {test: /\.css$/, loader: 'raw-loader'},
            {test: /\.html$/, loader: 'raw-loader'},
            {test: /\.ts$/, loader: 'ts-loader'}
        ]
    },
        output: {
        path: './dist',
        filename: 'bundle.js'
    },
    plugins: [
        new CopyWebpackPlugin(
            [
                {
                    from: './index.html',
                    to: 'index.html'
                }
            ]
        ),
    ],
  resolve: {
    extensions: ['.ts', '.js']
  }
};
<commit_msg>Build finishes<commit_after>const path = require('path');
var webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    devtool: 'source-map',
    entry: {
        'main': './main.ts'
    },
    module: {
        loaders: [
            {test: /\.css$/, loader: 'raw-loader'},
            {test: /\.html$/, loader: 'raw-loader'},
            {test: /\.ts$/, loader: 'ts-loader'},
            {test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: 'url-loader'}
        ]
    },
        output: {
        path: './dist',
        filename: 'bundle.js'
    },
    plugins: [
        new CopyWebpackPlugin(
            [
                {
                    from: './index.html',
                    to: 'index.html'
                }
            ]
        ),
        new webpack.ProvidePlugin(
            {
                jQuery: 'jquery',
                $: 'jquery',
                jquery: 'jquery'
            }
        )
    ],
  resolve: {
    extensions: ['.ts', '.js']
  }
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require( 'gulp' );
var $ = require( 'gulp-load-plugins' )();
var pkg = require( '../config' ).pkg;
var banner = require( '../config' ).banner;
var config = require( '../config' ).scripts;
var handleErrors = require( '../utils/handleErrors' );
var browserSync = require( 'browser-sync' );

gulp.task( 'scripts', function() {
  return gulp.src( config.src )
    .pipe( $.sourcemaps.init() )
    .pipe( $.webpack() )
    .pipe( $.uglify() )
    .on( 'error', handleErrors )
    .pipe( $.header( banner, { pkg: pkg } ) )
    .pipe( $.rename( {
      suffix: ".min"
    } ) )
    .pipe( $.sourcemaps.write( '.' ) )
    .pipe( gulp.dest( config.dest ) )
    .pipe( browserSync.reload( {
      stream: true
    } ) );
} );
<commit_msg>Update webpack settings to retain filename<commit_after>'use strict';

var gulp = require( 'gulp' );
var $ = require( 'gulp-load-plugins' )();
var pkg = require( '../config' ).pkg;
var banner = require( '../config' ).banner;
var config = require( '../config' ).scripts;
var handleErrors = require( '../utils/handleErrors' );
var browserSync = require( 'browser-sync' );

gulp.task( 'scripts', function() {
  return gulp.src( config.src )
    .pipe( $.sourcemaps.init() )
    .pipe( $.webpack( {
      output: {
        filename: '[name].js'
      }
    } ) )
    .pipe( $.uglify() )
    .on( 'error', handleErrors )
    .pipe( $.header( banner, { pkg: pkg } ) )
    .pipe( $.rename( {
      suffix: '.min'
    } ) )
    .pipe( $.sourcemaps.write( '.' ) )
    .pipe( gulp.dest( config.dest ) )
    .pipe( browserSync.reload( {
      stream: true
    } ) );
} );
<|endoftext|>


<commit_before>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.224 2004/02/09 02:30:06 chregu Exp $

const BXE_VERSION = "0.9.1";
const BXE_BUILD = "200402090330"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.225 2004/02/10 02:30:04 chregu Exp $

const BXE_VERSION = "0.9.1";
const BXE_BUILD = "200402100330"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>


<commit_before>define(["handlebars"], function(Handlebars) {
    function collectionTimes(string) {
        // Function that takes a collection times string and returns a 'true' if
        // it has been collected today else 'false'
        if(!string) {
            return "";
        }
        try {
            result = TimeDomain.evaluateNextTime(string);
        } catch (err) {
            console.log(err);
            return "";
        }
        if(result.value === true) {
            return "collected";
        } else {
            return "not yet collected";
        }
    }
    Handlebars.registerHelper('collectionTimes', collectionTimes);
    return collectionTimes;
});<commit_msg>Places / display "not collected" postboxes in green and "collected" in red (TRELLO#110).<commit_after>define(["handlebars"], function(Handlebars) {
    function collectionTimes(string) {
        // Function that takes a collection times string and returns a 'true' if
        // it has been collected today else 'false'
        if(!string) {
            return "";
        }
        try {
            result = TimeDomain.evaluateNextTime(string);
        } catch (err) {
            console.log(err);
            return "";
        }
        if(result.value === true) {
            return "collected";
        } else {
            return "not yet collected";
        }
    }
    Handlebars.registerHelper('collectionTimes', collectionTimes);
    return collectionTimes;
});<|endoftext|>


<commit_before>var kanso = require('kanso');

exports.rewrites = [
    {from: '/static/*', to: 'static/jquery-1.4.2.min.js'},
    {from: '/', to: '_show/welcome'}
];

exports.shows = {
    welcome: function (doc, req) {
        return kanso.template(req, 'welcome.html', {});
    }
};
<commit_msg>update base project template to be more client-side friendly<commit_after>var kanso = require('kanso');

exports.rewrites = [
    {from: '/static/*', to: 'static/jquery-1.4.2.min.js'},
    {from: '/', to: '_show/welcome'}
];

exports.shows = {
    welcome: function (doc, req) {
        var content = kanso.template(req, 'welcome.html', {});

        if (req.client) {
            $('#content').html(content);
        }
        else {
            return kanso.template(req, 'base.html', {
                title: 'It worked!',
                content: content
            });
        }
    }
};
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

(function () {

var monitor = function (temporalConstraint) {

    var self = this
    this.temporalConstraint = temporalConstraint
    this.sequence = temporalConstraint.constraintBody.sequence
    this.filters = {}
    this.buffer = {}
    this.link = temporalConstraint.constraintBody.link

    var isLast = function (participant) {
        return _.findIndex(self.sequence, function (part) { return part === participant }) === (self.sequence.length - 1)
    }
    _.each(temporalConstraint.constraintBody.filters, function (filter) {
        this.filters[filter.id] = filter
    }, this)

    _.each(this.sequence, function (participant) {
        if (!isLast(participant))
            this.buffer[participant] = []
    }, this)

    var predIsAvailable = function (current) {
        var idx = _.findIndex(self.sequence, function (participant) { return participant === current })
        for (var i = idx - 1; i >= 0; i--)
            if (self.buffer[self.sequence[i]].length === 0)
                return false
        return true
    }

    var cartesian = function (arrays, callback) {
        var result = [], max = arrays.length - 1
        var finished = false
        function helper (acc, i) {
            if (finished)
                return
            for (var x = 0; x < arrays[i].length; x++) {
                var newAry = acc.slice(0)
                newAry.push(arrays[i][x])
                if (i === max) {
                    if (callback(newAry)) {
                        finished = true
                        break;
                    }
                }
                else
                    helper(newAry, i + 1)
            }
        }

        helper([], 0)
        return result
    }

    var checkLink = function (trace) {
        var found = false
        var bags = _.values(self.buffer)
        cartesian(bags, function (permutation) {
            var ctx = {}
            _.each(permutation, function (trace) {
                ctx[trace.member] = trace
            })
            ctx[_.last(self.sequence)] = trace
            if (trace.evaluateExpr(self.link.condition, ctx)) {
                found = true
                return false
            }
        })
        return found
    }

    this.processTerminate = function (trace) {
        var result = []
        var filter = this.filters[this.sequence[this.sequence.length - 1]]
        var res = trace.evaluateExpr(filter.condition)
        if (res) {
            if (_.filter(self.buffer, function (buf) { return buf.length !== 0 }).length === 0)
                return
            if (!predIsAvailable(filter.id) || (isLast(filter.id) && !checkLink(trace))) {
                _.forIn(self.buffer, function (value) {
                    _.each(value, function (tr) {
                        tr.checks = [{
                            constraint: temporalConstraint,
                            subs: [],
                            result: 'FAIL'
                        }]
                        result.push(tr)
                    })
                })
            }
        }

        return result
    }

    this.processTrace = function (trace) {
        var result = null
        /*  push each trace to the matching filters bag  */
        _.each(this.filters, function (filter) {
            var res = trace.evaluateExpr(filter.condition)
            if (res) {
                if (!predIsAvailable(filter.id) || (isLast(filter.id) && !checkLink(trace))) {
                    trace.checks = [{
                        constraint: temporalConstraint,
                        subs: [],
                        result: 'FAIL'
                    }]
                    result = trace
                    return false
                }
                else {
                    if (!isLast(filter.id)) {
                        trace.member = filter.id
                        this.buffer[filter.id].push(trace)
                    }
                }
            }
        }, this)

        return result
    }
}

app.lib.happens_before_monitor = monitor

})()<commit_msg>Fixed processTerminate method<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

(function () {

var monitor = function (temporalConstraint) {

    var self = this
    this.temporalConstraint = temporalConstraint
    this.sequence = temporalConstraint.constraintBody.sequence
    this.filters = {}
    this.buffer = {}
    this.link = temporalConstraint.constraintBody.link

    var isLast = function (participant) {
        return _.findIndex(self.sequence, function (part) { return part === participant }) === (self.sequence.length - 1)
    }
    _.each(temporalConstraint.constraintBody.filters, function (filter) {
        this.filters[filter.id] = filter
    }, this)

    _.each(this.sequence, function (participant) {
        if (!isLast(participant))
            this.buffer[participant] = []
    }, this)

    var predIsAvailable = function (current) {
        var idx = _.findIndex(self.sequence, function (participant) { return participant === current })
        for (var i = idx - 1; i >= 0; i--)
            if (self.buffer[self.sequence[i]].length === 0)
                return false
        return true
    }

    var cartesian = function (arrays, callback) {
        var result = [], max = arrays.length - 1
        var finished = false
        function helper (acc, i) {
            if (finished)
                return
            for (var x = 0; x < arrays[i].length; x++) {
                var newAry = acc.slice(0)
                newAry.push(arrays[i][x])
                if (i === max) {
                    if (callback(newAry)) {
                        finished = true
                        break;
                    }
                }
                else
                    helper(newAry, i + 1)
            }
        }

        helper([], 0)
        return result
    }

    var checkLink = function (trace) {
        var found = false
        var bags = _.values(self.buffer)
        cartesian(bags, function (permutation) {
            var ctx = {}
            _.each(permutation, function (trace) {
                ctx[trace.member] = trace
            })
            ctx[_.last(self.sequence)] = trace
            if (trace.evaluateExpr(self.link.condition, ctx)) {
                found = true
                return false
            }
        })
        return found
    }

    this.processTerminate = function () {
        var result = []
        var last = _.last(self.sequence)
        if (last === 'terminate') {
            if (_.filter(self.buffer, function (buf) { return buf.length !== 0 }).length === 0)
                return
            self.sequence.reverse()
            self.sequence.splice(0,1)
            var traces = self.buffer[_.last(self.sequence)]
            _.each(traces, function (probe) {
                if (!predIsAvailable(_.last(self.sequence)) || !checkLink(probe)) {
                    probe.checks = [{
                        constraint: temporalConstraint,
                        subs: [],
                        result: 'FAIL'
                    }]
                    result.push(probe)
                }
            })
            self.sequence.reverse()
            self.sequence.push(last)
        }
        return result
    }

    this.processTrace = function (trace) {
        var result = null
        /*  push each trace to the matching filters bag  */
        _.each(this.filters, function (filter) {
            var res = trace.evaluateExpr(filter.condition)
            if (res) {
                if (!predIsAvailable(filter.id) || (isLast(filter.id) && !checkLink(trace))) {
                    trace.checks = [{
                        constraint: temporalConstraint,
                        subs: [],
                        result: 'FAIL'
                    }]
                    result = trace
                    return false
                }
                else {
                    if (!isLast(filter.id)) {
                        trace.member = filter.id
                        this.buffer[filter.id].push(trace)
                    }
                }
            }
        }, this)

        return result
    }
}

app.lib.happens_before_monitor = monitor

})()<|endoftext|>


<commit_before>/*globals global require __dirname BT */

require('blossom/buildtools'); // adds the SC and BT namespaces as globals

var path = require('path');

var project = BT.Project.create({

  "postbooks": BT.App.create({
    frameworks: 'blossom xm xt'.w(),
    sourceTree: path.join(__dirname, 'apps/postbooks')
  }),

  "console": BT.App.create({
    frameworks: 'blossom xm'.w(),
    sourceTree: path.join(__dirname, 'apps/console')
  }),

  "blossom": require('blossom'),
  "foundation": require('blossom/foundation'),
  "datastore": require('blossom/datastore'),

  "xm": require('./frameworks/xm/node/buildfile'),
  "xt": require('./frameworks/xt/node/buildfile'),

  "datasource": BT.Proxy.create({
     proxyHost: '127.0.0.1',
    //proxyHost: 'aurora.xtuple.com',
    proxyPort: 9000,
    proxyPrefix: '/'
  }),

  "data": BT.Proxy.create({
    // proxyHost: '127.0.0.1',
    proxyHost: 'aurora.xtuple.com',
    proxyPort: 9000,
    proxyPrefix: '/data'
  })
});

// project.accept(BT.LoggingVisitor.create());

BT.Server.create({
  project: project
});

// var project = BT.Project.create({
//   "postbooks": BT.App.create({
//     frameworks: 'foundation datastore xt'.w(),
//     sourceTree: path.join(__dirname, 'apps/postbooks')
//   }),
//   "foundation": require('blossom/foundation'),
//   "datastore": require('blossom/datastore'),
//   "xt": require('./frameworks/xt/node/buildfile')
// });
//
// // project.accept(BT.LoggingVisitor.create());
//
// BT.Server.create({
//   project: project
// });
//
// require('jsdom').defaultDocumentFeatures = {
//   FetchExternalResources   : ['script', 'img'],
//   ProcessExternalResources : false, // We load our code manually.
//   MutationEvents           : false,
//   QuerySelector            : false
// };
//
// var app = project.findApp('postbooks'),
//     jsFiles = [];
//
// function appendFile(file) {
//   jsFiles.push(file.get('sourcePath'));
//   // jsFiles.push("http://localhost:4020/" + file.get('targetPath'));
// }
//
// // First include our frameworks.
// app.get('orderedFrameworks').forEach(function(framework) {
//   framework.get('orderedJavaScriptFiles').forEach(appendFile);
// });
//
// // Then include the app itself.
// app.get('orderedJavaScriptFiles').forEach(appendFile);
//
// console.log(jsFiles);
//
// var jsdom = require('jsdom').jsdom,
//     document = jsdom(app.get('indexHTML')),
//     window = document.createWindow();
//
//     // set up so we don't need to change window everywhere by defining a reference to global
// global.window = window;
// global.document = document;
// global.top = window;
//
// global.navigator = { userAgent: "node-js", language: "en" };
//
// global.sc_require = function do_nothing(){};
// global.sc_resource = function sc_resource(){};
//
// global.YES = true ;
// global.NO = false ;
//
// global.SC = {};
// global.SproutCore = SC;
// global.SC.isNode = true;
//
// // use a node.js xmlhttprequest plugin
// global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
//
// // hack to get the node xmlhttprequest to work
// // msie cannot be true otherwise ready.js wont work properly and
// // node processes that use sproutnode won't exit
// SC.browser = { msie: false, opera: true };
//
// global.BLOSSOM = true;
// global.SPROUTCORE = false;
// global.FAST_LAYOUT_FUNCTION = false;
// global.sc_assert = function(assertion, msg) {
//   if (!assertion) throw msg || "sc_assert()";
// };
//
// jsFiles.forEach(function(path) { require(path); });
//
// console.log(window.document.innerHTML);
// console.log(window.XT.NAMESPACE);
<commit_msg>project_file<commit_after>/*globals global require __dirname BT */

require('blossom/buildtools'); // adds the SC and BT namespaces as globals

var path = require('path');

var project = BT.Project.create({

  "postbooks": BT.App.create({
    frameworks: 'blossom xm xt'.w(),
    sourceTree: path.join(__dirname, 'apps/postbooks')
  }),

  "console": BT.App.create({
    frameworks: 'blossom xm'.w(),
    sourceTree: path.join(__dirname, 'apps/console')
  }),

  "blossom": require('blossom'),
  "foundation": require('blossom/foundation'),
  "datastore": require('blossom/datastore'),

  "xm": require('./frameworks/xm/node/buildfile'),
  "xt": require('./frameworks/xt/node/buildfile'),

  "datasource": BT.Proxy.create({
     proxyHost: '127.0.0.1',
    //proxyHost: 'aurora.xtuple.com',
    proxyPort: 9000,
    proxyPrefix: '/'
  }),

  "data": BT.Proxy.create({
     proxyHost: '127.0.0.1',
   // proxyHost: 'aurora.xtuple.com',
    proxyPort: 9000,
    proxyPrefix: '/data'
  })
});

// project.accept(BT.LoggingVisitor.create());

BT.Server.create({
  project: project
});

// var project = BT.Project.create({
//   "postbooks": BT.App.create({
//     frameworks: 'foundation datastore xt'.w(),
//     sourceTree: path.join(__dirname, 'apps/postbooks')
//   }),
//   "foundation": require('blossom/foundation'),
//   "datastore": require('blossom/datastore'),
//   "xt": require('./frameworks/xt/node/buildfile')
// });
//
// // project.accept(BT.LoggingVisitor.create());
//
// BT.Server.create({
//   project: project
// });
//
// require('jsdom').defaultDocumentFeatures = {
//   FetchExternalResources   : ['script', 'img'],
//   ProcessExternalResources : false, // We load our code manually.
//   MutationEvents           : false,
//   QuerySelector            : false
// };
//
// var app = project.findApp('postbooks'),
//     jsFiles = [];
//
// function appendFile(file) {
//   jsFiles.push(file.get('sourcePath'));
//   // jsFiles.push("http://localhost:4020/" + file.get('targetPath'));
// }
//
// // First include our frameworks.
// app.get('orderedFrameworks').forEach(function(framework) {
//   framework.get('orderedJavaScriptFiles').forEach(appendFile);
// });
//
// // Then include the app itself.
// app.get('orderedJavaScriptFiles').forEach(appendFile);
//
// console.log(jsFiles);
//
// var jsdom = require('jsdom').jsdom,
//     document = jsdom(app.get('indexHTML')),
//     window = document.createWindow();
//
//     // set up so we don't need to change window everywhere by defining a reference to global
// global.window = window;
// global.document = document;
// global.top = window;
//
// global.navigator = { userAgent: "node-js", language: "en" };
//
// global.sc_require = function do_nothing(){};
// global.sc_resource = function sc_resource(){};
//
// global.YES = true ;
// global.NO = false ;
//
// global.SC = {};
// global.SproutCore = SC;
// global.SC.isNode = true;
//
// // use a node.js xmlhttprequest plugin
// global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
//
// // hack to get the node xmlhttprequest to work
// // msie cannot be true otherwise ready.js wont work properly and
// // node processes that use sproutnode won't exit
// SC.browser = { msie: false, opera: true };
//
// global.BLOSSOM = true;
// global.SPROUTCORE = false;
// global.FAST_LAYOUT_FUNCTION = false;
// global.sc_assert = function(assertion, msg) {
//   if (!assertion) throw msg || "sc_assert()";
// };
//
// jsFiles.forEach(function(path) { require(path); });
//
// console.log(window.document.innerHTML);
// console.log(window.XT.NAMESPACE);
<|endoftext|>


<commit_before>(function init() {
    const apiUrl = 'wss://ws.binaryws.com/websockets/v3';
    try {
        window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || {};
        window.BinaryBoot.connection = new WebSocket(apiUrl + '?l=' + window.BinaryBoot.language);
    } catch (e) {
        window.console.log('Error while initializing', e);
    }
}());
<commit_msg>Add app_id to connection<commit_after>(function init() {
    const apiUrl = 'wss://ws.binaryws.com/websockets/v3';
    try {
        window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || {};
        window.BinaryBoot.connection = new WebSocket(apiUrl + '?app_id=1006&l=' + window.BinaryBoot.language);
    } catch (e) {
        window.console.log('Error while initializing', e);
    }
}());
<|endoftext|>